* linux-nat.c (linux_nat_wait): Adjust.
[binutils-gdb.git] / gdb / remote.c
blobaeeb8b8a8730ed1a27fe6dbc9f649d4edcc79381
1 /* Remote target communications for serial-line targets in custom GDB protocol
3 Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
4 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009
5 Free Software Foundation, Inc.
7 This file is part of GDB.
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 3 of the License, or
12 (at your option) any later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with this program. If not, see <http://www.gnu.org/licenses/>. */
22 /* See the GDB User Guide for details of the GDB remote protocol. */
24 #include "defs.h"
25 #include "gdb_string.h"
26 #include <ctype.h>
27 #include <fcntl.h>
28 #include "inferior.h"
29 #include "bfd.h"
30 #include "symfile.h"
31 #include "exceptions.h"
32 #include "target.h"
33 /*#include "terminal.h" */
34 #include "gdbcmd.h"
35 #include "objfiles.h"
36 #include "gdb-stabs.h"
37 #include "gdbthread.h"
38 #include "remote.h"
39 #include "regcache.h"
40 #include "value.h"
41 #include "gdb_assert.h"
42 #include "observer.h"
43 #include "solib.h"
44 #include "cli/cli-decode.h"
45 #include "cli/cli-setshow.h"
46 #include "target-descriptions.h"
48 #include <ctype.h>
49 #include <sys/time.h>
51 #include "event-loop.h"
52 #include "event-top.h"
53 #include "inf-loop.h"
55 #include <signal.h>
56 #include "serial.h"
58 #include "gdbcore.h" /* for exec_bfd */
60 #include "remote-fileio.h"
61 #include "gdb/fileio.h"
62 #include "gdb_stat.h"
64 #include "memory-map.h"
66 /* The size to align memory write packets, when practical. The protocol
67 does not guarantee any alignment, and gdb will generate short
68 writes and unaligned writes, but even as a best-effort attempt this
69 can improve bulk transfers. For instance, if a write is misaligned
70 relative to the target's data bus, the stub may need to make an extra
71 round trip fetching data from the target. This doesn't make a
72 huge difference, but it's easy to do, so we try to be helpful.
74 The alignment chosen is arbitrary; usually data bus width is
75 important here, not the possibly larger cache line size. */
76 enum { REMOTE_ALIGN_WRITES = 16 };
78 /* Prototypes for local functions. */
79 static void cleanup_sigint_signal_handler (void *dummy);
80 static void initialize_sigint_signal_handler (void);
81 static int getpkt_sane (char **buf, long *sizeof_buf, int forever);
82 static int getpkt_or_notif_sane (char **buf, long *sizeof_buf,
83 int forever);
85 static void handle_remote_sigint (int);
86 static void handle_remote_sigint_twice (int);
87 static void async_remote_interrupt (gdb_client_data);
88 void async_remote_interrupt_twice (gdb_client_data);
90 static void remote_files_info (struct target_ops *ignore);
92 static void remote_prepare_to_store (struct regcache *regcache);
94 static void remote_fetch_registers (struct regcache *regcache, int regno);
96 static void remote_resume (ptid_t ptid, int step,
97 enum target_signal siggnal);
98 static void remote_open (char *name, int from_tty);
100 static void extended_remote_open (char *name, int from_tty);
102 static void remote_open_1 (char *, int, struct target_ops *, int extended_p);
104 static void remote_close (int quitting);
106 static void remote_store_registers (struct regcache *regcache, int regno);
108 static void remote_mourn (struct target_ops *ops);
110 static void extended_remote_restart (void);
112 static void extended_remote_mourn (struct target_ops *);
114 static void remote_mourn_1 (struct target_ops *);
116 static void remote_send (char **buf, long *sizeof_buf_p);
118 static int readchar (int timeout);
120 static void remote_kill (void);
122 static int tohex (int nib);
124 static int remote_can_async_p (void);
126 static int remote_is_async_p (void);
128 static void remote_async (void (*callback) (enum inferior_event_type event_type,
129 void *context), void *context);
131 static int remote_async_mask (int new_mask);
133 static void remote_detach (struct target_ops *ops, char *args, int from_tty);
135 static void remote_interrupt (int signo);
137 static void remote_interrupt_twice (int signo);
139 static void interrupt_query (void);
141 static void set_general_thread (struct ptid ptid);
142 static void set_continue_thread (struct ptid ptid);
144 static int remote_thread_alive (ptid_t);
146 static void get_offsets (void);
148 static void skip_frame (void);
150 static long read_frame (char **buf_p, long *sizeof_buf);
152 static int hexnumlen (ULONGEST num);
154 static void init_remote_ops (void);
156 static void init_extended_remote_ops (void);
158 static void remote_stop (ptid_t);
160 static int ishex (int ch, int *val);
162 static int stubhex (int ch);
164 static int hexnumstr (char *, ULONGEST);
166 static int hexnumnstr (char *, ULONGEST, int);
168 static CORE_ADDR remote_address_masked (CORE_ADDR);
170 static void print_packet (char *);
172 static unsigned long crc32 (unsigned char *, int, unsigned int);
174 static void compare_sections_command (char *, int);
176 static void packet_command (char *, int);
178 static int stub_unpack_int (char *buff, int fieldlength);
180 static ptid_t remote_current_thread (ptid_t oldptid);
182 static void remote_find_new_threads (void);
184 static void record_currthread (ptid_t currthread);
186 static int fromhex (int a);
188 static int hex2bin (const char *hex, gdb_byte *bin, int count);
190 static int bin2hex (const gdb_byte *bin, char *hex, int count);
192 static int putpkt_binary (char *buf, int cnt);
194 static void check_binary_download (CORE_ADDR addr);
196 struct packet_config;
198 static void show_packet_config_cmd (struct packet_config *config);
200 static void update_packet_config (struct packet_config *config);
202 static void set_remote_protocol_packet_cmd (char *args, int from_tty,
203 struct cmd_list_element *c);
205 static void show_remote_protocol_packet_cmd (struct ui_file *file,
206 int from_tty,
207 struct cmd_list_element *c,
208 const char *value);
210 static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
211 static ptid_t read_ptid (char *buf, char **obuf);
213 static void remote_query_supported (void);
215 static void remote_check_symbols (struct objfile *objfile);
217 void _initialize_remote (void);
219 struct stop_reply;
220 static struct stop_reply *stop_reply_xmalloc (void);
221 static void stop_reply_xfree (struct stop_reply *);
222 static void do_stop_reply_xfree (void *arg);
223 static void remote_parse_stop_reply (char *buf, struct stop_reply *);
224 static void push_stop_reply (struct stop_reply *);
225 static void remote_get_pending_stop_replies (void);
226 static void discard_pending_stop_replies (int pid);
227 static int peek_stop_reply (ptid_t ptid);
229 static void remote_async_inferior_event_handler (gdb_client_data);
230 static void remote_async_get_pending_events_handler (gdb_client_data);
232 static void remote_terminal_ours (void);
234 static int remote_read_description_p (struct target_ops *target);
236 /* The non-stop remote protocol provisions for one pending stop reply.
237 This is where we keep it until it is acknowledged. */
239 static struct stop_reply *pending_stop_reply = NULL;
241 /* For "remote". */
243 static struct cmd_list_element *remote_cmdlist;
245 /* For "set remote" and "show remote". */
247 static struct cmd_list_element *remote_set_cmdlist;
248 static struct cmd_list_element *remote_show_cmdlist;
250 /* Description of the remote protocol state for the currently
251 connected target. This is per-target state, and independent of the
252 selected architecture. */
254 struct remote_state
256 /* A buffer to use for incoming packets, and its current size. The
257 buffer is grown dynamically for larger incoming packets.
258 Outgoing packets may also be constructed in this buffer.
259 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
260 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
261 packets. */
262 char *buf;
263 long buf_size;
265 /* If we negotiated packet size explicitly (and thus can bypass
266 heuristics for the largest packet size that will not overflow
267 a buffer in the stub), this will be set to that packet size.
268 Otherwise zero, meaning to use the guessed size. */
269 long explicit_packet_size;
271 /* remote_wait is normally called when the target is running and
272 waits for a stop reply packet. But sometimes we need to call it
273 when the target is already stopped. We can send a "?" packet
274 and have remote_wait read the response. Or, if we already have
275 the response, we can stash it in BUF and tell remote_wait to
276 skip calling getpkt. This flag is set when BUF contains a
277 stop reply packet and the target is not waiting. */
278 int cached_wait_status;
280 /* True, if in no ack mode. That is, neither GDB nor the stub will
281 expect acks from each other. The connection is assumed to be
282 reliable. */
283 int noack_mode;
285 /* True if we're connected in extended remote mode. */
286 int extended;
288 /* True if the stub reported support for multi-process
289 extensions. */
290 int multi_process_aware;
292 /* True if we resumed the target and we're waiting for the target to
293 stop. In the mean time, we can't start another command/query.
294 The remote server wouldn't be ready to process it, so we'd
295 timeout waiting for a reply that would never come and eventually
296 we'd close the connection. This can happen in asynchronous mode
297 because we allow GDB commands while the target is running. */
298 int waiting_for_stop_reply;
300 /* True if the stub reports support for non-stop mode. */
301 int non_stop_aware;
303 /* True if the stub reports support for vCont;t. */
304 int support_vCont_t;
307 /* Returns true if the multi-process extensions are in effect. */
308 static int
309 remote_multi_process_p (struct remote_state *rs)
311 return rs->extended && rs->multi_process_aware;
314 /* This data could be associated with a target, but we do not always
315 have access to the current target when we need it, so for now it is
316 static. This will be fine for as long as only one target is in use
317 at a time. */
318 static struct remote_state remote_state;
320 static struct remote_state *
321 get_remote_state_raw (void)
323 return &remote_state;
326 /* Description of the remote protocol for a given architecture. */
328 struct packet_reg
330 long offset; /* Offset into G packet. */
331 long regnum; /* GDB's internal register number. */
332 LONGEST pnum; /* Remote protocol register number. */
333 int in_g_packet; /* Always part of G packet. */
334 /* long size in bytes; == register_size (target_gdbarch, regnum);
335 at present. */
336 /* char *name; == gdbarch_register_name (target_gdbarch, regnum);
337 at present. */
340 struct remote_arch_state
342 /* Description of the remote protocol registers. */
343 long sizeof_g_packet;
345 /* Description of the remote protocol registers indexed by REGNUM
346 (making an array gdbarch_num_regs in size). */
347 struct packet_reg *regs;
349 /* This is the size (in chars) of the first response to the ``g''
350 packet. It is used as a heuristic when determining the maximum
351 size of memory-read and memory-write packets. A target will
352 typically only reserve a buffer large enough to hold the ``g''
353 packet. The size does not include packet overhead (headers and
354 trailers). */
355 long actual_register_packet_size;
357 /* This is the maximum size (in chars) of a non read/write packet.
358 It is also used as a cap on the size of read/write packets. */
359 long remote_packet_size;
363 /* Handle for retreving the remote protocol data from gdbarch. */
364 static struct gdbarch_data *remote_gdbarch_data_handle;
366 static struct remote_arch_state *
367 get_remote_arch_state (void)
369 return gdbarch_data (target_gdbarch, remote_gdbarch_data_handle);
372 /* Fetch the global remote target state. */
374 static struct remote_state *
375 get_remote_state (void)
377 /* Make sure that the remote architecture state has been
378 initialized, because doing so might reallocate rs->buf. Any
379 function which calls getpkt also needs to be mindful of changes
380 to rs->buf, but this call limits the number of places which run
381 into trouble. */
382 get_remote_arch_state ();
384 return get_remote_state_raw ();
387 static int
388 compare_pnums (const void *lhs_, const void *rhs_)
390 const struct packet_reg * const *lhs = lhs_;
391 const struct packet_reg * const *rhs = rhs_;
393 if ((*lhs)->pnum < (*rhs)->pnum)
394 return -1;
395 else if ((*lhs)->pnum == (*rhs)->pnum)
396 return 0;
397 else
398 return 1;
401 static void *
402 init_remote_state (struct gdbarch *gdbarch)
404 int regnum, num_remote_regs, offset;
405 struct remote_state *rs = get_remote_state_raw ();
406 struct remote_arch_state *rsa;
407 struct packet_reg **remote_regs;
409 rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
411 /* Use the architecture to build a regnum<->pnum table, which will be
412 1:1 unless a feature set specifies otherwise. */
413 rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
414 gdbarch_num_regs (gdbarch),
415 struct packet_reg);
416 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
418 struct packet_reg *r = &rsa->regs[regnum];
420 if (register_size (gdbarch, regnum) == 0)
421 /* Do not try to fetch zero-sized (placeholder) registers. */
422 r->pnum = -1;
423 else
424 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
426 r->regnum = regnum;
429 /* Define the g/G packet format as the contents of each register
430 with a remote protocol number, in order of ascending protocol
431 number. */
433 remote_regs = alloca (gdbarch_num_regs (gdbarch)
434 * sizeof (struct packet_reg *));
435 for (num_remote_regs = 0, regnum = 0;
436 regnum < gdbarch_num_regs (gdbarch);
437 regnum++)
438 if (rsa->regs[regnum].pnum != -1)
439 remote_regs[num_remote_regs++] = &rsa->regs[regnum];
441 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
442 compare_pnums);
444 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
446 remote_regs[regnum]->in_g_packet = 1;
447 remote_regs[regnum]->offset = offset;
448 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
451 /* Record the maximum possible size of the g packet - it may turn out
452 to be smaller. */
453 rsa->sizeof_g_packet = offset;
455 /* Default maximum number of characters in a packet body. Many
456 remote stubs have a hardwired buffer size of 400 bytes
457 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
458 as the maximum packet-size to ensure that the packet and an extra
459 NUL character can always fit in the buffer. This stops GDB
460 trashing stubs that try to squeeze an extra NUL into what is
461 already a full buffer (As of 1999-12-04 that was most stubs). */
462 rsa->remote_packet_size = 400 - 1;
464 /* This one is filled in when a ``g'' packet is received. */
465 rsa->actual_register_packet_size = 0;
467 /* Should rsa->sizeof_g_packet needs more space than the
468 default, adjust the size accordingly. Remember that each byte is
469 encoded as two characters. 32 is the overhead for the packet
470 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
471 (``$NN:G...#NN'') is a better guess, the below has been padded a
472 little. */
473 if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
474 rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
476 /* Make sure that the packet buffer is plenty big enough for
477 this architecture. */
478 if (rs->buf_size < rsa->remote_packet_size)
480 rs->buf_size = 2 * rsa->remote_packet_size;
481 rs->buf = xrealloc (rs->buf, rs->buf_size);
484 return rsa;
487 /* Return the current allowed size of a remote packet. This is
488 inferred from the current architecture, and should be used to
489 limit the length of outgoing packets. */
490 static long
491 get_remote_packet_size (void)
493 struct remote_state *rs = get_remote_state ();
494 struct remote_arch_state *rsa = get_remote_arch_state ();
496 if (rs->explicit_packet_size)
497 return rs->explicit_packet_size;
499 return rsa->remote_packet_size;
502 static struct packet_reg *
503 packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
505 if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch))
506 return NULL;
507 else
509 struct packet_reg *r = &rsa->regs[regnum];
510 gdb_assert (r->regnum == regnum);
511 return r;
515 static struct packet_reg *
516 packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
518 int i;
519 for (i = 0; i < gdbarch_num_regs (target_gdbarch); i++)
521 struct packet_reg *r = &rsa->regs[i];
522 if (r->pnum == pnum)
523 return r;
525 return NULL;
528 /* FIXME: graces/2002-08-08: These variables should eventually be
529 bound to an instance of the target object (as in gdbarch-tdep()),
530 when such a thing exists. */
532 /* This is set to the data address of the access causing the target
533 to stop for a watchpoint. */
534 static CORE_ADDR remote_watch_data_address;
536 /* This is non-zero if target stopped for a watchpoint. */
537 static int remote_stopped_by_watchpoint_p;
539 static struct target_ops remote_ops;
541 static struct target_ops extended_remote_ops;
543 static int remote_async_mask_value = 1;
545 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
546 ``forever'' still use the normal timeout mechanism. This is
547 currently used by the ASYNC code to guarentee that target reads
548 during the initial connect always time-out. Once getpkt has been
549 modified to return a timeout indication and, in turn
550 remote_wait()/wait_for_inferior() have gained a timeout parameter
551 this can go away. */
552 static int wait_forever_enabled_p = 1;
555 /* This variable chooses whether to send a ^C or a break when the user
556 requests program interruption. Although ^C is usually what remote
557 systems expect, and that is the default here, sometimes a break is
558 preferable instead. */
560 static int remote_break;
562 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
563 remote_open knows that we don't have a file open when the program
564 starts. */
565 static struct serial *remote_desc = NULL;
567 /* This variable sets the number of bits in an address that are to be
568 sent in a memory ("M" or "m") packet. Normally, after stripping
569 leading zeros, the entire address would be sent. This variable
570 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
571 initial implementation of remote.c restricted the address sent in
572 memory packets to ``host::sizeof long'' bytes - (typically 32
573 bits). Consequently, for 64 bit targets, the upper 32 bits of an
574 address was never sent. Since fixing this bug may cause a break in
575 some remote targets this variable is principly provided to
576 facilitate backward compatibility. */
578 static int remote_address_size;
580 /* Temporary to track who currently owns the terminal. See
581 remote_terminal_* for more details. */
583 static int remote_async_terminal_ours_p;
585 /* The executable file to use for "run" on the remote side. */
587 static char *remote_exec_file = "";
590 /* User configurable variables for the number of characters in a
591 memory read/write packet. MIN (rsa->remote_packet_size,
592 rsa->sizeof_g_packet) is the default. Some targets need smaller
593 values (fifo overruns, et.al.) and some users need larger values
594 (speed up transfers). The variables ``preferred_*'' (the user
595 request), ``current_*'' (what was actually set) and ``forced_*''
596 (Positive - a soft limit, negative - a hard limit). */
598 struct memory_packet_config
600 char *name;
601 long size;
602 int fixed_p;
605 /* Compute the current size of a read/write packet. Since this makes
606 use of ``actual_register_packet_size'' the computation is dynamic. */
608 static long
609 get_memory_packet_size (struct memory_packet_config *config)
611 struct remote_state *rs = get_remote_state ();
612 struct remote_arch_state *rsa = get_remote_arch_state ();
614 /* NOTE: The somewhat arbitrary 16k comes from the knowledge (folk
615 law?) that some hosts don't cope very well with large alloca()
616 calls. Eventually the alloca() code will be replaced by calls to
617 xmalloc() and make_cleanups() allowing this restriction to either
618 be lifted or removed. */
619 #ifndef MAX_REMOTE_PACKET_SIZE
620 #define MAX_REMOTE_PACKET_SIZE 16384
621 #endif
622 /* NOTE: 20 ensures we can write at least one byte. */
623 #ifndef MIN_REMOTE_PACKET_SIZE
624 #define MIN_REMOTE_PACKET_SIZE 20
625 #endif
626 long what_they_get;
627 if (config->fixed_p)
629 if (config->size <= 0)
630 what_they_get = MAX_REMOTE_PACKET_SIZE;
631 else
632 what_they_get = config->size;
634 else
636 what_they_get = get_remote_packet_size ();
637 /* Limit the packet to the size specified by the user. */
638 if (config->size > 0
639 && what_they_get > config->size)
640 what_they_get = config->size;
642 /* Limit it to the size of the targets ``g'' response unless we have
643 permission from the stub to use a larger packet size. */
644 if (rs->explicit_packet_size == 0
645 && rsa->actual_register_packet_size > 0
646 && what_they_get > rsa->actual_register_packet_size)
647 what_they_get = rsa->actual_register_packet_size;
649 if (what_they_get > MAX_REMOTE_PACKET_SIZE)
650 what_they_get = MAX_REMOTE_PACKET_SIZE;
651 if (what_they_get < MIN_REMOTE_PACKET_SIZE)
652 what_they_get = MIN_REMOTE_PACKET_SIZE;
654 /* Make sure there is room in the global buffer for this packet
655 (including its trailing NUL byte). */
656 if (rs->buf_size < what_they_get + 1)
658 rs->buf_size = 2 * what_they_get;
659 rs->buf = xrealloc (rs->buf, 2 * what_they_get);
662 return what_they_get;
665 /* Update the size of a read/write packet. If they user wants
666 something really big then do a sanity check. */
668 static void
669 set_memory_packet_size (char *args, struct memory_packet_config *config)
671 int fixed_p = config->fixed_p;
672 long size = config->size;
673 if (args == NULL)
674 error (_("Argument required (integer, `fixed' or `limited')."));
675 else if (strcmp (args, "hard") == 0
676 || strcmp (args, "fixed") == 0)
677 fixed_p = 1;
678 else if (strcmp (args, "soft") == 0
679 || strcmp (args, "limit") == 0)
680 fixed_p = 0;
681 else
683 char *end;
684 size = strtoul (args, &end, 0);
685 if (args == end)
686 error (_("Invalid %s (bad syntax)."), config->name);
687 #if 0
688 /* Instead of explicitly capping the size of a packet to
689 MAX_REMOTE_PACKET_SIZE or dissallowing it, the user is
690 instead allowed to set the size to something arbitrarily
691 large. */
692 if (size > MAX_REMOTE_PACKET_SIZE)
693 error (_("Invalid %s (too large)."), config->name);
694 #endif
696 /* Extra checks? */
697 if (fixed_p && !config->fixed_p)
699 if (! query (_("The target may not be able to correctly handle a %s\n"
700 "of %ld bytes. Change the packet size? "),
701 config->name, size))
702 error (_("Packet size not changed."));
704 /* Update the config. */
705 config->fixed_p = fixed_p;
706 config->size = size;
709 static void
710 show_memory_packet_size (struct memory_packet_config *config)
712 printf_filtered (_("The %s is %ld. "), config->name, config->size);
713 if (config->fixed_p)
714 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
715 get_memory_packet_size (config));
716 else
717 printf_filtered (_("Packets are limited to %ld bytes.\n"),
718 get_memory_packet_size (config));
721 static struct memory_packet_config memory_write_packet_config =
723 "memory-write-packet-size",
726 static void
727 set_memory_write_packet_size (char *args, int from_tty)
729 set_memory_packet_size (args, &memory_write_packet_config);
732 static void
733 show_memory_write_packet_size (char *args, int from_tty)
735 show_memory_packet_size (&memory_write_packet_config);
738 static long
739 get_memory_write_packet_size (void)
741 return get_memory_packet_size (&memory_write_packet_config);
744 static struct memory_packet_config memory_read_packet_config =
746 "memory-read-packet-size",
749 static void
750 set_memory_read_packet_size (char *args, int from_tty)
752 set_memory_packet_size (args, &memory_read_packet_config);
755 static void
756 show_memory_read_packet_size (char *args, int from_tty)
758 show_memory_packet_size (&memory_read_packet_config);
761 static long
762 get_memory_read_packet_size (void)
764 long size = get_memory_packet_size (&memory_read_packet_config);
765 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
766 extra buffer size argument before the memory read size can be
767 increased beyond this. */
768 if (size > get_remote_packet_size ())
769 size = get_remote_packet_size ();
770 return size;
774 /* Generic configuration support for packets the stub optionally
775 supports. Allows the user to specify the use of the packet as well
776 as allowing GDB to auto-detect support in the remote stub. */
778 enum packet_support
780 PACKET_SUPPORT_UNKNOWN = 0,
781 PACKET_ENABLE,
782 PACKET_DISABLE
785 struct packet_config
787 const char *name;
788 const char *title;
789 enum auto_boolean detect;
790 enum packet_support support;
793 /* Analyze a packet's return value and update the packet config
794 accordingly. */
796 enum packet_result
798 PACKET_ERROR,
799 PACKET_OK,
800 PACKET_UNKNOWN
803 static void
804 update_packet_config (struct packet_config *config)
806 switch (config->detect)
808 case AUTO_BOOLEAN_TRUE:
809 config->support = PACKET_ENABLE;
810 break;
811 case AUTO_BOOLEAN_FALSE:
812 config->support = PACKET_DISABLE;
813 break;
814 case AUTO_BOOLEAN_AUTO:
815 config->support = PACKET_SUPPORT_UNKNOWN;
816 break;
820 static void
821 show_packet_config_cmd (struct packet_config *config)
823 char *support = "internal-error";
824 switch (config->support)
826 case PACKET_ENABLE:
827 support = "enabled";
828 break;
829 case PACKET_DISABLE:
830 support = "disabled";
831 break;
832 case PACKET_SUPPORT_UNKNOWN:
833 support = "unknown";
834 break;
836 switch (config->detect)
838 case AUTO_BOOLEAN_AUTO:
839 printf_filtered (_("Support for the `%s' packet is auto-detected, currently %s.\n"),
840 config->name, support);
841 break;
842 case AUTO_BOOLEAN_TRUE:
843 case AUTO_BOOLEAN_FALSE:
844 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
845 config->name, support);
846 break;
850 static void
851 add_packet_config_cmd (struct packet_config *config, const char *name,
852 const char *title, int legacy)
854 char *set_doc;
855 char *show_doc;
856 char *cmd_name;
858 config->name = name;
859 config->title = title;
860 config->detect = AUTO_BOOLEAN_AUTO;
861 config->support = PACKET_SUPPORT_UNKNOWN;
862 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
863 name, title);
864 show_doc = xstrprintf ("Show current use of remote protocol `%s' (%s) packet",
865 name, title);
866 /* set/show TITLE-packet {auto,on,off} */
867 cmd_name = xstrprintf ("%s-packet", title);
868 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
869 &config->detect, set_doc, show_doc, NULL, /* help_doc */
870 set_remote_protocol_packet_cmd,
871 show_remote_protocol_packet_cmd,
872 &remote_set_cmdlist, &remote_show_cmdlist);
873 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
874 if (legacy)
876 char *legacy_name;
877 legacy_name = xstrprintf ("%s-packet", name);
878 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
879 &remote_set_cmdlist);
880 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
881 &remote_show_cmdlist);
885 static enum packet_result
886 packet_check_result (const char *buf)
888 if (buf[0] != '\0')
890 /* The stub recognized the packet request. Check that the
891 operation succeeded. */
892 if (buf[0] == 'E'
893 && isxdigit (buf[1]) && isxdigit (buf[2])
894 && buf[3] == '\0')
895 /* "Enn" - definitly an error. */
896 return PACKET_ERROR;
898 /* Always treat "E." as an error. This will be used for
899 more verbose error messages, such as E.memtypes. */
900 if (buf[0] == 'E' && buf[1] == '.')
901 return PACKET_ERROR;
903 /* The packet may or may not be OK. Just assume it is. */
904 return PACKET_OK;
906 else
907 /* The stub does not support the packet. */
908 return PACKET_UNKNOWN;
911 static enum packet_result
912 packet_ok (const char *buf, struct packet_config *config)
914 enum packet_result result;
916 result = packet_check_result (buf);
917 switch (result)
919 case PACKET_OK:
920 case PACKET_ERROR:
921 /* The stub recognized the packet request. */
922 switch (config->support)
924 case PACKET_SUPPORT_UNKNOWN:
925 if (remote_debug)
926 fprintf_unfiltered (gdb_stdlog,
927 "Packet %s (%s) is supported\n",
928 config->name, config->title);
929 config->support = PACKET_ENABLE;
930 break;
931 case PACKET_DISABLE:
932 internal_error (__FILE__, __LINE__,
933 _("packet_ok: attempt to use a disabled packet"));
934 break;
935 case PACKET_ENABLE:
936 break;
938 break;
939 case PACKET_UNKNOWN:
940 /* The stub does not support the packet. */
941 switch (config->support)
943 case PACKET_ENABLE:
944 if (config->detect == AUTO_BOOLEAN_AUTO)
945 /* If the stub previously indicated that the packet was
946 supported then there is a protocol error.. */
947 error (_("Protocol error: %s (%s) conflicting enabled responses."),
948 config->name, config->title);
949 else
950 /* The user set it wrong. */
951 error (_("Enabled packet %s (%s) not recognized by stub"),
952 config->name, config->title);
953 break;
954 case PACKET_SUPPORT_UNKNOWN:
955 if (remote_debug)
956 fprintf_unfiltered (gdb_stdlog,
957 "Packet %s (%s) is NOT supported\n",
958 config->name, config->title);
959 config->support = PACKET_DISABLE;
960 break;
961 case PACKET_DISABLE:
962 break;
964 break;
967 return result;
970 enum {
971 PACKET_vCont = 0,
972 PACKET_X,
973 PACKET_qSymbol,
974 PACKET_P,
975 PACKET_p,
976 PACKET_Z0,
977 PACKET_Z1,
978 PACKET_Z2,
979 PACKET_Z3,
980 PACKET_Z4,
981 PACKET_vFile_open,
982 PACKET_vFile_pread,
983 PACKET_vFile_pwrite,
984 PACKET_vFile_close,
985 PACKET_vFile_unlink,
986 PACKET_qXfer_auxv,
987 PACKET_qXfer_features,
988 PACKET_qXfer_libraries,
989 PACKET_qXfer_memory_map,
990 PACKET_qXfer_spu_read,
991 PACKET_qXfer_spu_write,
992 PACKET_qXfer_osdata,
993 PACKET_qGetTLSAddr,
994 PACKET_qSupported,
995 PACKET_QPassSignals,
996 PACKET_qSearch_memory,
997 PACKET_vAttach,
998 PACKET_vRun,
999 PACKET_QStartNoAckMode,
1000 PACKET_vKill,
1001 PACKET_MAX
1004 static struct packet_config remote_protocol_packets[PACKET_MAX];
1006 static void
1007 set_remote_protocol_packet_cmd (char *args, int from_tty,
1008 struct cmd_list_element *c)
1010 struct packet_config *packet;
1012 for (packet = remote_protocol_packets;
1013 packet < &remote_protocol_packets[PACKET_MAX];
1014 packet++)
1016 if (&packet->detect == c->var)
1018 update_packet_config (packet);
1019 return;
1022 internal_error (__FILE__, __LINE__, "Could not find config for %s",
1023 c->name);
1026 static void
1027 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1028 struct cmd_list_element *c,
1029 const char *value)
1031 struct packet_config *packet;
1033 for (packet = remote_protocol_packets;
1034 packet < &remote_protocol_packets[PACKET_MAX];
1035 packet++)
1037 if (&packet->detect == c->var)
1039 show_packet_config_cmd (packet);
1040 return;
1043 internal_error (__FILE__, __LINE__, "Could not find config for %s",
1044 c->name);
1047 /* Should we try one of the 'Z' requests? */
1049 enum Z_packet_type
1051 Z_PACKET_SOFTWARE_BP,
1052 Z_PACKET_HARDWARE_BP,
1053 Z_PACKET_WRITE_WP,
1054 Z_PACKET_READ_WP,
1055 Z_PACKET_ACCESS_WP,
1056 NR_Z_PACKET_TYPES
1059 /* For compatibility with older distributions. Provide a ``set remote
1060 Z-packet ...'' command that updates all the Z packet types. */
1062 static enum auto_boolean remote_Z_packet_detect;
1064 static void
1065 set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1066 struct cmd_list_element *c)
1068 int i;
1069 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1071 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
1072 update_packet_config (&remote_protocol_packets[PACKET_Z0 + i]);
1076 static void
1077 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1078 struct cmd_list_element *c,
1079 const char *value)
1081 int i;
1082 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1084 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
1088 /* Should we try the 'ThreadInfo' query packet?
1090 This variable (NOT available to the user: auto-detect only!)
1091 determines whether GDB will use the new, simpler "ThreadInfo"
1092 query or the older, more complex syntax for thread queries.
1093 This is an auto-detect variable (set to true at each connect,
1094 and set to false when the target fails to recognize it). */
1096 static int use_threadinfo_query;
1097 static int use_threadextra_query;
1099 /* Tokens for use by the asynchronous signal handlers for SIGINT. */
1100 static struct async_signal_handler *sigint_remote_twice_token;
1101 static struct async_signal_handler *sigint_remote_token;
1104 /* Asynchronous signal handle registered as event loop source for
1105 when we have pending events ready to be passed to the core. */
1107 static struct async_event_handler *remote_async_inferior_event_token;
1109 /* Asynchronous signal handle registered as event loop source for when
1110 the remote sent us a %Stop notification. The registered callback
1111 will do a vStopped sequence to pull the rest of the events out of
1112 the remote side into our event queue. */
1114 static struct async_event_handler *remote_async_get_pending_events_token;
1117 static ptid_t magic_null_ptid;
1118 static ptid_t not_sent_ptid;
1119 static ptid_t any_thread_ptid;
1121 /* These are the threads which we last sent to the remote system. The
1122 TID member will be -1 for all or -2 for not sent yet. */
1124 static ptid_t general_thread;
1125 static ptid_t continue_thread;
1127 static void
1128 notice_new_inferiors (ptid_t currthread)
1130 /* If this is a new thread, add it to GDB's thread list.
1131 If we leave it up to WFI to do this, bad things will happen. */
1133 if (in_thread_list (currthread) && is_exited (currthread))
1135 /* We're seeing an event on a thread id we knew had exited.
1136 This has to be a new thread reusing the old id. Add it. */
1137 add_thread (currthread);
1138 return;
1141 if (!in_thread_list (currthread))
1143 if (ptid_equal (pid_to_ptid (ptid_get_pid (currthread)), inferior_ptid))
1145 /* inferior_ptid has no thread member yet. This can happen
1146 with the vAttach -> remote_wait,"TAAthread:" path if the
1147 stub doesn't support qC. This is the first stop reported
1148 after an attach, so this is the main thread. Update the
1149 ptid in the thread list. */
1150 thread_change_ptid (inferior_ptid, currthread);
1151 return;
1154 if (ptid_equal (magic_null_ptid, inferior_ptid))
1156 /* inferior_ptid is not set yet. This can happen with the
1157 vRun -> remote_wait,"TAAthread:" path if the stub
1158 doesn't support qC. This is the first stop reported
1159 after an attach, so this is the main thread. Update the
1160 ptid in the thread list. */
1161 thread_change_ptid (inferior_ptid, currthread);
1162 return;
1165 /* When connecting to a target remote, or to a target
1166 extended-remote which already was debugging an inferior, we
1167 may not know about it yet. Add it before adding its child
1168 thread, so notifications are emitted in a sensible order. */
1169 if (!in_inferior_list (ptid_get_pid (currthread)))
1170 add_inferior (ptid_get_pid (currthread));
1172 /* This is really a new thread. Add it. */
1173 add_thread (currthread);
1177 /* Call this function as a result of
1178 1) A halt indication (T packet) containing a thread id
1179 2) A direct query of currthread
1180 3) Successful execution of set thread
1183 static void
1184 record_currthread (ptid_t currthread)
1186 general_thread = currthread;
1188 if (ptid_equal (currthread, minus_one_ptid))
1189 /* We're just invalidating the local thread mirror. */
1190 return;
1192 notice_new_inferiors (currthread);
1195 static char *last_pass_packet;
1197 /* If 'QPassSignals' is supported, tell the remote stub what signals
1198 it can simply pass through to the inferior without reporting. */
1200 static void
1201 remote_pass_signals (void)
1203 if (remote_protocol_packets[PACKET_QPassSignals].support != PACKET_DISABLE)
1205 char *pass_packet, *p;
1206 int numsigs = (int) TARGET_SIGNAL_LAST;
1207 int count = 0, i;
1209 gdb_assert (numsigs < 256);
1210 for (i = 0; i < numsigs; i++)
1212 if (signal_stop_state (i) == 0
1213 && signal_print_state (i) == 0
1214 && signal_pass_state (i) == 1)
1215 count++;
1217 pass_packet = xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
1218 strcpy (pass_packet, "QPassSignals:");
1219 p = pass_packet + strlen (pass_packet);
1220 for (i = 0; i < numsigs; i++)
1222 if (signal_stop_state (i) == 0
1223 && signal_print_state (i) == 0
1224 && signal_pass_state (i) == 1)
1226 if (i >= 16)
1227 *p++ = tohex (i >> 4);
1228 *p++ = tohex (i & 15);
1229 if (count)
1230 *p++ = ';';
1231 else
1232 break;
1233 count--;
1236 *p = 0;
1237 if (!last_pass_packet || strcmp (last_pass_packet, pass_packet))
1239 struct remote_state *rs = get_remote_state ();
1240 char *buf = rs->buf;
1242 putpkt (pass_packet);
1243 getpkt (&rs->buf, &rs->buf_size, 0);
1244 packet_ok (buf, &remote_protocol_packets[PACKET_QPassSignals]);
1245 if (last_pass_packet)
1246 xfree (last_pass_packet);
1247 last_pass_packet = pass_packet;
1249 else
1250 xfree (pass_packet);
1254 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
1255 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
1256 thread. If GEN is set, set the general thread, if not, then set
1257 the step/continue thread. */
1258 static void
1259 set_thread (struct ptid ptid, int gen)
1261 struct remote_state *rs = get_remote_state ();
1262 ptid_t state = gen ? general_thread : continue_thread;
1263 char *buf = rs->buf;
1264 char *endbuf = rs->buf + get_remote_packet_size ();
1266 if (ptid_equal (state, ptid))
1267 return;
1269 *buf++ = 'H';
1270 *buf++ = gen ? 'g' : 'c';
1271 if (ptid_equal (ptid, magic_null_ptid))
1272 xsnprintf (buf, endbuf - buf, "0");
1273 else if (ptid_equal (ptid, any_thread_ptid))
1274 xsnprintf (buf, endbuf - buf, "0");
1275 else if (ptid_equal (ptid, minus_one_ptid))
1276 xsnprintf (buf, endbuf - buf, "-1");
1277 else
1278 write_ptid (buf, endbuf, ptid);
1279 putpkt (rs->buf);
1280 getpkt (&rs->buf, &rs->buf_size, 0);
1281 if (gen)
1282 general_thread = ptid;
1283 else
1284 continue_thread = ptid;
1287 static void
1288 set_general_thread (struct ptid ptid)
1290 set_thread (ptid, 1);
1293 static void
1294 set_continue_thread (struct ptid ptid)
1296 set_thread (ptid, 0);
1299 /* Change the remote current process. Which thread within the process
1300 ends up selected isn't important, as long as it is the same process
1301 as what INFERIOR_PTID points to.
1303 This comes from that fact that there is no explicit notion of
1304 "selected process" in the protocol. The selected process for
1305 general operations is the process the selected general thread
1306 belongs to. */
1308 static void
1309 set_general_process (void)
1311 struct remote_state *rs = get_remote_state ();
1313 /* If the remote can't handle multiple processes, don't bother. */
1314 if (!remote_multi_process_p (rs))
1315 return;
1317 /* We only need to change the remote current thread if it's pointing
1318 at some other process. */
1319 if (ptid_get_pid (general_thread) != ptid_get_pid (inferior_ptid))
1320 set_general_thread (inferior_ptid);
1324 /* Return nonzero if the thread PTID is still alive on the remote
1325 system. */
1327 static int
1328 remote_thread_alive (ptid_t ptid)
1330 struct remote_state *rs = get_remote_state ();
1331 int tid = ptid_get_tid (ptid);
1332 char *p, *endp;
1334 if (ptid_equal (ptid, magic_null_ptid))
1335 /* The main thread is always alive. */
1336 return 1;
1338 if (ptid_get_pid (ptid) != 0 && ptid_get_tid (ptid) == 0)
1339 /* The main thread is always alive. This can happen after a
1340 vAttach, if the remote side doesn't support
1341 multi-threading. */
1342 return 1;
1344 p = rs->buf;
1345 endp = rs->buf + get_remote_packet_size ();
1347 *p++ = 'T';
1348 write_ptid (p, endp, ptid);
1350 putpkt (rs->buf);
1351 getpkt (&rs->buf, &rs->buf_size, 0);
1352 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
1355 /* About these extended threadlist and threadinfo packets. They are
1356 variable length packets but, the fields within them are often fixed
1357 length. They are redundent enough to send over UDP as is the
1358 remote protocol in general. There is a matching unit test module
1359 in libstub. */
1361 #define OPAQUETHREADBYTES 8
1363 /* a 64 bit opaque identifier */
1364 typedef unsigned char threadref[OPAQUETHREADBYTES];
1366 /* WARNING: This threadref data structure comes from the remote O.S.,
1367 libstub protocol encoding, and remote.c. it is not particularly
1368 changable. */
1370 /* Right now, the internal structure is int. We want it to be bigger.
1371 Plan to fix this.
1374 typedef int gdb_threadref; /* Internal GDB thread reference. */
1376 /* gdb_ext_thread_info is an internal GDB data structure which is
1377 equivalent to the reply of the remote threadinfo packet. */
1379 struct gdb_ext_thread_info
1381 threadref threadid; /* External form of thread reference. */
1382 int active; /* Has state interesting to GDB?
1383 regs, stack. */
1384 char display[256]; /* Brief state display, name,
1385 blocked/suspended. */
1386 char shortname[32]; /* To be used to name threads. */
1387 char more_display[256]; /* Long info, statistics, queue depth,
1388 whatever. */
1391 /* The volume of remote transfers can be limited by submitting
1392 a mask containing bits specifying the desired information.
1393 Use a union of these values as the 'selection' parameter to
1394 get_thread_info. FIXME: Make these TAG names more thread specific.
1397 #define TAG_THREADID 1
1398 #define TAG_EXISTS 2
1399 #define TAG_DISPLAY 4
1400 #define TAG_THREADNAME 8
1401 #define TAG_MOREDISPLAY 16
1403 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
1405 char *unpack_varlen_hex (char *buff, ULONGEST *result);
1407 static char *unpack_nibble (char *buf, int *val);
1409 static char *pack_nibble (char *buf, int nibble);
1411 static char *pack_hex_byte (char *pkt, int /* unsigned char */ byte);
1413 static char *unpack_byte (char *buf, int *value);
1415 static char *pack_int (char *buf, int value);
1417 static char *unpack_int (char *buf, int *value);
1419 static char *unpack_string (char *src, char *dest, int length);
1421 static char *pack_threadid (char *pkt, threadref *id);
1423 static char *unpack_threadid (char *inbuf, threadref *id);
1425 void int_to_threadref (threadref *id, int value);
1427 static int threadref_to_int (threadref *ref);
1429 static void copy_threadref (threadref *dest, threadref *src);
1431 static int threadmatch (threadref *dest, threadref *src);
1433 static char *pack_threadinfo_request (char *pkt, int mode,
1434 threadref *id);
1436 static int remote_unpack_thread_info_response (char *pkt,
1437 threadref *expectedref,
1438 struct gdb_ext_thread_info
1439 *info);
1442 static int remote_get_threadinfo (threadref *threadid,
1443 int fieldset, /*TAG mask */
1444 struct gdb_ext_thread_info *info);
1446 static char *pack_threadlist_request (char *pkt, int startflag,
1447 int threadcount,
1448 threadref *nextthread);
1450 static int parse_threadlist_response (char *pkt,
1451 int result_limit,
1452 threadref *original_echo,
1453 threadref *resultlist,
1454 int *doneflag);
1456 static int remote_get_threadlist (int startflag,
1457 threadref *nextthread,
1458 int result_limit,
1459 int *done,
1460 int *result_count,
1461 threadref *threadlist);
1463 typedef int (*rmt_thread_action) (threadref *ref, void *context);
1465 static int remote_threadlist_iterator (rmt_thread_action stepfunction,
1466 void *context, int looplimit);
1468 static int remote_newthread_step (threadref *ref, void *context);
1471 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
1472 buffer we're allowed to write to. Returns
1473 BUF+CHARACTERS_WRITTEN. */
1475 static char *
1476 write_ptid (char *buf, const char *endbuf, ptid_t ptid)
1478 int pid, tid;
1479 struct remote_state *rs = get_remote_state ();
1481 if (remote_multi_process_p (rs))
1483 pid = ptid_get_pid (ptid);
1484 if (pid < 0)
1485 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
1486 else
1487 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
1489 tid = ptid_get_tid (ptid);
1490 if (tid < 0)
1491 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
1492 else
1493 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
1495 return buf;
1498 /* Extract a PTID from BUF. If non-null, OBUF is set to the to one
1499 passed the last parsed char. Returns null_ptid on error. */
1501 static ptid_t
1502 read_ptid (char *buf, char **obuf)
1504 char *p = buf;
1505 char *pp;
1506 ULONGEST pid = 0, tid = 0;
1507 ptid_t ptid;
1509 if (*p == 'p')
1511 /* Multi-process ptid. */
1512 pp = unpack_varlen_hex (p + 1, &pid);
1513 if (*pp != '.')
1514 error (_("invalid remote ptid: %s\n"), p);
1516 p = pp;
1517 pp = unpack_varlen_hex (p + 1, &tid);
1518 if (obuf)
1519 *obuf = pp;
1520 return ptid_build (pid, 0, tid);
1523 /* No multi-process. Just a tid. */
1524 pp = unpack_varlen_hex (p, &tid);
1526 /* Since the stub is not sending a process id, then default to
1527 what's in inferior_ptid, unless it's null at this point. If so,
1528 then since there's no way to know the pid of the reported
1529 threads, use the magic number. */
1530 if (ptid_equal (inferior_ptid, null_ptid))
1531 pid = ptid_get_pid (magic_null_ptid);
1532 else
1533 pid = ptid_get_pid (inferior_ptid);
1535 if (obuf)
1536 *obuf = pp;
1537 return ptid_build (pid, 0, tid);
1540 /* Encode 64 bits in 16 chars of hex. */
1542 static const char hexchars[] = "0123456789abcdef";
1544 static int
1545 ishex (int ch, int *val)
1547 if ((ch >= 'a') && (ch <= 'f'))
1549 *val = ch - 'a' + 10;
1550 return 1;
1552 if ((ch >= 'A') && (ch <= 'F'))
1554 *val = ch - 'A' + 10;
1555 return 1;
1557 if ((ch >= '0') && (ch <= '9'))
1559 *val = ch - '0';
1560 return 1;
1562 return 0;
1565 static int
1566 stubhex (int ch)
1568 if (ch >= 'a' && ch <= 'f')
1569 return ch - 'a' + 10;
1570 if (ch >= '0' && ch <= '9')
1571 return ch - '0';
1572 if (ch >= 'A' && ch <= 'F')
1573 return ch - 'A' + 10;
1574 return -1;
1577 static int
1578 stub_unpack_int (char *buff, int fieldlength)
1580 int nibble;
1581 int retval = 0;
1583 while (fieldlength)
1585 nibble = stubhex (*buff++);
1586 retval |= nibble;
1587 fieldlength--;
1588 if (fieldlength)
1589 retval = retval << 4;
1591 return retval;
1594 char *
1595 unpack_varlen_hex (char *buff, /* packet to parse */
1596 ULONGEST *result)
1598 int nibble;
1599 ULONGEST retval = 0;
1601 while (ishex (*buff, &nibble))
1603 buff++;
1604 retval = retval << 4;
1605 retval |= nibble & 0x0f;
1607 *result = retval;
1608 return buff;
1611 static char *
1612 unpack_nibble (char *buf, int *val)
1614 *val = fromhex (*buf++);
1615 return buf;
1618 static char *
1619 pack_nibble (char *buf, int nibble)
1621 *buf++ = hexchars[(nibble & 0x0f)];
1622 return buf;
1625 static char *
1626 pack_hex_byte (char *pkt, int byte)
1628 *pkt++ = hexchars[(byte >> 4) & 0xf];
1629 *pkt++ = hexchars[(byte & 0xf)];
1630 return pkt;
1633 static char *
1634 unpack_byte (char *buf, int *value)
1636 *value = stub_unpack_int (buf, 2);
1637 return buf + 2;
1640 static char *
1641 pack_int (char *buf, int value)
1643 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
1644 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
1645 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
1646 buf = pack_hex_byte (buf, (value & 0xff));
1647 return buf;
1650 static char *
1651 unpack_int (char *buf, int *value)
1653 *value = stub_unpack_int (buf, 8);
1654 return buf + 8;
1657 #if 0 /* Currently unused, uncomment when needed. */
1658 static char *pack_string (char *pkt, char *string);
1660 static char *
1661 pack_string (char *pkt, char *string)
1663 char ch;
1664 int len;
1666 len = strlen (string);
1667 if (len > 200)
1668 len = 200; /* Bigger than most GDB packets, junk??? */
1669 pkt = pack_hex_byte (pkt, len);
1670 while (len-- > 0)
1672 ch = *string++;
1673 if ((ch == '\0') || (ch == '#'))
1674 ch = '*'; /* Protect encapsulation. */
1675 *pkt++ = ch;
1677 return pkt;
1679 #endif /* 0 (unused) */
1681 static char *
1682 unpack_string (char *src, char *dest, int length)
1684 while (length--)
1685 *dest++ = *src++;
1686 *dest = '\0';
1687 return src;
1690 static char *
1691 pack_threadid (char *pkt, threadref *id)
1693 char *limit;
1694 unsigned char *altid;
1696 altid = (unsigned char *) id;
1697 limit = pkt + BUF_THREAD_ID_SIZE;
1698 while (pkt < limit)
1699 pkt = pack_hex_byte (pkt, *altid++);
1700 return pkt;
1704 static char *
1705 unpack_threadid (char *inbuf, threadref *id)
1707 char *altref;
1708 char *limit = inbuf + BUF_THREAD_ID_SIZE;
1709 int x, y;
1711 altref = (char *) id;
1713 while (inbuf < limit)
1715 x = stubhex (*inbuf++);
1716 y = stubhex (*inbuf++);
1717 *altref++ = (x << 4) | y;
1719 return inbuf;
1722 /* Externally, threadrefs are 64 bits but internally, they are still
1723 ints. This is due to a mismatch of specifications. We would like
1724 to use 64bit thread references internally. This is an adapter
1725 function. */
1727 void
1728 int_to_threadref (threadref *id, int value)
1730 unsigned char *scan;
1732 scan = (unsigned char *) id;
1734 int i = 4;
1735 while (i--)
1736 *scan++ = 0;
1738 *scan++ = (value >> 24) & 0xff;
1739 *scan++ = (value >> 16) & 0xff;
1740 *scan++ = (value >> 8) & 0xff;
1741 *scan++ = (value & 0xff);
1744 static int
1745 threadref_to_int (threadref *ref)
1747 int i, value = 0;
1748 unsigned char *scan;
1750 scan = *ref;
1751 scan += 4;
1752 i = 4;
1753 while (i-- > 0)
1754 value = (value << 8) | ((*scan++) & 0xff);
1755 return value;
1758 static void
1759 copy_threadref (threadref *dest, threadref *src)
1761 int i;
1762 unsigned char *csrc, *cdest;
1764 csrc = (unsigned char *) src;
1765 cdest = (unsigned char *) dest;
1766 i = 8;
1767 while (i--)
1768 *cdest++ = *csrc++;
1771 static int
1772 threadmatch (threadref *dest, threadref *src)
1774 /* Things are broken right now, so just assume we got a match. */
1775 #if 0
1776 unsigned char *srcp, *destp;
1777 int i, result;
1778 srcp = (char *) src;
1779 destp = (char *) dest;
1781 result = 1;
1782 while (i-- > 0)
1783 result &= (*srcp++ == *destp++) ? 1 : 0;
1784 return result;
1785 #endif
1786 return 1;
1790 threadid:1, # always request threadid
1791 context_exists:2,
1792 display:4,
1793 unique_name:8,
1794 more_display:16
1797 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
1799 static char *
1800 pack_threadinfo_request (char *pkt, int mode, threadref *id)
1802 *pkt++ = 'q'; /* Info Query */
1803 *pkt++ = 'P'; /* process or thread info */
1804 pkt = pack_int (pkt, mode); /* mode */
1805 pkt = pack_threadid (pkt, id); /* threadid */
1806 *pkt = '\0'; /* terminate */
1807 return pkt;
1810 /* These values tag the fields in a thread info response packet. */
1811 /* Tagging the fields allows us to request specific fields and to
1812 add more fields as time goes by. */
1814 #define TAG_THREADID 1 /* Echo the thread identifier. */
1815 #define TAG_EXISTS 2 /* Is this process defined enough to
1816 fetch registers and its stack? */
1817 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
1818 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
1819 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
1820 the process. */
1822 static int
1823 remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
1824 struct gdb_ext_thread_info *info)
1826 struct remote_state *rs = get_remote_state ();
1827 int mask, length;
1828 int tag;
1829 threadref ref;
1830 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
1831 int retval = 1;
1833 /* info->threadid = 0; FIXME: implement zero_threadref. */
1834 info->active = 0;
1835 info->display[0] = '\0';
1836 info->shortname[0] = '\0';
1837 info->more_display[0] = '\0';
1839 /* Assume the characters indicating the packet type have been
1840 stripped. */
1841 pkt = unpack_int (pkt, &mask); /* arg mask */
1842 pkt = unpack_threadid (pkt, &ref);
1844 if (mask == 0)
1845 warning (_("Incomplete response to threadinfo request."));
1846 if (!threadmatch (&ref, expectedref))
1847 { /* This is an answer to a different request. */
1848 warning (_("ERROR RMT Thread info mismatch."));
1849 return 0;
1851 copy_threadref (&info->threadid, &ref);
1853 /* Loop on tagged fields , try to bail if somthing goes wrong. */
1855 /* Packets are terminated with nulls. */
1856 while ((pkt < limit) && mask && *pkt)
1858 pkt = unpack_int (pkt, &tag); /* tag */
1859 pkt = unpack_byte (pkt, &length); /* length */
1860 if (!(tag & mask)) /* Tags out of synch with mask. */
1862 warning (_("ERROR RMT: threadinfo tag mismatch."));
1863 retval = 0;
1864 break;
1866 if (tag == TAG_THREADID)
1868 if (length != 16)
1870 warning (_("ERROR RMT: length of threadid is not 16."));
1871 retval = 0;
1872 break;
1874 pkt = unpack_threadid (pkt, &ref);
1875 mask = mask & ~TAG_THREADID;
1876 continue;
1878 if (tag == TAG_EXISTS)
1880 info->active = stub_unpack_int (pkt, length);
1881 pkt += length;
1882 mask = mask & ~(TAG_EXISTS);
1883 if (length > 8)
1885 warning (_("ERROR RMT: 'exists' length too long."));
1886 retval = 0;
1887 break;
1889 continue;
1891 if (tag == TAG_THREADNAME)
1893 pkt = unpack_string (pkt, &info->shortname[0], length);
1894 mask = mask & ~TAG_THREADNAME;
1895 continue;
1897 if (tag == TAG_DISPLAY)
1899 pkt = unpack_string (pkt, &info->display[0], length);
1900 mask = mask & ~TAG_DISPLAY;
1901 continue;
1903 if (tag == TAG_MOREDISPLAY)
1905 pkt = unpack_string (pkt, &info->more_display[0], length);
1906 mask = mask & ~TAG_MOREDISPLAY;
1907 continue;
1909 warning (_("ERROR RMT: unknown thread info tag."));
1910 break; /* Not a tag we know about. */
1912 return retval;
1915 static int
1916 remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
1917 struct gdb_ext_thread_info *info)
1919 struct remote_state *rs = get_remote_state ();
1920 int result;
1922 pack_threadinfo_request (rs->buf, fieldset, threadid);
1923 putpkt (rs->buf);
1924 getpkt (&rs->buf, &rs->buf_size, 0);
1926 if (rs->buf[0] == '\0')
1927 return 0;
1929 result = remote_unpack_thread_info_response (rs->buf + 2,
1930 threadid, info);
1931 return result;
1934 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
1936 static char *
1937 pack_threadlist_request (char *pkt, int startflag, int threadcount,
1938 threadref *nextthread)
1940 *pkt++ = 'q'; /* info query packet */
1941 *pkt++ = 'L'; /* Process LIST or threadLIST request */
1942 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
1943 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
1944 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
1945 *pkt = '\0';
1946 return pkt;
1949 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
1951 static int
1952 parse_threadlist_response (char *pkt, int result_limit,
1953 threadref *original_echo, threadref *resultlist,
1954 int *doneflag)
1956 struct remote_state *rs = get_remote_state ();
1957 char *limit;
1958 int count, resultcount, done;
1960 resultcount = 0;
1961 /* Assume the 'q' and 'M chars have been stripped. */
1962 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
1963 /* done parse past here */
1964 pkt = unpack_byte (pkt, &count); /* count field */
1965 pkt = unpack_nibble (pkt, &done);
1966 /* The first threadid is the argument threadid. */
1967 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
1968 while ((count-- > 0) && (pkt < limit))
1970 pkt = unpack_threadid (pkt, resultlist++);
1971 if (resultcount++ >= result_limit)
1972 break;
1974 if (doneflag)
1975 *doneflag = done;
1976 return resultcount;
1979 static int
1980 remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
1981 int *done, int *result_count, threadref *threadlist)
1983 struct remote_state *rs = get_remote_state ();
1984 static threadref echo_nextthread;
1985 int result = 1;
1987 /* Trancate result limit to be smaller than the packet size. */
1988 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10) >= get_remote_packet_size ())
1989 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
1991 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
1992 putpkt (rs->buf);
1993 getpkt (&rs->buf, &rs->buf_size, 0);
1995 if (*rs->buf == '\0')
1996 *result_count = 0;
1997 else
1998 *result_count =
1999 parse_threadlist_response (rs->buf + 2, result_limit, &echo_nextthread,
2000 threadlist, done);
2002 if (!threadmatch (&echo_nextthread, nextthread))
2004 /* FIXME: This is a good reason to drop the packet. */
2005 /* Possably, there is a duplicate response. */
2006 /* Possabilities :
2007 retransmit immediatly - race conditions
2008 retransmit after timeout - yes
2009 exit
2010 wait for packet, then exit
2012 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
2013 return 0; /* I choose simply exiting. */
2015 if (*result_count <= 0)
2017 if (*done != 1)
2019 warning (_("RMT ERROR : failed to get remote thread list."));
2020 result = 0;
2022 return result; /* break; */
2024 if (*result_count > result_limit)
2026 *result_count = 0;
2027 warning (_("RMT ERROR: threadlist response longer than requested."));
2028 return 0;
2030 return result;
2033 /* This is the interface between remote and threads, remotes upper
2034 interface. */
2036 /* remote_find_new_threads retrieves the thread list and for each
2037 thread in the list, looks up the thread in GDB's internal list,
2038 adding the thread if it does not already exist. This involves
2039 getting partial thread lists from the remote target so, polling the
2040 quit_flag is required. */
2043 /* About this many threadisds fit in a packet. */
2045 #define MAXTHREADLISTRESULTS 32
2047 static int
2048 remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2049 int looplimit)
2051 int done, i, result_count;
2052 int startflag = 1;
2053 int result = 1;
2054 int loopcount = 0;
2055 static threadref nextthread;
2056 static threadref resultthreadlist[MAXTHREADLISTRESULTS];
2058 done = 0;
2059 while (!done)
2061 if (loopcount++ > looplimit)
2063 result = 0;
2064 warning (_("Remote fetch threadlist -infinite loop-."));
2065 break;
2067 if (!remote_get_threadlist (startflag, &nextthread, MAXTHREADLISTRESULTS,
2068 &done, &result_count, resultthreadlist))
2070 result = 0;
2071 break;
2073 /* Clear for later iterations. */
2074 startflag = 0;
2075 /* Setup to resume next batch of thread references, set nextthread. */
2076 if (result_count >= 1)
2077 copy_threadref (&nextthread, &resultthreadlist[result_count - 1]);
2078 i = 0;
2079 while (result_count--)
2080 if (!(result = (*stepfunction) (&resultthreadlist[i++], context)))
2081 break;
2083 return result;
2086 static int
2087 remote_newthread_step (threadref *ref, void *context)
2089 int pid = ptid_get_pid (inferior_ptid);
2090 ptid_t ptid = ptid_build (pid, 0, threadref_to_int (ref));
2092 if (!in_thread_list (ptid))
2093 add_thread (ptid);
2094 return 1; /* continue iterator */
2097 #define CRAZY_MAX_THREADS 1000
2099 static ptid_t
2100 remote_current_thread (ptid_t oldpid)
2102 struct remote_state *rs = get_remote_state ();
2103 char *p = rs->buf;
2104 int tid;
2105 int pid;
2107 putpkt ("qC");
2108 getpkt (&rs->buf, &rs->buf_size, 0);
2109 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
2110 return read_ptid (&rs->buf[2], NULL);
2111 else
2112 return oldpid;
2115 /* Find new threads for info threads command.
2116 * Original version, using John Metzler's thread protocol.
2119 static void
2120 remote_find_new_threads (void)
2122 remote_threadlist_iterator (remote_newthread_step, 0,
2123 CRAZY_MAX_THREADS);
2127 * Find all threads for info threads command.
2128 * Uses new thread protocol contributed by Cisco.
2129 * Falls back and attempts to use the older method (above)
2130 * if the target doesn't respond to the new method.
2133 static void
2134 remote_threads_info (void)
2136 struct remote_state *rs = get_remote_state ();
2137 char *bufp;
2138 ptid_t new_thread;
2140 if (remote_desc == 0) /* paranoia */
2141 error (_("Command can only be used when connected to the remote target."));
2143 if (use_threadinfo_query)
2145 putpkt ("qfThreadInfo");
2146 getpkt (&rs->buf, &rs->buf_size, 0);
2147 bufp = rs->buf;
2148 if (bufp[0] != '\0') /* q packet recognized */
2150 while (*bufp++ == 'm') /* reply contains one or more TID */
2154 new_thread = read_ptid (bufp, &bufp);
2155 if (!ptid_equal (new_thread, null_ptid)
2156 && (!in_thread_list (new_thread)
2157 || is_exited (new_thread)))
2159 /* When connected to a multi-process aware stub,
2160 "info threads" may show up threads of
2161 inferiors we didn't know about yet. Add them
2162 now, and before adding any of its child
2163 threads, so notifications are emitted in a
2164 sensible order. */
2165 if (!in_inferior_list (ptid_get_pid (new_thread)))
2166 add_inferior (ptid_get_pid (new_thread));
2168 add_thread (new_thread);
2170 /* In non-stop mode, we assume new found threads
2171 are running until we proven otherwise with a
2172 stop reply. In all-stop, we can only get
2173 here if all threads are stopped. */
2174 set_executing (new_thread, non_stop ? 1 : 0);
2175 set_running (new_thread, non_stop ? 1 : 0);
2178 while (*bufp++ == ','); /* comma-separated list */
2179 putpkt ("qsThreadInfo");
2180 getpkt (&rs->buf, &rs->buf_size, 0);
2181 bufp = rs->buf;
2183 return; /* done */
2187 /* Only qfThreadInfo is supported in non-stop mode. */
2188 if (non_stop)
2189 return;
2191 /* Else fall back to old method based on jmetzler protocol. */
2192 use_threadinfo_query = 0;
2193 remote_find_new_threads ();
2194 return;
2198 * Collect a descriptive string about the given thread.
2199 * The target may say anything it wants to about the thread
2200 * (typically info about its blocked / runnable state, name, etc.).
2201 * This string will appear in the info threads display.
2203 * Optional: targets are not required to implement this function.
2206 static char *
2207 remote_threads_extra_info (struct thread_info *tp)
2209 struct remote_state *rs = get_remote_state ();
2210 int result;
2211 int set;
2212 threadref id;
2213 struct gdb_ext_thread_info threadinfo;
2214 static char display_buf[100]; /* arbitrary... */
2215 int n = 0; /* position in display_buf */
2217 if (remote_desc == 0) /* paranoia */
2218 internal_error (__FILE__, __LINE__,
2219 _("remote_threads_extra_info"));
2221 if (ptid_equal (tp->ptid, magic_null_ptid)
2222 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_tid (tp->ptid) == 0))
2223 /* This is the main thread which was added by GDB. The remote
2224 server doesn't know about it. */
2225 return NULL;
2227 if (use_threadextra_query)
2229 char *b = rs->buf;
2230 char *endb = rs->buf + get_remote_packet_size ();
2232 xsnprintf (b, endb - b, "qThreadExtraInfo,");
2233 b += strlen (b);
2234 write_ptid (b, endb, tp->ptid);
2236 putpkt (rs->buf);
2237 getpkt (&rs->buf, &rs->buf_size, 0);
2238 if (rs->buf[0] != 0)
2240 n = min (strlen (rs->buf) / 2, sizeof (display_buf));
2241 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
2242 display_buf [result] = '\0';
2243 return display_buf;
2247 /* If the above query fails, fall back to the old method. */
2248 use_threadextra_query = 0;
2249 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
2250 | TAG_MOREDISPLAY | TAG_DISPLAY;
2251 int_to_threadref (&id, ptid_get_tid (tp->ptid));
2252 if (remote_get_threadinfo (&id, set, &threadinfo))
2253 if (threadinfo.active)
2255 if (*threadinfo.shortname)
2256 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
2257 " Name: %s,", threadinfo.shortname);
2258 if (*threadinfo.display)
2259 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
2260 " State: %s,", threadinfo.display);
2261 if (*threadinfo.more_display)
2262 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
2263 " Priority: %s", threadinfo.more_display);
2265 if (n > 0)
2267 /* For purely cosmetic reasons, clear up trailing commas. */
2268 if (',' == display_buf[n-1])
2269 display_buf[n-1] = ' ';
2270 return display_buf;
2273 return NULL;
2277 /* Restart the remote side; this is an extended protocol operation. */
2279 static void
2280 extended_remote_restart (void)
2282 struct remote_state *rs = get_remote_state ();
2284 /* Send the restart command; for reasons I don't understand the
2285 remote side really expects a number after the "R". */
2286 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
2287 putpkt (rs->buf);
2289 remote_fileio_reset ();
2292 /* Clean up connection to a remote debugger. */
2294 static void
2295 remote_close (int quitting)
2297 if (remote_desc == NULL)
2298 return; /* already closed */
2300 /* Make sure we leave stdin registered in the event loop, and we
2301 don't leave the async SIGINT signal handler installed. */
2302 remote_terminal_ours ();
2304 serial_close (remote_desc);
2305 remote_desc = NULL;
2307 /* We don't have a connection to the remote stub anymore. Get rid
2308 of all the inferiors and their threads we were controlling. */
2309 discard_all_inferiors ();
2311 /* We're no longer interested in any of these events. */
2312 discard_pending_stop_replies (-1);
2314 if (remote_async_inferior_event_token)
2315 delete_async_event_handler (&remote_async_inferior_event_token);
2316 if (remote_async_get_pending_events_token)
2317 delete_async_event_handler (&remote_async_get_pending_events_token);
2319 generic_mourn_inferior ();
2322 /* Query the remote side for the text, data and bss offsets. */
2324 static void
2325 get_offsets (void)
2327 struct remote_state *rs = get_remote_state ();
2328 char *buf;
2329 char *ptr;
2330 int lose, num_segments = 0, do_sections, do_segments;
2331 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
2332 struct section_offsets *offs;
2333 struct symfile_segment_data *data;
2335 if (symfile_objfile == NULL)
2336 return;
2338 putpkt ("qOffsets");
2339 getpkt (&rs->buf, &rs->buf_size, 0);
2340 buf = rs->buf;
2342 if (buf[0] == '\000')
2343 return; /* Return silently. Stub doesn't support
2344 this command. */
2345 if (buf[0] == 'E')
2347 warning (_("Remote failure reply: %s"), buf);
2348 return;
2351 /* Pick up each field in turn. This used to be done with scanf, but
2352 scanf will make trouble if CORE_ADDR size doesn't match
2353 conversion directives correctly. The following code will work
2354 with any size of CORE_ADDR. */
2355 text_addr = data_addr = bss_addr = 0;
2356 ptr = buf;
2357 lose = 0;
2359 if (strncmp (ptr, "Text=", 5) == 0)
2361 ptr += 5;
2362 /* Don't use strtol, could lose on big values. */
2363 while (*ptr && *ptr != ';')
2364 text_addr = (text_addr << 4) + fromhex (*ptr++);
2366 if (strncmp (ptr, ";Data=", 6) == 0)
2368 ptr += 6;
2369 while (*ptr && *ptr != ';')
2370 data_addr = (data_addr << 4) + fromhex (*ptr++);
2372 else
2373 lose = 1;
2375 if (!lose && strncmp (ptr, ";Bss=", 5) == 0)
2377 ptr += 5;
2378 while (*ptr && *ptr != ';')
2379 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
2381 if (bss_addr != data_addr)
2382 warning (_("Target reported unsupported offsets: %s"), buf);
2384 else
2385 lose = 1;
2387 else if (strncmp (ptr, "TextSeg=", 8) == 0)
2389 ptr += 8;
2390 /* Don't use strtol, could lose on big values. */
2391 while (*ptr && *ptr != ';')
2392 text_addr = (text_addr << 4) + fromhex (*ptr++);
2393 num_segments = 1;
2395 if (strncmp (ptr, ";DataSeg=", 9) == 0)
2397 ptr += 9;
2398 while (*ptr && *ptr != ';')
2399 data_addr = (data_addr << 4) + fromhex (*ptr++);
2400 num_segments++;
2403 else
2404 lose = 1;
2406 if (lose)
2407 error (_("Malformed response to offset query, %s"), buf);
2408 else if (*ptr != '\0')
2409 warning (_("Target reported unsupported offsets: %s"), buf);
2411 offs = ((struct section_offsets *)
2412 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
2413 memcpy (offs, symfile_objfile->section_offsets,
2414 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
2416 data = get_symfile_segment_data (symfile_objfile->obfd);
2417 do_segments = (data != NULL);
2418 do_sections = num_segments == 0;
2420 if (num_segments > 0)
2422 segments[0] = text_addr;
2423 segments[1] = data_addr;
2425 /* If we have two segments, we can still try to relocate everything
2426 by assuming that the .text and .data offsets apply to the whole
2427 text and data segments. Convert the offsets given in the packet
2428 to base addresses for symfile_map_offsets_to_segments. */
2429 else if (data && data->num_segments == 2)
2431 segments[0] = data->segment_bases[0] + text_addr;
2432 segments[1] = data->segment_bases[1] + data_addr;
2433 num_segments = 2;
2435 /* If the object file has only one segment, assume that it is text
2436 rather than data; main programs with no writable data are rare,
2437 but programs with no code are useless. Of course the code might
2438 have ended up in the data segment... to detect that we would need
2439 the permissions here. */
2440 else if (data && data->num_segments == 1)
2442 segments[0] = data->segment_bases[0] + text_addr;
2443 num_segments = 1;
2445 /* There's no way to relocate by segment. */
2446 else
2447 do_segments = 0;
2449 if (do_segments)
2451 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
2452 offs, num_segments, segments);
2454 if (ret == 0 && !do_sections)
2455 error (_("Can not handle qOffsets TextSeg response with this symbol file"));
2457 if (ret > 0)
2458 do_sections = 0;
2461 if (data)
2462 free_symfile_segment_data (data);
2464 if (do_sections)
2466 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
2468 /* This is a temporary kludge to force data and bss to use the same offsets
2469 because that's what nlmconv does now. The real solution requires changes
2470 to the stub and remote.c that I don't have time to do right now. */
2472 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
2473 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
2476 objfile_relocate (symfile_objfile, offs);
2479 /* Callback for iterate_over_threads. Set the STOP_REQUESTED flags in
2480 threads we know are stopped already. This is used during the
2481 initial remote connection in non-stop mode --- threads that are
2482 reported as already being stopped are left stopped. */
2484 static int
2485 set_stop_requested_callback (struct thread_info *thread, void *data)
2487 /* If we have a stop reply for this thread, it must be stopped. */
2488 if (peek_stop_reply (thread->ptid))
2489 set_stop_requested (thread->ptid, 1);
2491 return 0;
2494 /* Stub for catch_exception. */
2496 struct start_remote_args
2498 int from_tty;
2500 /* The current target. */
2501 struct target_ops *target;
2503 /* Non-zero if this is an extended-remote target. */
2504 int extended_p;
2507 static void
2508 remote_start_remote (struct ui_out *uiout, void *opaque)
2510 struct start_remote_args *args = opaque;
2511 struct remote_state *rs = get_remote_state ();
2512 struct packet_config *noack_config;
2513 char *wait_status = NULL;
2515 immediate_quit++; /* Allow user to interrupt it. */
2517 /* Ack any packet which the remote side has already sent. */
2518 serial_write (remote_desc, "+", 1);
2520 /* The first packet we send to the target is the optional "supported
2521 packets" request. If the target can answer this, it will tell us
2522 which later probes to skip. */
2523 remote_query_supported ();
2525 /* Next, we possibly activate noack mode.
2527 If the QStartNoAckMode packet configuration is set to AUTO,
2528 enable noack mode if the stub reported a wish for it with
2529 qSupported.
2531 If set to TRUE, then enable noack mode even if the stub didn't
2532 report it in qSupported. If the stub doesn't reply OK, the
2533 session ends with an error.
2535 If FALSE, then don't activate noack mode, regardless of what the
2536 stub claimed should be the default with qSupported. */
2538 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
2540 if (noack_config->detect == AUTO_BOOLEAN_TRUE
2541 || (noack_config->detect == AUTO_BOOLEAN_AUTO
2542 && noack_config->support == PACKET_ENABLE))
2544 putpkt ("QStartNoAckMode");
2545 getpkt (&rs->buf, &rs->buf_size, 0);
2546 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
2547 rs->noack_mode = 1;
2550 if (args->extended_p)
2552 /* Tell the remote that we are using the extended protocol. */
2553 putpkt ("!");
2554 getpkt (&rs->buf, &rs->buf_size, 0);
2557 /* Next, if the target can specify a description, read it. We do
2558 this before anything involving memory or registers. */
2559 target_find_description ();
2561 /* On OSs where the list of libraries is global to all
2562 processes, we fetch them early. */
2563 if (gdbarch_has_global_solist (target_gdbarch))
2564 solib_add (NULL, args->from_tty, args->target, auto_solib_add);
2566 if (non_stop)
2568 if (!rs->non_stop_aware)
2569 error (_("Non-stop mode requested, but remote does not support non-stop"));
2571 putpkt ("QNonStop:1");
2572 getpkt (&rs->buf, &rs->buf_size, 0);
2574 if (strcmp (rs->buf, "OK") != 0)
2575 error ("Remote refused setting non-stop mode with: %s", rs->buf);
2577 /* Find about threads and processes the stub is already
2578 controlling. We default to adding them in the running state.
2579 The '?' query below will then tell us about which threads are
2580 stopped. */
2581 remote_threads_info ();
2583 else if (rs->non_stop_aware)
2585 /* Don't assume that the stub can operate in all-stop mode.
2586 Request it explicitely. */
2587 putpkt ("QNonStop:0");
2588 getpkt (&rs->buf, &rs->buf_size, 0);
2590 if (strcmp (rs->buf, "OK") != 0)
2591 error ("Remote refused setting all-stop mode with: %s", rs->buf);
2594 /* Check whether the target is running now. */
2595 putpkt ("?");
2596 getpkt (&rs->buf, &rs->buf_size, 0);
2598 if (!non_stop)
2600 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
2602 if (args->extended_p)
2604 /* We're connected, but not running. Drop out before we
2605 call start_remote. */
2606 target_mark_exited (args->target);
2607 return;
2609 else
2610 error (_("The target is not running (try extended-remote?)"));
2612 else
2614 if (args->extended_p)
2615 target_mark_running (args->target);
2617 /* Save the reply for later. */
2618 wait_status = alloca (strlen (rs->buf) + 1);
2619 strcpy (wait_status, rs->buf);
2622 /* Let the stub know that we want it to return the thread. */
2623 set_continue_thread (minus_one_ptid);
2625 /* Without this, some commands which require an active target
2626 (such as kill) won't work. This variable serves (at least)
2627 double duty as both the pid of the target process (if it has
2628 such), and as a flag indicating that a target is active.
2629 These functions should be split out into seperate variables,
2630 especially since GDB will someday have a notion of debugging
2631 several processes. */
2632 inferior_ptid = magic_null_ptid;
2634 /* Now, if we have thread information, update inferior_ptid. */
2635 inferior_ptid = remote_current_thread (inferior_ptid);
2637 add_inferior (ptid_get_pid (inferior_ptid));
2639 /* Always add the main thread. */
2640 add_thread_silent (inferior_ptid);
2642 get_offsets (); /* Get text, data & bss offsets. */
2644 /* If we could not find a description using qXfer, and we know
2645 how to do it some other way, try again. This is not
2646 supported for non-stop; it could be, but it is tricky if
2647 there are no stopped threads when we connect. */
2648 if (remote_read_description_p (args->target)
2649 && gdbarch_target_desc (target_gdbarch) == NULL)
2651 target_clear_description ();
2652 target_find_description ();
2655 /* Use the previously fetched status. */
2656 gdb_assert (wait_status != NULL);
2657 strcpy (rs->buf, wait_status);
2658 rs->cached_wait_status = 1;
2660 immediate_quit--;
2661 start_remote (args->from_tty); /* Initialize gdb process mechanisms. */
2663 else
2665 /* In non-stop, we will either get an "OK", meaning that there
2666 are no stopped threads at this time; or, a regular stop
2667 reply. In the latter case, there may be more than one thread
2668 stopped --- we pull them all out using the vStopped
2669 mechanism. */
2670 if (strcmp (rs->buf, "OK") != 0)
2672 struct stop_reply *stop_reply;
2673 struct cleanup *old_chain;
2675 stop_reply = stop_reply_xmalloc ();
2676 old_chain = make_cleanup (do_stop_reply_xfree, stop_reply);
2678 remote_parse_stop_reply (rs->buf, stop_reply);
2679 discard_cleanups (old_chain);
2681 /* get_pending_stop_replies acks this one, and gets the rest
2682 out. */
2683 pending_stop_reply = stop_reply;
2684 remote_get_pending_stop_replies ();
2686 /* Make sure that threads that were stopped remain
2687 stopped. */
2688 iterate_over_threads (set_stop_requested_callback, NULL);
2691 if (target_can_async_p ())
2692 target_async (inferior_event_handler, 0);
2694 if (thread_count () == 0)
2696 if (args->extended_p)
2698 /* We're connected, but not running. Drop out before we
2699 call start_remote. */
2700 target_mark_exited (args->target);
2701 return;
2703 else
2704 error (_("The target is not running (try extended-remote?)"));
2707 if (args->extended_p)
2708 target_mark_running (args->target);
2710 /* Let the stub know that we want it to return the thread. */
2712 /* Force the stub to choose a thread. */
2713 set_general_thread (null_ptid);
2715 /* Query it. */
2716 inferior_ptid = remote_current_thread (minus_one_ptid);
2717 if (ptid_equal (inferior_ptid, minus_one_ptid))
2718 error (_("remote didn't report the current thread in non-stop mode"));
2720 get_offsets (); /* Get text, data & bss offsets. */
2722 /* In non-stop mode, any cached wait status will be stored in
2723 the stop reply queue. */
2724 gdb_assert (wait_status == NULL);
2727 /* If we connected to a live target, do some additional setup. */
2728 if (target_has_execution)
2730 if (exec_bfd) /* No use without an exec file. */
2731 remote_check_symbols (symfile_objfile);
2734 /* If code is shared between processes, then breakpoints are global
2735 too; Insert them now. */
2736 if (gdbarch_has_global_solist (target_gdbarch)
2737 && breakpoints_always_inserted_mode ())
2738 insert_breakpoints ();
2741 /* Open a connection to a remote debugger.
2742 NAME is the filename used for communication. */
2744 static void
2745 remote_open (char *name, int from_tty)
2747 remote_open_1 (name, from_tty, &remote_ops, 0);
2750 /* Open a connection to a remote debugger using the extended
2751 remote gdb protocol. NAME is the filename used for communication. */
2753 static void
2754 extended_remote_open (char *name, int from_tty)
2756 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
2759 /* Generic code for opening a connection to a remote target. */
2761 static void
2762 init_all_packet_configs (void)
2764 int i;
2765 for (i = 0; i < PACKET_MAX; i++)
2766 update_packet_config (&remote_protocol_packets[i]);
2769 /* Symbol look-up. */
2771 static void
2772 remote_check_symbols (struct objfile *objfile)
2774 struct remote_state *rs = get_remote_state ();
2775 char *msg, *reply, *tmp;
2776 struct minimal_symbol *sym;
2777 int end;
2779 if (remote_protocol_packets[PACKET_qSymbol].support == PACKET_DISABLE)
2780 return;
2782 /* Make sure the remote is pointing at the right process. */
2783 set_general_process ();
2785 /* Allocate a message buffer. We can't reuse the input buffer in RS,
2786 because we need both at the same time. */
2787 msg = alloca (get_remote_packet_size ());
2789 /* Invite target to request symbol lookups. */
2791 putpkt ("qSymbol::");
2792 getpkt (&rs->buf, &rs->buf_size, 0);
2793 packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSymbol]);
2794 reply = rs->buf;
2796 while (strncmp (reply, "qSymbol:", 8) == 0)
2798 tmp = &reply[8];
2799 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
2800 msg[end] = '\0';
2801 sym = lookup_minimal_symbol (msg, NULL, NULL);
2802 if (sym == NULL)
2803 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
2804 else
2806 CORE_ADDR sym_addr = SYMBOL_VALUE_ADDRESS (sym);
2808 /* If this is a function address, return the start of code
2809 instead of any data function descriptor. */
2810 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch,
2811 sym_addr,
2812 &current_target);
2814 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
2815 paddr_nz (sym_addr), &reply[8]);
2818 putpkt (msg);
2819 getpkt (&rs->buf, &rs->buf_size, 0);
2820 reply = rs->buf;
2824 static struct serial *
2825 remote_serial_open (char *name)
2827 static int udp_warning = 0;
2829 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
2830 of in ser-tcp.c, because it is the remote protocol assuming that the
2831 serial connection is reliable and not the serial connection promising
2832 to be. */
2833 if (!udp_warning && strncmp (name, "udp:", 4) == 0)
2835 warning (_("\
2836 The remote protocol may be unreliable over UDP.\n\
2837 Some events may be lost, rendering further debugging impossible."));
2838 udp_warning = 1;
2841 return serial_open (name);
2844 /* This type describes each known response to the qSupported
2845 packet. */
2846 struct protocol_feature
2848 /* The name of this protocol feature. */
2849 const char *name;
2851 /* The default for this protocol feature. */
2852 enum packet_support default_support;
2854 /* The function to call when this feature is reported, or after
2855 qSupported processing if the feature is not supported.
2856 The first argument points to this structure. The second
2857 argument indicates whether the packet requested support be
2858 enabled, disabled, or probed (or the default, if this function
2859 is being called at the end of processing and this feature was
2860 not reported). The third argument may be NULL; if not NULL, it
2861 is a NUL-terminated string taken from the packet following
2862 this feature's name and an equals sign. */
2863 void (*func) (const struct protocol_feature *, enum packet_support,
2864 const char *);
2866 /* The corresponding packet for this feature. Only used if
2867 FUNC is remote_supported_packet. */
2868 int packet;
2871 static void
2872 remote_supported_packet (const struct protocol_feature *feature,
2873 enum packet_support support,
2874 const char *argument)
2876 if (argument)
2878 warning (_("Remote qSupported response supplied an unexpected value for"
2879 " \"%s\"."), feature->name);
2880 return;
2883 if (remote_protocol_packets[feature->packet].support
2884 == PACKET_SUPPORT_UNKNOWN)
2885 remote_protocol_packets[feature->packet].support = support;
2888 static void
2889 remote_packet_size (const struct protocol_feature *feature,
2890 enum packet_support support, const char *value)
2892 struct remote_state *rs = get_remote_state ();
2894 int packet_size;
2895 char *value_end;
2897 if (support != PACKET_ENABLE)
2898 return;
2900 if (value == NULL || *value == '\0')
2902 warning (_("Remote target reported \"%s\" without a size."),
2903 feature->name);
2904 return;
2907 errno = 0;
2908 packet_size = strtol (value, &value_end, 16);
2909 if (errno != 0 || *value_end != '\0' || packet_size < 0)
2911 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
2912 feature->name, value);
2913 return;
2916 if (packet_size > MAX_REMOTE_PACKET_SIZE)
2918 warning (_("limiting remote suggested packet size (%d bytes) to %d"),
2919 packet_size, MAX_REMOTE_PACKET_SIZE);
2920 packet_size = MAX_REMOTE_PACKET_SIZE;
2923 /* Record the new maximum packet size. */
2924 rs->explicit_packet_size = packet_size;
2927 static void
2928 remote_multi_process_feature (const struct protocol_feature *feature,
2929 enum packet_support support, const char *value)
2931 struct remote_state *rs = get_remote_state ();
2932 rs->multi_process_aware = (support == PACKET_ENABLE);
2935 static void
2936 remote_non_stop_feature (const struct protocol_feature *feature,
2937 enum packet_support support, const char *value)
2939 struct remote_state *rs = get_remote_state ();
2940 rs->non_stop_aware = (support == PACKET_ENABLE);
2943 static struct protocol_feature remote_protocol_features[] = {
2944 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
2945 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
2946 PACKET_qXfer_auxv },
2947 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
2948 PACKET_qXfer_features },
2949 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
2950 PACKET_qXfer_libraries },
2951 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
2952 PACKET_qXfer_memory_map },
2953 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
2954 PACKET_qXfer_spu_read },
2955 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
2956 PACKET_qXfer_spu_write },
2957 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
2958 PACKET_qXfer_osdata },
2959 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
2960 PACKET_QPassSignals },
2961 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
2962 PACKET_QStartNoAckMode },
2963 { "multiprocess", PACKET_DISABLE, remote_multi_process_feature, -1 },
2964 { "QNonStop", PACKET_DISABLE, remote_non_stop_feature, -1 },
2967 static void
2968 remote_query_supported (void)
2970 struct remote_state *rs = get_remote_state ();
2971 char *next;
2972 int i;
2973 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
2975 /* The packet support flags are handled differently for this packet
2976 than for most others. We treat an error, a disabled packet, and
2977 an empty response identically: any features which must be reported
2978 to be used will be automatically disabled. An empty buffer
2979 accomplishes this, since that is also the representation for a list
2980 containing no features. */
2982 rs->buf[0] = 0;
2983 if (remote_protocol_packets[PACKET_qSupported].support != PACKET_DISABLE)
2985 if (rs->extended)
2986 putpkt ("qSupported:multiprocess+");
2987 else
2988 putpkt ("qSupported");
2990 getpkt (&rs->buf, &rs->buf_size, 0);
2992 /* If an error occured, warn, but do not return - just reset the
2993 buffer to empty and go on to disable features. */
2994 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
2995 == PACKET_ERROR)
2997 warning (_("Remote failure reply: %s"), rs->buf);
2998 rs->buf[0] = 0;
3002 memset (seen, 0, sizeof (seen));
3004 next = rs->buf;
3005 while (*next)
3007 enum packet_support is_supported;
3008 char *p, *end, *name_end, *value;
3010 /* First separate out this item from the rest of the packet. If
3011 there's another item after this, we overwrite the separator
3012 (terminated strings are much easier to work with). */
3013 p = next;
3014 end = strchr (p, ';');
3015 if (end == NULL)
3017 end = p + strlen (p);
3018 next = end;
3020 else
3022 *end = '\0';
3023 next = end + 1;
3025 if (end == p)
3027 warning (_("empty item in \"qSupported\" response"));
3028 continue;
3032 name_end = strchr (p, '=');
3033 if (name_end)
3035 /* This is a name=value entry. */
3036 is_supported = PACKET_ENABLE;
3037 value = name_end + 1;
3038 *name_end = '\0';
3040 else
3042 value = NULL;
3043 switch (end[-1])
3045 case '+':
3046 is_supported = PACKET_ENABLE;
3047 break;
3049 case '-':
3050 is_supported = PACKET_DISABLE;
3051 break;
3053 case '?':
3054 is_supported = PACKET_SUPPORT_UNKNOWN;
3055 break;
3057 default:
3058 warning (_("unrecognized item \"%s\" in \"qSupported\" response"), p);
3059 continue;
3061 end[-1] = '\0';
3064 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
3065 if (strcmp (remote_protocol_features[i].name, p) == 0)
3067 const struct protocol_feature *feature;
3069 seen[i] = 1;
3070 feature = &remote_protocol_features[i];
3071 feature->func (feature, is_supported, value);
3072 break;
3076 /* If we increased the packet size, make sure to increase the global
3077 buffer size also. We delay this until after parsing the entire
3078 qSupported packet, because this is the same buffer we were
3079 parsing. */
3080 if (rs->buf_size < rs->explicit_packet_size)
3082 rs->buf_size = rs->explicit_packet_size;
3083 rs->buf = xrealloc (rs->buf, rs->buf_size);
3086 /* Handle the defaults for unmentioned features. */
3087 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
3088 if (!seen[i])
3090 const struct protocol_feature *feature;
3092 feature = &remote_protocol_features[i];
3093 feature->func (feature, feature->default_support, NULL);
3098 static void
3099 remote_open_1 (char *name, int from_tty, struct target_ops *target, int extended_p)
3101 struct remote_state *rs = get_remote_state ();
3103 if (name == 0)
3104 error (_("To open a remote debug connection, you need to specify what\n"
3105 "serial device is attached to the remote system\n"
3106 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
3108 /* See FIXME above. */
3109 if (!target_async_permitted)
3110 wait_forever_enabled_p = 1;
3112 /* If we're connected to a running target, target_preopen will kill it.
3113 But if we're connected to a target system with no running process,
3114 then we will still be connected when it returns. Ask this question
3115 first, before target_preopen has a chance to kill anything. */
3116 if (remote_desc != NULL && !target_has_execution)
3118 if (!from_tty
3119 || query (_("Already connected to a remote target. Disconnect? ")))
3120 pop_target ();
3121 else
3122 error (_("Still connected."));
3125 target_preopen (from_tty);
3127 unpush_target (target);
3129 /* This time without a query. If we were connected to an
3130 extended-remote target and target_preopen killed the running
3131 process, we may still be connected. If we are starting "target
3132 remote" now, the extended-remote target will not have been
3133 removed by unpush_target. */
3134 if (remote_desc != NULL && !target_has_execution)
3135 pop_target ();
3137 /* Make sure we send the passed signals list the next time we resume. */
3138 xfree (last_pass_packet);
3139 last_pass_packet = NULL;
3141 remote_fileio_reset ();
3142 reopen_exec_file ();
3143 reread_symbols ();
3145 remote_desc = remote_serial_open (name);
3146 if (!remote_desc)
3147 perror_with_name (name);
3149 if (baud_rate != -1)
3151 if (serial_setbaudrate (remote_desc, baud_rate))
3153 /* The requested speed could not be set. Error out to
3154 top level after closing remote_desc. Take care to
3155 set remote_desc to NULL to avoid closing remote_desc
3156 more than once. */
3157 serial_close (remote_desc);
3158 remote_desc = NULL;
3159 perror_with_name (name);
3163 serial_raw (remote_desc);
3165 /* If there is something sitting in the buffer we might take it as a
3166 response to a command, which would be bad. */
3167 serial_flush_input (remote_desc);
3169 if (from_tty)
3171 puts_filtered ("Remote debugging using ");
3172 puts_filtered (name);
3173 puts_filtered ("\n");
3175 push_target (target); /* Switch to using remote target now. */
3177 /* Assume that the target is not running, until we learn otherwise. */
3178 if (extended_p)
3179 target_mark_exited (target);
3181 /* Register extra event sources in the event loop. */
3182 remote_async_inferior_event_token
3183 = create_async_event_handler (remote_async_inferior_event_handler,
3184 NULL);
3185 remote_async_get_pending_events_token
3186 = create_async_event_handler (remote_async_get_pending_events_handler,
3187 NULL);
3189 /* Reset the target state; these things will be queried either by
3190 remote_query_supported or as they are needed. */
3191 init_all_packet_configs ();
3192 rs->cached_wait_status = 0;
3193 rs->explicit_packet_size = 0;
3194 rs->noack_mode = 0;
3195 rs->multi_process_aware = 0;
3196 rs->extended = extended_p;
3197 rs->non_stop_aware = 0;
3198 rs->waiting_for_stop_reply = 0;
3200 general_thread = not_sent_ptid;
3201 continue_thread = not_sent_ptid;
3203 /* Probe for ability to use "ThreadInfo" query, as required. */
3204 use_threadinfo_query = 1;
3205 use_threadextra_query = 1;
3207 if (target_async_permitted)
3209 /* With this target we start out by owning the terminal. */
3210 remote_async_terminal_ours_p = 1;
3212 /* FIXME: cagney/1999-09-23: During the initial connection it is
3213 assumed that the target is already ready and able to respond to
3214 requests. Unfortunately remote_start_remote() eventually calls
3215 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
3216 around this. Eventually a mechanism that allows
3217 wait_for_inferior() to expect/get timeouts will be
3218 implemented. */
3219 wait_forever_enabled_p = 0;
3222 /* First delete any symbols previously loaded from shared libraries. */
3223 no_shared_libraries (NULL, 0);
3225 /* Start afresh. */
3226 init_thread_list ();
3228 /* Start the remote connection. If error() or QUIT, discard this
3229 target (we'd otherwise be in an inconsistent state) and then
3230 propogate the error on up the exception chain. This ensures that
3231 the caller doesn't stumble along blindly assuming that the
3232 function succeeded. The CLI doesn't have this problem but other
3233 UI's, such as MI do.
3235 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
3236 this function should return an error indication letting the
3237 caller restore the previous state. Unfortunately the command
3238 ``target remote'' is directly wired to this function making that
3239 impossible. On a positive note, the CLI side of this problem has
3240 been fixed - the function set_cmd_context() makes it possible for
3241 all the ``target ....'' commands to share a common callback
3242 function. See cli-dump.c. */
3244 struct gdb_exception ex;
3245 struct start_remote_args args;
3247 args.from_tty = from_tty;
3248 args.target = target;
3249 args.extended_p = extended_p;
3251 ex = catch_exception (uiout, remote_start_remote, &args, RETURN_MASK_ALL);
3252 if (ex.reason < 0)
3254 /* Pop the partially set up target - unless something else did
3255 already before throwing the exception. */
3256 if (remote_desc != NULL)
3257 pop_target ();
3258 if (target_async_permitted)
3259 wait_forever_enabled_p = 1;
3260 throw_exception (ex);
3264 if (target_async_permitted)
3265 wait_forever_enabled_p = 1;
3268 /* This takes a program previously attached to and detaches it. After
3269 this is done, GDB can be used to debug some other program. We
3270 better not have left any breakpoints in the target program or it'll
3271 die when it hits one. */
3273 static void
3274 remote_detach_1 (char *args, int from_tty, int extended)
3276 int pid = ptid_get_pid (inferior_ptid);
3277 struct remote_state *rs = get_remote_state ();
3279 if (args)
3280 error (_("Argument given to \"detach\" when remotely debugging."));
3282 if (!target_has_execution)
3283 error (_("No process to detach from."));
3285 /* Tell the remote target to detach. */
3286 if (remote_multi_process_p (rs))
3287 sprintf (rs->buf, "D;%x", pid);
3288 else
3289 strcpy (rs->buf, "D");
3291 putpkt (rs->buf);
3292 getpkt (&rs->buf, &rs->buf_size, 0);
3294 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
3296 else if (rs->buf[0] == '\0')
3297 error (_("Remote doesn't know how to detach"));
3298 else
3299 error (_("Can't detach process."));
3301 if (from_tty)
3303 if (remote_multi_process_p (rs))
3304 printf_filtered (_("Detached from remote %s.\n"),
3305 target_pid_to_str (pid_to_ptid (pid)));
3306 else
3308 if (extended)
3309 puts_filtered (_("Detached from remote process.\n"));
3310 else
3311 puts_filtered (_("Ending remote debugging.\n"));
3315 discard_pending_stop_replies (pid);
3316 target_mourn_inferior ();
3319 static void
3320 remote_detach (struct target_ops *ops, char *args, int from_tty)
3322 remote_detach_1 (args, from_tty, 0);
3325 static void
3326 extended_remote_detach (struct target_ops *ops, char *args, int from_tty)
3328 remote_detach_1 (args, from_tty, 1);
3331 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
3333 static void
3334 remote_disconnect (struct target_ops *target, char *args, int from_tty)
3336 if (args)
3337 error (_("Argument given to \"disconnect\" when remotely debugging."));
3339 /* Make sure we unpush even the extended remote targets; mourn
3340 won't do it. So call remote_mourn_1 directly instead of
3341 target_mourn_inferior. */
3342 remote_mourn_1 (target);
3344 if (from_tty)
3345 puts_filtered ("Ending remote debugging.\n");
3348 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
3349 be chatty about it. */
3351 static void
3352 extended_remote_attach_1 (struct target_ops *target, char *args, int from_tty)
3354 struct remote_state *rs = get_remote_state ();
3355 int pid;
3356 char *dummy;
3357 char *wait_status = NULL;
3358 struct inferior *inf;
3360 if (!args)
3361 error_no_arg (_("process-id to attach"));
3363 dummy = args;
3364 pid = strtol (args, &dummy, 0);
3365 /* Some targets don't set errno on errors, grrr! */
3366 if (pid == 0 && args == dummy)
3367 error (_("Illegal process-id: %s."), args);
3369 if (remote_protocol_packets[PACKET_vAttach].support == PACKET_DISABLE)
3370 error (_("This target does not support attaching to a process"));
3372 sprintf (rs->buf, "vAttach;%x", pid);
3373 putpkt (rs->buf);
3374 getpkt (&rs->buf, &rs->buf_size, 0);
3376 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vAttach]) == PACKET_OK)
3378 if (from_tty)
3379 printf_unfiltered (_("Attached to %s\n"),
3380 target_pid_to_str (pid_to_ptid (pid)));
3382 if (!non_stop)
3384 /* Save the reply for later. */
3385 wait_status = alloca (strlen (rs->buf) + 1);
3386 strcpy (wait_status, rs->buf);
3388 else if (strcmp (rs->buf, "OK") != 0)
3389 error (_("Attaching to %s failed with: %s"),
3390 target_pid_to_str (pid_to_ptid (pid)),
3391 rs->buf);
3393 else if (remote_protocol_packets[PACKET_vAttach].support == PACKET_DISABLE)
3394 error (_("This target does not support attaching to a process"));
3395 else
3396 error (_("Attaching to %s failed"),
3397 target_pid_to_str (pid_to_ptid (pid)));
3399 target_mark_running (target);
3400 inferior_ptid = pid_to_ptid (pid);
3402 /* Now, if we have thread information, update inferior_ptid. */
3403 inferior_ptid = remote_current_thread (inferior_ptid);
3405 inf = add_inferior (pid);
3406 inf->attach_flag = 1;
3408 if (non_stop)
3409 /* Get list of threads. */
3410 remote_threads_info ();
3411 else
3412 /* Add the main thread to the thread list. */
3413 add_thread_silent (inferior_ptid);
3415 /* Next, if the target can specify a description, read it. We do
3416 this before anything involving memory or registers. */
3417 target_find_description ();
3419 if (!non_stop)
3421 /* Use the previously fetched status. */
3422 gdb_assert (wait_status != NULL);
3424 if (target_can_async_p ())
3426 struct stop_reply *stop_reply;
3427 struct cleanup *old_chain;
3429 stop_reply = stop_reply_xmalloc ();
3430 old_chain = make_cleanup (do_stop_reply_xfree, stop_reply);
3431 remote_parse_stop_reply (wait_status, stop_reply);
3432 discard_cleanups (old_chain);
3433 push_stop_reply (stop_reply);
3435 target_async (inferior_event_handler, 0);
3437 else
3439 gdb_assert (wait_status != NULL);
3440 strcpy (rs->buf, wait_status);
3441 rs->cached_wait_status = 1;
3444 else
3445 gdb_assert (wait_status == NULL);
3448 static void
3449 extended_remote_attach (struct target_ops *ops, char *args, int from_tty)
3451 extended_remote_attach_1 (ops, args, from_tty);
3454 /* Convert hex digit A to a number. */
3456 static int
3457 fromhex (int a)
3459 if (a >= '0' && a <= '9')
3460 return a - '0';
3461 else if (a >= 'a' && a <= 'f')
3462 return a - 'a' + 10;
3463 else if (a >= 'A' && a <= 'F')
3464 return a - 'A' + 10;
3465 else
3466 error (_("Reply contains invalid hex digit %d"), a);
3469 static int
3470 hex2bin (const char *hex, gdb_byte *bin, int count)
3472 int i;
3474 for (i = 0; i < count; i++)
3476 if (hex[0] == 0 || hex[1] == 0)
3478 /* Hex string is short, or of uneven length.
3479 Return the count that has been converted so far. */
3480 return i;
3482 *bin++ = fromhex (hex[0]) * 16 + fromhex (hex[1]);
3483 hex += 2;
3485 return i;
3488 /* Convert number NIB to a hex digit. */
3490 static int
3491 tohex (int nib)
3493 if (nib < 10)
3494 return '0' + nib;
3495 else
3496 return 'a' + nib - 10;
3499 static int
3500 bin2hex (const gdb_byte *bin, char *hex, int count)
3502 int i;
3503 /* May use a length, or a nul-terminated string as input. */
3504 if (count == 0)
3505 count = strlen ((char *) bin);
3507 for (i = 0; i < count; i++)
3509 *hex++ = tohex ((*bin >> 4) & 0xf);
3510 *hex++ = tohex (*bin++ & 0xf);
3512 *hex = 0;
3513 return i;
3516 /* Check for the availability of vCont. This function should also check
3517 the response. */
3519 static void
3520 remote_vcont_probe (struct remote_state *rs)
3522 char *buf;
3524 strcpy (rs->buf, "vCont?");
3525 putpkt (rs->buf);
3526 getpkt (&rs->buf, &rs->buf_size, 0);
3527 buf = rs->buf;
3529 /* Make sure that the features we assume are supported. */
3530 if (strncmp (buf, "vCont", 5) == 0)
3532 char *p = &buf[5];
3533 int support_s, support_S, support_c, support_C;
3535 support_s = 0;
3536 support_S = 0;
3537 support_c = 0;
3538 support_C = 0;
3539 rs->support_vCont_t = 0;
3540 while (p && *p == ';')
3542 p++;
3543 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
3544 support_s = 1;
3545 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
3546 support_S = 1;
3547 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
3548 support_c = 1;
3549 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
3550 support_C = 1;
3551 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
3552 rs->support_vCont_t = 1;
3554 p = strchr (p, ';');
3557 /* If s, S, c, and C are not all supported, we can't use vCont. Clearing
3558 BUF will make packet_ok disable the packet. */
3559 if (!support_s || !support_S || !support_c || !support_C)
3560 buf[0] = 0;
3563 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
3566 /* Resume the remote inferior by using a "vCont" packet. The thread
3567 to be resumed is PTID; STEP and SIGGNAL indicate whether the
3568 resumed thread should be single-stepped and/or signalled. If PTID
3569 equals minus_one_ptid, then all threads are resumed; the thread to
3570 be stepped and/or signalled is given in the global INFERIOR_PTID.
3571 This function returns non-zero iff it resumes the inferior.
3573 This function issues a strict subset of all possible vCont commands at the
3574 moment. */
3576 static int
3577 remote_vcont_resume (ptid_t ptid, int step, enum target_signal siggnal)
3579 struct remote_state *rs = get_remote_state ();
3580 char *p;
3581 char *endp;
3583 if (remote_protocol_packets[PACKET_vCont].support == PACKET_SUPPORT_UNKNOWN)
3584 remote_vcont_probe (rs);
3586 if (remote_protocol_packets[PACKET_vCont].support == PACKET_DISABLE)
3587 return 0;
3589 p = rs->buf;
3590 endp = rs->buf + get_remote_packet_size ();
3592 /* If we could generate a wider range of packets, we'd have to worry
3593 about overflowing BUF. Should there be a generic
3594 "multi-part-packet" packet? */
3596 if (ptid_equal (ptid, magic_null_ptid))
3598 /* MAGIC_NULL_PTID means that we don't have any active threads,
3599 so we don't have any TID numbers the inferior will
3600 understand. Make sure to only send forms that do not specify
3601 a TID. */
3602 if (step && siggnal != TARGET_SIGNAL_0)
3603 xsnprintf (p, endp - p, "vCont;S%02x", siggnal);
3604 else if (step)
3605 xsnprintf (p, endp - p, "vCont;s");
3606 else if (siggnal != TARGET_SIGNAL_0)
3607 xsnprintf (p, endp - p, "vCont;C%02x", siggnal);
3608 else
3609 xsnprintf (p, endp - p, "vCont;c");
3611 else if (ptid_equal (ptid, minus_one_ptid))
3613 /* Resume all threads, with preference for INFERIOR_PTID. */
3614 if (step && siggnal != TARGET_SIGNAL_0)
3616 /* Step inferior_ptid with signal. */
3617 p += xsnprintf (p, endp - p, "vCont;S%02x:", siggnal);
3618 p = write_ptid (p, endp, inferior_ptid);
3619 /* And continue others. */
3620 p += xsnprintf (p, endp - p, ";c");
3622 else if (step)
3624 /* Step inferior_ptid. */
3625 p += xsnprintf (p, endp - p, "vCont;s:");
3626 p = write_ptid (p, endp, inferior_ptid);
3627 /* And continue others. */
3628 p += xsnprintf (p, endp - p, ";c");
3630 else if (siggnal != TARGET_SIGNAL_0)
3632 /* Continue inferior_ptid with signal. */
3633 p += xsnprintf (p, endp - p, "vCont;C%02x:", siggnal);
3634 p = write_ptid (p, endp, inferior_ptid);
3635 /* And continue others. */
3636 p += xsnprintf (p, endp - p, ";c");
3638 else
3639 xsnprintf (p, endp - p, "vCont;c");
3641 else
3643 /* Scheduler locking; resume only PTID. */
3644 if (step && siggnal != TARGET_SIGNAL_0)
3646 /* Step ptid with signal. */
3647 p += xsnprintf (p, endp - p, "vCont;S%02x:", siggnal);
3648 p = write_ptid (p, endp, ptid);
3650 else if (step)
3652 /* Step ptid. */
3653 p += xsnprintf (p, endp - p, "vCont;s:");
3654 p = write_ptid (p, endp, ptid);
3656 else if (siggnal != TARGET_SIGNAL_0)
3658 /* Continue ptid with signal. */
3659 p += xsnprintf (p, endp - p, "vCont;C%02x:", siggnal);
3660 p = write_ptid (p, endp, ptid);
3662 else
3664 /* Continue ptid. */
3665 p += xsnprintf (p, endp - p, "vCont;c:");
3666 p = write_ptid (p, endp, ptid);
3670 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
3671 putpkt (rs->buf);
3673 if (non_stop)
3675 /* In non-stop, the stub replies to vCont with "OK". The stop
3676 reply will be reported asynchronously by means of a `%Stop'
3677 notification. */
3678 getpkt (&rs->buf, &rs->buf_size, 0);
3679 if (strcmp (rs->buf, "OK") != 0)
3680 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
3683 return 1;
3686 /* Tell the remote machine to resume. */
3688 static enum target_signal last_sent_signal = TARGET_SIGNAL_0;
3690 static int last_sent_step;
3692 static void
3693 remote_resume (ptid_t ptid, int step, enum target_signal siggnal)
3695 struct remote_state *rs = get_remote_state ();
3696 char *buf;
3698 last_sent_signal = siggnal;
3699 last_sent_step = step;
3701 /* Update the inferior on signals to silently pass, if they've changed. */
3702 remote_pass_signals ();
3704 /* The vCont packet doesn't need to specify threads via Hc. */
3705 if (remote_vcont_resume (ptid, step, siggnal))
3706 goto done;
3708 /* All other supported resume packets do use Hc, so set the continue
3709 thread. */
3710 if (ptid_equal (ptid, minus_one_ptid))
3711 set_continue_thread (any_thread_ptid);
3712 else
3713 set_continue_thread (ptid);
3715 buf = rs->buf;
3716 if (execution_direction == EXEC_REVERSE)
3718 /* We don't pass signals to the target in reverse exec mode. */
3719 if (info_verbose && siggnal != TARGET_SIGNAL_0)
3720 warning (" - Can't pass signal %d to target in reverse: ignored.\n",
3721 siggnal);
3722 strcpy (buf, step ? "bs" : "bc");
3724 else if (siggnal != TARGET_SIGNAL_0)
3726 buf[0] = step ? 'S' : 'C';
3727 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
3728 buf[2] = tohex (((int) siggnal) & 0xf);
3729 buf[3] = '\0';
3731 else
3732 strcpy (buf, step ? "s" : "c");
3734 putpkt (buf);
3736 done:
3737 /* We are about to start executing the inferior, let's register it
3738 with the event loop. NOTE: this is the one place where all the
3739 execution commands end up. We could alternatively do this in each
3740 of the execution commands in infcmd.c. */
3741 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
3742 into infcmd.c in order to allow inferior function calls to work
3743 NOT asynchronously. */
3744 if (target_can_async_p ())
3745 target_async (inferior_event_handler, 0);
3747 /* We've just told the target to resume. The remote server will
3748 wait for the inferior to stop, and then send a stop reply. In
3749 the mean time, we can't start another command/query ourselves
3750 because the stub wouldn't be ready to process it. This applies
3751 only to the base all-stop protocol, however. In non-stop (which
3752 only supports vCont), the stub replies with an "OK", and is
3753 immediate able to process further serial input. */
3754 if (!non_stop)
3755 rs->waiting_for_stop_reply = 1;
3759 /* Set up the signal handler for SIGINT, while the target is
3760 executing, ovewriting the 'regular' SIGINT signal handler. */
3761 static void
3762 initialize_sigint_signal_handler (void)
3764 signal (SIGINT, handle_remote_sigint);
3767 /* Signal handler for SIGINT, while the target is executing. */
3768 static void
3769 handle_remote_sigint (int sig)
3771 signal (sig, handle_remote_sigint_twice);
3772 mark_async_signal_handler_wrapper (sigint_remote_token);
3775 /* Signal handler for SIGINT, installed after SIGINT has already been
3776 sent once. It will take effect the second time that the user sends
3777 a ^C. */
3778 static void
3779 handle_remote_sigint_twice (int sig)
3781 signal (sig, handle_remote_sigint);
3782 mark_async_signal_handler_wrapper (sigint_remote_twice_token);
3785 /* Perform the real interruption of the target execution, in response
3786 to a ^C. */
3787 static void
3788 async_remote_interrupt (gdb_client_data arg)
3790 if (remote_debug)
3791 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
3793 target_stop (inferior_ptid);
3796 /* Perform interrupt, if the first attempt did not succeed. Just give
3797 up on the target alltogether. */
3798 void
3799 async_remote_interrupt_twice (gdb_client_data arg)
3801 if (remote_debug)
3802 fprintf_unfiltered (gdb_stdlog, "remote_interrupt_twice called\n");
3804 interrupt_query ();
3807 /* Reinstall the usual SIGINT handlers, after the target has
3808 stopped. */
3809 static void
3810 cleanup_sigint_signal_handler (void *dummy)
3812 signal (SIGINT, handle_sigint);
3815 /* Send ^C to target to halt it. Target will respond, and send us a
3816 packet. */
3817 static void (*ofunc) (int);
3819 /* The command line interface's stop routine. This function is installed
3820 as a signal handler for SIGINT. The first time a user requests a
3821 stop, we call remote_stop to send a break or ^C. If there is no
3822 response from the target (it didn't stop when the user requested it),
3823 we ask the user if he'd like to detach from the target. */
3824 static void
3825 remote_interrupt (int signo)
3827 /* If this doesn't work, try more severe steps. */
3828 signal (signo, remote_interrupt_twice);
3830 gdb_call_async_signal_handler (sigint_remote_token, 1);
3833 /* The user typed ^C twice. */
3835 static void
3836 remote_interrupt_twice (int signo)
3838 signal (signo, ofunc);
3839 gdb_call_async_signal_handler (sigint_remote_twice_token, 1);
3840 signal (signo, remote_interrupt);
3843 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
3844 thread, all threads of a remote process, or all threads of all
3845 processes. */
3847 static void
3848 remote_stop_ns (ptid_t ptid)
3850 struct remote_state *rs = get_remote_state ();
3851 char *p = rs->buf;
3852 char *endp = rs->buf + get_remote_packet_size ();
3853 struct stop_reply *reply, *next;
3855 if (remote_protocol_packets[PACKET_vCont].support == PACKET_SUPPORT_UNKNOWN)
3856 remote_vcont_probe (rs);
3858 if (!rs->support_vCont_t)
3859 error (_("Remote server does not support stopping threads"));
3861 if (ptid_equal (ptid, minus_one_ptid))
3862 p += xsnprintf (p, endp - p, "vCont;t");
3863 else
3865 ptid_t nptid;
3867 /* Step inferior_ptid. */
3868 p += xsnprintf (p, endp - p, "vCont;t:");
3870 if (ptid_is_pid (ptid))
3871 /* All (-1) threads of process. */
3872 nptid = ptid_build (ptid_get_pid (ptid), 0, -1);
3873 else
3875 /* Small optimization: if we already have a stop reply for
3876 this thread, no use in telling the stub we want this
3877 stopped. */
3878 if (peek_stop_reply (ptid))
3879 return;
3881 nptid = ptid;
3884 p = write_ptid (p, endp, nptid);
3887 /* In non-stop, we get an immediate OK reply. The stop reply will
3888 come in asynchronously by notification. */
3889 putpkt (rs->buf);
3890 getpkt (&rs->buf, &rs->buf_size, 0);
3891 if (strcmp (rs->buf, "OK") != 0)
3892 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
3895 /* All-stop version of target_stop. Sends a break or a ^C to stop the
3896 remote target. It is undefined which thread of which process
3897 reports the stop. */
3899 static void
3900 remote_stop_as (ptid_t ptid)
3902 struct remote_state *rs = get_remote_state ();
3904 /* If the inferior is stopped already, but the core didn't know
3905 about it yet, just ignore the request. The cached wait status
3906 will be collected in remote_wait. */
3907 if (rs->cached_wait_status)
3908 return;
3910 /* Send a break or a ^C, depending on user preference. */
3912 if (remote_break)
3913 serial_send_break (remote_desc);
3914 else
3915 serial_write (remote_desc, "\003", 1);
3918 /* This is the generic stop called via the target vector. When a target
3919 interrupt is requested, either by the command line or the GUI, we
3920 will eventually end up here. */
3922 static void
3923 remote_stop (ptid_t ptid)
3925 if (remote_debug)
3926 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
3928 if (non_stop)
3929 remote_stop_ns (ptid);
3930 else
3931 remote_stop_as (ptid);
3934 /* Ask the user what to do when an interrupt is received. */
3936 static void
3937 interrupt_query (void)
3939 target_terminal_ours ();
3941 if (target_can_async_p ())
3943 signal (SIGINT, handle_sigint);
3944 deprecated_throw_reason (RETURN_QUIT);
3946 else
3948 if (query ("Interrupted while waiting for the program.\n\
3949 Give up (and stop debugging it)? "))
3951 pop_target ();
3952 deprecated_throw_reason (RETURN_QUIT);
3956 target_terminal_inferior ();
3959 /* Enable/disable target terminal ownership. Most targets can use
3960 terminal groups to control terminal ownership. Remote targets are
3961 different in that explicit transfer of ownership to/from GDB/target
3962 is required. */
3964 static void
3965 remote_terminal_inferior (void)
3967 if (!target_async_permitted)
3968 /* Nothing to do. */
3969 return;
3971 /* FIXME: cagney/1999-09-27: Shouldn't need to test for
3972 sync_execution here. This function should only be called when
3973 GDB is resuming the inferior in the forground. A background
3974 resume (``run&'') should leave GDB in control of the terminal and
3975 consequently should not call this code. */
3976 if (!sync_execution)
3977 return;
3978 /* FIXME: cagney/1999-09-27: Closely related to the above. Make
3979 calls target_terminal_*() idenpotent. The event-loop GDB talking
3980 to an asynchronous target with a synchronous command calls this
3981 function from both event-top.c and infrun.c/infcmd.c. Once GDB
3982 stops trying to transfer the terminal to the target when it
3983 shouldn't this guard can go away. */
3984 if (!remote_async_terminal_ours_p)
3985 return;
3986 delete_file_handler (input_fd);
3987 remote_async_terminal_ours_p = 0;
3988 initialize_sigint_signal_handler ();
3989 /* NOTE: At this point we could also register our selves as the
3990 recipient of all input. Any characters typed could then be
3991 passed on down to the target. */
3994 static void
3995 remote_terminal_ours (void)
3997 if (!target_async_permitted)
3998 /* Nothing to do. */
3999 return;
4001 /* See FIXME in remote_terminal_inferior. */
4002 if (!sync_execution)
4003 return;
4004 /* See FIXME in remote_terminal_inferior. */
4005 if (remote_async_terminal_ours_p)
4006 return;
4007 cleanup_sigint_signal_handler (NULL);
4008 add_file_handler (input_fd, stdin_event_handler, 0);
4009 remote_async_terminal_ours_p = 1;
4012 void
4013 remote_console_output (char *msg)
4015 char *p;
4017 for (p = msg; p[0] && p[1]; p += 2)
4019 char tb[2];
4020 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
4021 tb[0] = c;
4022 tb[1] = 0;
4023 fputs_unfiltered (tb, gdb_stdtarg);
4025 gdb_flush (gdb_stdtarg);
4028 typedef struct cached_reg
4030 int num;
4031 gdb_byte data[MAX_REGISTER_SIZE];
4032 } cached_reg_t;
4034 DEF_VEC_O(cached_reg_t);
4036 struct stop_reply
4038 struct stop_reply *next;
4040 ptid_t ptid;
4042 struct target_waitstatus ws;
4044 VEC(cached_reg_t) *regcache;
4046 int stopped_by_watchpoint_p;
4047 CORE_ADDR watch_data_address;
4049 int solibs_changed;
4050 int replay_event;
4053 /* The list of already fetched and acknowledged stop events. */
4054 static struct stop_reply *stop_reply_queue;
4056 static struct stop_reply *
4057 stop_reply_xmalloc (void)
4059 struct stop_reply *r = XMALLOC (struct stop_reply);
4060 r->next = NULL;
4061 return r;
4064 static void
4065 stop_reply_xfree (struct stop_reply *r)
4067 if (r != NULL)
4069 VEC_free (cached_reg_t, r->regcache);
4070 xfree (r);
4074 /* Discard all pending stop replies of inferior PID. If PID is -1,
4075 discard everything. */
4077 static void
4078 discard_pending_stop_replies (int pid)
4080 struct stop_reply *prev = NULL, *reply, *next;
4082 /* Discard the in-flight notification. */
4083 if (pending_stop_reply != NULL
4084 && (pid == -1
4085 || ptid_get_pid (pending_stop_reply->ptid) == pid))
4087 stop_reply_xfree (pending_stop_reply);
4088 pending_stop_reply = NULL;
4091 /* Discard the stop replies we have already pulled with
4092 vStopped. */
4093 for (reply = stop_reply_queue; reply; reply = next)
4095 next = reply->next;
4096 if (pid == -1
4097 || ptid_get_pid (reply->ptid) == pid)
4099 if (reply == stop_reply_queue)
4100 stop_reply_queue = reply->next;
4101 else
4102 prev->next = reply->next;
4104 stop_reply_xfree (reply);
4106 else
4107 prev = reply;
4111 /* Cleanup wrapper. */
4113 static void
4114 do_stop_reply_xfree (void *arg)
4116 struct stop_reply *r = arg;
4117 stop_reply_xfree (r);
4120 /* Look for a queued stop reply belonging to PTID. If one is found,
4121 remove it from the queue, and return it. Returns NULL if none is
4122 found. If there are still queued events left to process, tell the
4123 event loop to get back to target_wait soon. */
4125 static struct stop_reply *
4126 queued_stop_reply (ptid_t ptid)
4128 struct stop_reply *it, *prev;
4129 struct stop_reply head;
4131 head.next = stop_reply_queue;
4132 prev = &head;
4134 it = head.next;
4136 if (!ptid_equal (ptid, minus_one_ptid))
4137 for (; it; prev = it, it = it->next)
4138 if (ptid_equal (ptid, it->ptid))
4139 break;
4141 if (it)
4143 prev->next = it->next;
4144 it->next = NULL;
4147 stop_reply_queue = head.next;
4149 if (stop_reply_queue)
4150 /* There's still at least an event left. */
4151 mark_async_event_handler (remote_async_inferior_event_token);
4153 return it;
4156 /* Push a fully parsed stop reply in the stop reply queue. Since we
4157 know that we now have at least one queued event left to pass to the
4158 core side, tell the event loop to get back to target_wait soon. */
4160 static void
4161 push_stop_reply (struct stop_reply *new_event)
4163 struct stop_reply *event;
4165 if (stop_reply_queue)
4167 for (event = stop_reply_queue;
4168 event && event->next;
4169 event = event->next)
4172 event->next = new_event;
4174 else
4175 stop_reply_queue = new_event;
4177 mark_async_event_handler (remote_async_inferior_event_token);
4180 /* Returns true if we have a stop reply for PTID. */
4182 static int
4183 peek_stop_reply (ptid_t ptid)
4185 struct stop_reply *it;
4187 for (it = stop_reply_queue; it; it = it->next)
4188 if (ptid_equal (ptid, it->ptid))
4190 if (it->ws.kind == TARGET_WAITKIND_STOPPED)
4191 return 1;
4194 return 0;
4197 /* Parse the stop reply in BUF. Either the function succeeds, and the
4198 result is stored in EVENT, or throws an error. */
4200 static void
4201 remote_parse_stop_reply (char *buf, struct stop_reply *event)
4203 struct remote_arch_state *rsa = get_remote_arch_state ();
4204 ULONGEST addr;
4205 char *p;
4207 event->ptid = null_ptid;
4208 event->ws.kind = TARGET_WAITKIND_IGNORE;
4209 event->ws.value.integer = 0;
4210 event->solibs_changed = 0;
4211 event->replay_event = 0;
4212 event->stopped_by_watchpoint_p = 0;
4213 event->regcache = NULL;
4215 switch (buf[0])
4217 case 'T': /* Status with PC, SP, FP, ... */
4219 gdb_byte regs[MAX_REGISTER_SIZE];
4221 /* Expedited reply, containing Signal, {regno, reg} repeat. */
4222 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
4223 ss = signal number
4224 n... = register number
4225 r... = register contents
4228 p = &buf[3]; /* after Txx */
4229 while (*p)
4231 char *p1;
4232 char *p_temp;
4233 int fieldsize;
4234 LONGEST pnum = 0;
4236 /* If the packet contains a register number, save it in
4237 pnum and set p1 to point to the character following it.
4238 Otherwise p1 points to p. */
4240 /* If this packet is an awatch packet, don't parse the 'a'
4241 as a register number. */
4243 if (strncmp (p, "awatch", strlen("awatch")) != 0)
4245 /* Read the ``P'' register number. */
4246 pnum = strtol (p, &p_temp, 16);
4247 p1 = p_temp;
4249 else
4250 p1 = p;
4252 if (p1 == p) /* No register number present here. */
4254 p1 = strchr (p, ':');
4255 if (p1 == NULL)
4256 error (_("Malformed packet(a) (missing colon): %s\n\
4257 Packet: '%s'\n"),
4258 p, buf);
4259 if (strncmp (p, "thread", p1 - p) == 0)
4260 event->ptid = read_ptid (++p1, &p);
4261 else if ((strncmp (p, "watch", p1 - p) == 0)
4262 || (strncmp (p, "rwatch", p1 - p) == 0)
4263 || (strncmp (p, "awatch", p1 - p) == 0))
4265 event->stopped_by_watchpoint_p = 1;
4266 p = unpack_varlen_hex (++p1, &addr);
4267 event->watch_data_address = (CORE_ADDR) addr;
4269 else if (strncmp (p, "library", p1 - p) == 0)
4271 p1++;
4272 p_temp = p1;
4273 while (*p_temp && *p_temp != ';')
4274 p_temp++;
4276 event->solibs_changed = 1;
4277 p = p_temp;
4279 else if (strncmp (p, "replaylog", p1 - p) == 0)
4281 /* NO_HISTORY event.
4282 p1 will indicate "begin" or "end", but
4283 it makes no difference for now, so ignore it. */
4284 event->replay_event = 1;
4285 p_temp = strchr (p1 + 1, ';');
4286 if (p_temp)
4287 p = p_temp;
4289 else
4291 /* Silently skip unknown optional info. */
4292 p_temp = strchr (p1 + 1, ';');
4293 if (p_temp)
4294 p = p_temp;
4297 else
4299 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
4300 cached_reg_t cached_reg;
4302 p = p1;
4304 if (*p != ':')
4305 error (_("Malformed packet(b) (missing colon): %s\n\
4306 Packet: '%s'\n"),
4307 p, buf);
4308 ++p;
4310 if (reg == NULL)
4311 error (_("Remote sent bad register number %s: %s\n\
4312 Packet: '%s'\n"),
4313 phex_nz (pnum, 0), p, buf);
4315 cached_reg.num = reg->regnum;
4317 fieldsize = hex2bin (p, cached_reg.data,
4318 register_size (target_gdbarch,
4319 reg->regnum));
4320 p += 2 * fieldsize;
4321 if (fieldsize < register_size (target_gdbarch,
4322 reg->regnum))
4323 warning (_("Remote reply is too short: %s"), buf);
4325 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
4328 if (*p != ';')
4329 error (_("Remote register badly formatted: %s\nhere: %s"),
4330 buf, p);
4331 ++p;
4334 /* fall through */
4335 case 'S': /* Old style status, just signal only. */
4336 if (event->solibs_changed)
4337 event->ws.kind = TARGET_WAITKIND_LOADED;
4338 else if (event->replay_event)
4339 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
4340 else
4342 event->ws.kind = TARGET_WAITKIND_STOPPED;
4343 event->ws.value.sig = (enum target_signal)
4344 (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
4346 break;
4347 case 'W': /* Target exited. */
4348 case 'X':
4350 char *p;
4351 int pid;
4352 ULONGEST value;
4354 /* GDB used to accept only 2 hex chars here. Stubs should
4355 only send more if they detect GDB supports multi-process
4356 support. */
4357 p = unpack_varlen_hex (&buf[1], &value);
4359 if (buf[0] == 'W')
4361 /* The remote process exited. */
4362 event->ws.kind = TARGET_WAITKIND_EXITED;
4363 event->ws.value.integer = value;
4365 else
4367 /* The remote process exited with a signal. */
4368 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
4369 event->ws.value.sig = (enum target_signal) value;
4372 /* If no process is specified, assume inferior_ptid. */
4373 pid = ptid_get_pid (inferior_ptid);
4374 if (*p == '\0')
4376 else if (*p == ';')
4378 p++;
4380 if (p == '\0')
4382 else if (strncmp (p,
4383 "process:", sizeof ("process:") - 1) == 0)
4385 ULONGEST upid;
4386 p += sizeof ("process:") - 1;
4387 unpack_varlen_hex (p, &upid);
4388 pid = upid;
4390 else
4391 error (_("unknown stop reply packet: %s"), buf);
4393 else
4394 error (_("unknown stop reply packet: %s"), buf);
4395 event->ptid = pid_to_ptid (pid);
4397 break;
4400 if (non_stop && ptid_equal (event->ptid, null_ptid))
4401 error (_("No process or thread specified in stop reply: %s"), buf);
4404 /* When the stub wants to tell GDB about a new stop reply, it sends a
4405 stop notification (%Stop). Those can come it at any time, hence,
4406 we have to make sure that any pending putpkt/getpkt sequence we're
4407 making is finished, before querying the stub for more events with
4408 vStopped. E.g., if we started a vStopped sequence immediatelly
4409 upon receiving the %Stop notification, something like this could
4410 happen:
4412 1.1) --> Hg 1
4413 1.2) <-- OK
4414 1.3) --> g
4415 1.4) <-- %Stop
4416 1.5) --> vStopped
4417 1.6) <-- (registers reply to step #1.3)
4419 Obviously, the reply in step #1.6 would be unexpected to a vStopped
4420 query.
4422 To solve this, whenever we parse a %Stop notification sucessfully,
4423 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
4424 doing whatever we were doing:
4426 2.1) --> Hg 1
4427 2.2) <-- OK
4428 2.3) --> g
4429 2.4) <-- %Stop
4430 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
4431 2.5) <-- (registers reply to step #2.3)
4433 Eventualy after step #2.5, we return to the event loop, which
4434 notices there's an event on the
4435 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
4436 associated callback --- the function below. At this point, we're
4437 always safe to start a vStopped sequence. :
4439 2.6) --> vStopped
4440 2.7) <-- T05 thread:2
4441 2.8) --> vStopped
4442 2.9) --> OK
4445 static void
4446 remote_get_pending_stop_replies (void)
4448 struct remote_state *rs = get_remote_state ();
4449 int ret;
4451 if (pending_stop_reply)
4453 /* acknowledge */
4454 putpkt ("vStopped");
4456 /* Now we can rely on it. */
4457 push_stop_reply (pending_stop_reply);
4458 pending_stop_reply = NULL;
4460 while (1)
4462 getpkt (&rs->buf, &rs->buf_size, 0);
4463 if (strcmp (rs->buf, "OK") == 0)
4464 break;
4465 else
4467 struct cleanup *old_chain;
4468 struct stop_reply *stop_reply = stop_reply_xmalloc ();
4470 old_chain = make_cleanup (do_stop_reply_xfree, stop_reply);
4471 remote_parse_stop_reply (rs->buf, stop_reply);
4473 /* acknowledge */
4474 putpkt ("vStopped");
4476 if (stop_reply->ws.kind != TARGET_WAITKIND_IGNORE)
4478 /* Now we can rely on it. */
4479 discard_cleanups (old_chain);
4480 push_stop_reply (stop_reply);
4482 else
4483 /* We got an unknown stop reply. */
4484 do_cleanups (old_chain);
4491 /* Called when it is decided that STOP_REPLY holds the info of the
4492 event that is to be returned to the core. This function always
4493 destroys STOP_REPLY. */
4495 static ptid_t
4496 process_stop_reply (struct stop_reply *stop_reply,
4497 struct target_waitstatus *status)
4499 ptid_t ptid;
4501 *status = stop_reply->ws;
4502 ptid = stop_reply->ptid;
4504 /* If no thread/process was reported by the stub, assume the current
4505 inferior. */
4506 if (ptid_equal (ptid, null_ptid))
4507 ptid = inferior_ptid;
4509 if (status->kind != TARGET_WAITKIND_EXITED
4510 && status->kind != TARGET_WAITKIND_SIGNALLED)
4512 notice_new_inferiors (ptid);
4514 /* Expedited registers. */
4515 if (stop_reply->regcache)
4517 cached_reg_t *reg;
4518 int ix;
4520 for (ix = 0;
4521 VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
4522 ix++)
4523 regcache_raw_supply (get_thread_regcache (ptid),
4524 reg->num, reg->data);
4525 VEC_free (cached_reg_t, stop_reply->regcache);
4528 remote_stopped_by_watchpoint_p = stop_reply->stopped_by_watchpoint_p;
4529 remote_watch_data_address = stop_reply->watch_data_address;
4532 stop_reply_xfree (stop_reply);
4533 return ptid;
4536 /* The non-stop mode version of target_wait. */
4538 static ptid_t
4539 remote_wait_ns (ptid_t ptid, struct target_waitstatus *status)
4541 struct remote_state *rs = get_remote_state ();
4542 struct remote_arch_state *rsa = get_remote_arch_state ();
4543 ptid_t event_ptid = null_ptid;
4544 struct stop_reply *stop_reply;
4545 int ret;
4547 /* If in non-stop mode, get out of getpkt even if a
4548 notification is received. */
4550 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
4551 0 /* forever */);
4552 while (1)
4554 if (ret != -1)
4555 switch (rs->buf[0])
4557 case 'E': /* Error of some sort. */
4558 /* We're out of sync with the target now. Did it continue
4559 or not? We can't tell which thread it was in non-stop,
4560 so just ignore this. */
4561 warning (_("Remote failure reply: %s"), rs->buf);
4562 break;
4563 case 'O': /* Console output. */
4564 remote_console_output (rs->buf + 1);
4565 break;
4566 default:
4567 warning (_("Invalid remote reply: %s"), rs->buf);
4568 break;
4571 /* Acknowledge a pending stop reply that may have arrived in the
4572 mean time. */
4573 if (pending_stop_reply != NULL)
4574 remote_get_pending_stop_replies ();
4576 /* If indeed we noticed a stop reply, we're done. */
4577 stop_reply = queued_stop_reply (ptid);
4578 if (stop_reply != NULL)
4579 return process_stop_reply (stop_reply, status);
4581 /* Still no event. If we're in asynchronous mode, then just
4582 return to the event loop. */
4583 if (remote_is_async_p ())
4585 status->kind = TARGET_WAITKIND_IGNORE;
4586 return minus_one_ptid;
4589 /* Otherwise, asynchronous mode is masked, so do a blocking
4590 wait. */
4591 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
4592 1 /* forever */);
4596 /* Wait until the remote machine stops, then return, storing status in
4597 STATUS just as `wait' would. */
4599 static ptid_t
4600 remote_wait_as (ptid_t ptid, struct target_waitstatus *status)
4602 struct remote_state *rs = get_remote_state ();
4603 struct remote_arch_state *rsa = get_remote_arch_state ();
4604 ptid_t event_ptid = null_ptid;
4605 ULONGEST addr;
4606 int solibs_changed = 0;
4607 char *buf, *p;
4608 struct stop_reply *stop_reply;
4610 status->kind = TARGET_WAITKIND_IGNORE;
4611 status->value.integer = 0;
4613 stop_reply = queued_stop_reply (ptid);
4614 if (stop_reply != NULL)
4615 return process_stop_reply (stop_reply, status);
4617 if (rs->cached_wait_status)
4618 /* Use the cached wait status, but only once. */
4619 rs->cached_wait_status = 0;
4620 else
4622 int ret;
4624 if (!target_is_async_p ())
4626 ofunc = signal (SIGINT, remote_interrupt);
4627 /* If the user hit C-c before this packet, or between packets,
4628 pretend that it was hit right here. */
4629 if (quit_flag)
4631 quit_flag = 0;
4632 remote_interrupt (SIGINT);
4636 /* FIXME: cagney/1999-09-27: If we're in async mode we should
4637 _never_ wait for ever -> test on target_is_async_p().
4638 However, before we do that we need to ensure that the caller
4639 knows how to take the target into/out of async mode. */
4640 ret = getpkt_sane (&rs->buf, &rs->buf_size, wait_forever_enabled_p);
4641 if (!target_is_async_p ())
4642 signal (SIGINT, ofunc);
4645 buf = rs->buf;
4647 remote_stopped_by_watchpoint_p = 0;
4649 /* We got something. */
4650 rs->waiting_for_stop_reply = 0;
4652 switch (buf[0])
4654 case 'E': /* Error of some sort. */
4655 /* We're out of sync with the target now. Did it continue or
4656 not? Not is more likely, so report a stop. */
4657 warning (_("Remote failure reply: %s"), buf);
4658 status->kind = TARGET_WAITKIND_STOPPED;
4659 status->value.sig = TARGET_SIGNAL_0;
4660 break;
4661 case 'F': /* File-I/O request. */
4662 remote_fileio_request (buf);
4663 break;
4664 case 'T': case 'S': case 'X': case 'W':
4666 struct stop_reply *stop_reply;
4667 struct cleanup *old_chain;
4669 stop_reply = stop_reply_xmalloc ();
4670 old_chain = make_cleanup (do_stop_reply_xfree, stop_reply);
4671 remote_parse_stop_reply (buf, stop_reply);
4672 discard_cleanups (old_chain);
4673 event_ptid = process_stop_reply (stop_reply, status);
4674 break;
4676 case 'O': /* Console output. */
4677 remote_console_output (buf + 1);
4679 /* The target didn't really stop; keep waiting. */
4680 rs->waiting_for_stop_reply = 1;
4682 break;
4683 case '\0':
4684 if (last_sent_signal != TARGET_SIGNAL_0)
4686 /* Zero length reply means that we tried 'S' or 'C' and the
4687 remote system doesn't support it. */
4688 target_terminal_ours_for_output ();
4689 printf_filtered
4690 ("Can't send signals to this remote system. %s not sent.\n",
4691 target_signal_to_name (last_sent_signal));
4692 last_sent_signal = TARGET_SIGNAL_0;
4693 target_terminal_inferior ();
4695 strcpy ((char *) buf, last_sent_step ? "s" : "c");
4696 putpkt ((char *) buf);
4698 /* We just told the target to resume, so a stop reply is in
4699 order. */
4700 rs->waiting_for_stop_reply = 1;
4701 break;
4703 /* else fallthrough */
4704 default:
4705 warning (_("Invalid remote reply: %s"), buf);
4706 /* Keep waiting. */
4707 rs->waiting_for_stop_reply = 1;
4708 break;
4711 if (status->kind == TARGET_WAITKIND_IGNORE)
4712 /* Nothing interesting happened. */
4713 return minus_one_ptid;
4714 else if (status->kind != TARGET_WAITKIND_EXITED
4715 && status->kind != TARGET_WAITKIND_SIGNALLED)
4717 if (!ptid_equal (event_ptid, null_ptid))
4718 record_currthread (event_ptid);
4719 else
4720 event_ptid = inferior_ptid;
4722 else
4723 /* A process exit. Invalidate our notion of current thread. */
4724 record_currthread (minus_one_ptid);
4726 return event_ptid;
4729 /* Wait until the remote machine stops, then return, storing status in
4730 STATUS just as `wait' would. */
4732 static ptid_t
4733 remote_wait (struct target_ops *ops,
4734 ptid_t ptid, struct target_waitstatus *status)
4736 ptid_t event_ptid;
4738 if (non_stop)
4739 event_ptid = remote_wait_ns (ptid, status);
4740 else
4742 /* In synchronous mode, keep waiting until the target stops. In
4743 asynchronous mode, always return to the event loop. */
4747 event_ptid = remote_wait_as (ptid, status);
4749 while (status->kind == TARGET_WAITKIND_IGNORE
4750 && !target_can_async_p ());
4753 if (target_can_async_p ())
4755 /* If there are are events left in the queue tell the event loop
4756 to return here. */
4757 if (stop_reply_queue)
4758 mark_async_event_handler (remote_async_inferior_event_token);
4761 return event_ptid;
4764 /* Fetch a single register using a 'p' packet. */
4766 static int
4767 fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
4769 struct remote_state *rs = get_remote_state ();
4770 char *buf, *p;
4771 char regp[MAX_REGISTER_SIZE];
4772 int i;
4774 if (remote_protocol_packets[PACKET_p].support == PACKET_DISABLE)
4775 return 0;
4777 if (reg->pnum == -1)
4778 return 0;
4780 p = rs->buf;
4781 *p++ = 'p';
4782 p += hexnumstr (p, reg->pnum);
4783 *p++ = '\0';
4784 remote_send (&rs->buf, &rs->buf_size);
4786 buf = rs->buf;
4788 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
4790 case PACKET_OK:
4791 break;
4792 case PACKET_UNKNOWN:
4793 return 0;
4794 case PACKET_ERROR:
4795 error (_("Could not fetch register \"%s\""),
4796 gdbarch_register_name (get_regcache_arch (regcache), reg->regnum));
4799 /* If this register is unfetchable, tell the regcache. */
4800 if (buf[0] == 'x')
4802 regcache_raw_supply (regcache, reg->regnum, NULL);
4803 return 1;
4806 /* Otherwise, parse and supply the value. */
4807 p = buf;
4808 i = 0;
4809 while (p[0] != 0)
4811 if (p[1] == 0)
4812 error (_("fetch_register_using_p: early buf termination"));
4814 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
4815 p += 2;
4817 regcache_raw_supply (regcache, reg->regnum, regp);
4818 return 1;
4821 /* Fetch the registers included in the target's 'g' packet. */
4823 static int
4824 send_g_packet (void)
4826 struct remote_state *rs = get_remote_state ();
4827 int i, buf_len;
4828 char *p;
4829 char *regs;
4831 sprintf (rs->buf, "g");
4832 remote_send (&rs->buf, &rs->buf_size);
4834 /* We can get out of synch in various cases. If the first character
4835 in the buffer is not a hex character, assume that has happened
4836 and try to fetch another packet to read. */
4837 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
4838 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
4839 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
4840 && rs->buf[0] != 'x') /* New: unavailable register value. */
4842 if (remote_debug)
4843 fprintf_unfiltered (gdb_stdlog,
4844 "Bad register packet; fetching a new packet\n");
4845 getpkt (&rs->buf, &rs->buf_size, 0);
4848 buf_len = strlen (rs->buf);
4850 /* Sanity check the received packet. */
4851 if (buf_len % 2 != 0)
4852 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
4854 return buf_len / 2;
4857 static void
4858 process_g_packet (struct regcache *regcache)
4860 struct gdbarch *gdbarch = get_regcache_arch (regcache);
4861 struct remote_state *rs = get_remote_state ();
4862 struct remote_arch_state *rsa = get_remote_arch_state ();
4863 int i, buf_len;
4864 char *p;
4865 char *regs;
4867 buf_len = strlen (rs->buf);
4869 /* Further sanity checks, with knowledge of the architecture. */
4870 if (buf_len > 2 * rsa->sizeof_g_packet)
4871 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
4873 /* Save the size of the packet sent to us by the target. It is used
4874 as a heuristic when determining the max size of packets that the
4875 target can safely receive. */
4876 if (rsa->actual_register_packet_size == 0)
4877 rsa->actual_register_packet_size = buf_len;
4879 /* If this is smaller than we guessed the 'g' packet would be,
4880 update our records. A 'g' reply that doesn't include a register's
4881 value implies either that the register is not available, or that
4882 the 'p' packet must be used. */
4883 if (buf_len < 2 * rsa->sizeof_g_packet)
4885 rsa->sizeof_g_packet = buf_len / 2;
4887 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
4889 if (rsa->regs[i].pnum == -1)
4890 continue;
4892 if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
4893 rsa->regs[i].in_g_packet = 0;
4894 else
4895 rsa->regs[i].in_g_packet = 1;
4899 regs = alloca (rsa->sizeof_g_packet);
4901 /* Unimplemented registers read as all bits zero. */
4902 memset (regs, 0, rsa->sizeof_g_packet);
4904 /* Reply describes registers byte by byte, each byte encoded as two
4905 hex characters. Suck them all up, then supply them to the
4906 register cacheing/storage mechanism. */
4908 p = rs->buf;
4909 for (i = 0; i < rsa->sizeof_g_packet; i++)
4911 if (p[0] == 0 || p[1] == 0)
4912 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
4913 internal_error (__FILE__, __LINE__,
4914 "unexpected end of 'g' packet reply");
4916 if (p[0] == 'x' && p[1] == 'x')
4917 regs[i] = 0; /* 'x' */
4918 else
4919 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
4920 p += 2;
4924 int i;
4925 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
4927 struct packet_reg *r = &rsa->regs[i];
4928 if (r->in_g_packet)
4930 if (r->offset * 2 >= strlen (rs->buf))
4931 /* This shouldn't happen - we adjusted in_g_packet above. */
4932 internal_error (__FILE__, __LINE__,
4933 "unexpected end of 'g' packet reply");
4934 else if (rs->buf[r->offset * 2] == 'x')
4936 gdb_assert (r->offset * 2 < strlen (rs->buf));
4937 /* The register isn't available, mark it as such (at
4938 the same time setting the value to zero). */
4939 regcache_raw_supply (regcache, r->regnum, NULL);
4941 else
4942 regcache_raw_supply (regcache, r->regnum,
4943 regs + r->offset);
4949 static void
4950 fetch_registers_using_g (struct regcache *regcache)
4952 send_g_packet ();
4953 process_g_packet (regcache);
4956 static void
4957 remote_fetch_registers (struct regcache *regcache, int regnum)
4959 struct remote_state *rs = get_remote_state ();
4960 struct remote_arch_state *rsa = get_remote_arch_state ();
4961 int i;
4963 set_general_thread (inferior_ptid);
4965 if (regnum >= 0)
4967 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
4968 gdb_assert (reg != NULL);
4970 /* If this register might be in the 'g' packet, try that first -
4971 we are likely to read more than one register. If this is the
4972 first 'g' packet, we might be overly optimistic about its
4973 contents, so fall back to 'p'. */
4974 if (reg->in_g_packet)
4976 fetch_registers_using_g (regcache);
4977 if (reg->in_g_packet)
4978 return;
4981 if (fetch_register_using_p (regcache, reg))
4982 return;
4984 /* This register is not available. */
4985 regcache_raw_supply (regcache, reg->regnum, NULL);
4987 return;
4990 fetch_registers_using_g (regcache);
4992 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
4993 if (!rsa->regs[i].in_g_packet)
4994 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
4996 /* This register is not available. */
4997 regcache_raw_supply (regcache, i, NULL);
5001 /* Prepare to store registers. Since we may send them all (using a
5002 'G' request), we have to read out the ones we don't want to change
5003 first. */
5005 static void
5006 remote_prepare_to_store (struct regcache *regcache)
5008 struct remote_arch_state *rsa = get_remote_arch_state ();
5009 int i;
5010 gdb_byte buf[MAX_REGISTER_SIZE];
5012 /* Make sure the entire registers array is valid. */
5013 switch (remote_protocol_packets[PACKET_P].support)
5015 case PACKET_DISABLE:
5016 case PACKET_SUPPORT_UNKNOWN:
5017 /* Make sure all the necessary registers are cached. */
5018 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
5019 if (rsa->regs[i].in_g_packet)
5020 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
5021 break;
5022 case PACKET_ENABLE:
5023 break;
5027 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
5028 packet was not recognized. */
5030 static int
5031 store_register_using_P (const struct regcache *regcache, struct packet_reg *reg)
5033 struct gdbarch *gdbarch = get_regcache_arch (regcache);
5034 struct remote_state *rs = get_remote_state ();
5035 struct remote_arch_state *rsa = get_remote_arch_state ();
5036 /* Try storing a single register. */
5037 char *buf = rs->buf;
5038 gdb_byte regp[MAX_REGISTER_SIZE];
5039 char *p;
5041 if (remote_protocol_packets[PACKET_P].support == PACKET_DISABLE)
5042 return 0;
5044 if (reg->pnum == -1)
5045 return 0;
5047 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
5048 p = buf + strlen (buf);
5049 regcache_raw_collect (regcache, reg->regnum, regp);
5050 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
5051 remote_send (&rs->buf, &rs->buf_size);
5053 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
5055 case PACKET_OK:
5056 return 1;
5057 case PACKET_ERROR:
5058 error (_("Could not write register \"%s\""),
5059 gdbarch_register_name (gdbarch, reg->regnum));
5060 case PACKET_UNKNOWN:
5061 return 0;
5062 default:
5063 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
5067 /* Store register REGNUM, or all registers if REGNUM == -1, from the
5068 contents of the register cache buffer. FIXME: ignores errors. */
5070 static void
5071 store_registers_using_G (const struct regcache *regcache)
5073 struct remote_state *rs = get_remote_state ();
5074 struct remote_arch_state *rsa = get_remote_arch_state ();
5075 gdb_byte *regs;
5076 char *p;
5078 /* Extract all the registers in the regcache copying them into a
5079 local buffer. */
5081 int i;
5082 regs = alloca (rsa->sizeof_g_packet);
5083 memset (regs, 0, rsa->sizeof_g_packet);
5084 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
5086 struct packet_reg *r = &rsa->regs[i];
5087 if (r->in_g_packet)
5088 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
5092 /* Command describes registers byte by byte,
5093 each byte encoded as two hex characters. */
5094 p = rs->buf;
5095 *p++ = 'G';
5096 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
5097 updated. */
5098 bin2hex (regs, p, rsa->sizeof_g_packet);
5099 remote_send (&rs->buf, &rs->buf_size);
5102 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
5103 of the register cache buffer. FIXME: ignores errors. */
5105 static void
5106 remote_store_registers (struct regcache *regcache, int regnum)
5108 struct remote_state *rs = get_remote_state ();
5109 struct remote_arch_state *rsa = get_remote_arch_state ();
5110 int i;
5112 set_general_thread (inferior_ptid);
5114 if (regnum >= 0)
5116 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
5117 gdb_assert (reg != NULL);
5119 /* Always prefer to store registers using the 'P' packet if
5120 possible; we often change only a small number of registers.
5121 Sometimes we change a larger number; we'd need help from a
5122 higher layer to know to use 'G'. */
5123 if (store_register_using_P (regcache, reg))
5124 return;
5126 /* For now, don't complain if we have no way to write the
5127 register. GDB loses track of unavailable registers too
5128 easily. Some day, this may be an error. We don't have
5129 any way to read the register, either... */
5130 if (!reg->in_g_packet)
5131 return;
5133 store_registers_using_G (regcache);
5134 return;
5137 store_registers_using_G (regcache);
5139 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
5140 if (!rsa->regs[i].in_g_packet)
5141 if (!store_register_using_P (regcache, &rsa->regs[i]))
5142 /* See above for why we do not issue an error here. */
5143 continue;
5147 /* Return the number of hex digits in num. */
5149 static int
5150 hexnumlen (ULONGEST num)
5152 int i;
5154 for (i = 0; num != 0; i++)
5155 num >>= 4;
5157 return max (i, 1);
5160 /* Set BUF to the minimum number of hex digits representing NUM. */
5162 static int
5163 hexnumstr (char *buf, ULONGEST num)
5165 int len = hexnumlen (num);
5166 return hexnumnstr (buf, num, len);
5170 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
5172 static int
5173 hexnumnstr (char *buf, ULONGEST num, int width)
5175 int i;
5177 buf[width] = '\0';
5179 for (i = width - 1; i >= 0; i--)
5181 buf[i] = "0123456789abcdef"[(num & 0xf)];
5182 num >>= 4;
5185 return width;
5188 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
5190 static CORE_ADDR
5191 remote_address_masked (CORE_ADDR addr)
5193 int address_size = remote_address_size;
5194 /* If "remoteaddresssize" was not set, default to target address size. */
5195 if (!address_size)
5196 address_size = gdbarch_addr_bit (target_gdbarch);
5198 if (address_size > 0
5199 && address_size < (sizeof (ULONGEST) * 8))
5201 /* Only create a mask when that mask can safely be constructed
5202 in a ULONGEST variable. */
5203 ULONGEST mask = 1;
5204 mask = (mask << address_size) - 1;
5205 addr &= mask;
5207 return addr;
5210 /* Convert BUFFER, binary data at least LEN bytes long, into escaped
5211 binary data in OUT_BUF. Set *OUT_LEN to the length of the data
5212 encoded in OUT_BUF, and return the number of bytes in OUT_BUF
5213 (which may be more than *OUT_LEN due to escape characters). The
5214 total number of bytes in the output buffer will be at most
5215 OUT_MAXLEN. */
5217 static int
5218 remote_escape_output (const gdb_byte *buffer, int len,
5219 gdb_byte *out_buf, int *out_len,
5220 int out_maxlen)
5222 int input_index, output_index;
5224 output_index = 0;
5225 for (input_index = 0; input_index < len; input_index++)
5227 gdb_byte b = buffer[input_index];
5229 if (b == '$' || b == '#' || b == '}')
5231 /* These must be escaped. */
5232 if (output_index + 2 > out_maxlen)
5233 break;
5234 out_buf[output_index++] = '}';
5235 out_buf[output_index++] = b ^ 0x20;
5237 else
5239 if (output_index + 1 > out_maxlen)
5240 break;
5241 out_buf[output_index++] = b;
5245 *out_len = input_index;
5246 return output_index;
5249 /* Convert BUFFER, escaped data LEN bytes long, into binary data
5250 in OUT_BUF. Return the number of bytes written to OUT_BUF.
5251 Raise an error if the total number of bytes exceeds OUT_MAXLEN.
5253 This function reverses remote_escape_output. It allows more
5254 escaped characters than that function does, in particular because
5255 '*' must be escaped to avoid the run-length encoding processing
5256 in reading packets. */
5258 static int
5259 remote_unescape_input (const gdb_byte *buffer, int len,
5260 gdb_byte *out_buf, int out_maxlen)
5262 int input_index, output_index;
5263 int escaped;
5265 output_index = 0;
5266 escaped = 0;
5267 for (input_index = 0; input_index < len; input_index++)
5269 gdb_byte b = buffer[input_index];
5271 if (output_index + 1 > out_maxlen)
5273 warning (_("Received too much data from remote target;"
5274 " ignoring overflow."));
5275 return output_index;
5278 if (escaped)
5280 out_buf[output_index++] = b ^ 0x20;
5281 escaped = 0;
5283 else if (b == '}')
5284 escaped = 1;
5285 else
5286 out_buf[output_index++] = b;
5289 if (escaped)
5290 error (_("Unmatched escape character in target response."));
5292 return output_index;
5295 /* Determine whether the remote target supports binary downloading.
5296 This is accomplished by sending a no-op memory write of zero length
5297 to the target at the specified address. It does not suffice to send
5298 the whole packet, since many stubs strip the eighth bit and
5299 subsequently compute a wrong checksum, which causes real havoc with
5300 remote_write_bytes.
5302 NOTE: This can still lose if the serial line is not eight-bit
5303 clean. In cases like this, the user should clear "remote
5304 X-packet". */
5306 static void
5307 check_binary_download (CORE_ADDR addr)
5309 struct remote_state *rs = get_remote_state ();
5311 switch (remote_protocol_packets[PACKET_X].support)
5313 case PACKET_DISABLE:
5314 break;
5315 case PACKET_ENABLE:
5316 break;
5317 case PACKET_SUPPORT_UNKNOWN:
5319 char *p;
5321 p = rs->buf;
5322 *p++ = 'X';
5323 p += hexnumstr (p, (ULONGEST) addr);
5324 *p++ = ',';
5325 p += hexnumstr (p, (ULONGEST) 0);
5326 *p++ = ':';
5327 *p = '\0';
5329 putpkt_binary (rs->buf, (int) (p - rs->buf));
5330 getpkt (&rs->buf, &rs->buf_size, 0);
5332 if (rs->buf[0] == '\0')
5334 if (remote_debug)
5335 fprintf_unfiltered (gdb_stdlog,
5336 "binary downloading NOT suppported by target\n");
5337 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
5339 else
5341 if (remote_debug)
5342 fprintf_unfiltered (gdb_stdlog,
5343 "binary downloading suppported by target\n");
5344 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
5346 break;
5351 /* Write memory data directly to the remote machine.
5352 This does not inform the data cache; the data cache uses this.
5353 HEADER is the starting part of the packet.
5354 MEMADDR is the address in the remote memory space.
5355 MYADDR is the address of the buffer in our space.
5356 LEN is the number of bytes.
5357 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
5358 should send data as binary ('X'), or hex-encoded ('M').
5360 The function creates packet of the form
5361 <HEADER><ADDRESS>,<LENGTH>:<DATA>
5363 where encoding of <DATA> is termined by PACKET_FORMAT.
5365 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
5366 are omitted.
5368 Returns the number of bytes transferred, or 0 (setting errno) for
5369 error. Only transfer a single packet. */
5371 static int
5372 remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
5373 const gdb_byte *myaddr, int len,
5374 char packet_format, int use_length)
5376 struct remote_state *rs = get_remote_state ();
5377 char *p;
5378 char *plen = NULL;
5379 int plenlen = 0;
5380 int todo;
5381 int nr_bytes;
5382 int payload_size;
5383 int payload_length;
5384 int header_length;
5386 if (packet_format != 'X' && packet_format != 'M')
5387 internal_error (__FILE__, __LINE__,
5388 "remote_write_bytes_aux: bad packet format");
5390 if (len <= 0)
5391 return 0;
5393 payload_size = get_memory_write_packet_size ();
5395 /* The packet buffer will be large enough for the payload;
5396 get_memory_packet_size ensures this. */
5397 rs->buf[0] = '\0';
5399 /* Compute the size of the actual payload by subtracting out the
5400 packet header and footer overhead: "$M<memaddr>,<len>:...#nn".
5402 payload_size -= strlen ("$,:#NN");
5403 if (!use_length)
5404 /* The comma won't be used. */
5405 payload_size += 1;
5406 header_length = strlen (header);
5407 payload_size -= header_length;
5408 payload_size -= hexnumlen (memaddr);
5410 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
5412 strcat (rs->buf, header);
5413 p = rs->buf + strlen (header);
5415 /* Compute a best guess of the number of bytes actually transfered. */
5416 if (packet_format == 'X')
5418 /* Best guess at number of bytes that will fit. */
5419 todo = min (len, payload_size);
5420 if (use_length)
5421 payload_size -= hexnumlen (todo);
5422 todo = min (todo, payload_size);
5424 else
5426 /* Num bytes that will fit. */
5427 todo = min (len, payload_size / 2);
5428 if (use_length)
5429 payload_size -= hexnumlen (todo);
5430 todo = min (todo, payload_size / 2);
5433 if (todo <= 0)
5434 internal_error (__FILE__, __LINE__,
5435 _("minumum packet size too small to write data"));
5437 /* If we already need another packet, then try to align the end
5438 of this packet to a useful boundary. */
5439 if (todo > 2 * REMOTE_ALIGN_WRITES && todo < len)
5440 todo = ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
5442 /* Append "<memaddr>". */
5443 memaddr = remote_address_masked (memaddr);
5444 p += hexnumstr (p, (ULONGEST) memaddr);
5446 if (use_length)
5448 /* Append ",". */
5449 *p++ = ',';
5451 /* Append <len>. Retain the location/size of <len>. It may need to
5452 be adjusted once the packet body has been created. */
5453 plen = p;
5454 plenlen = hexnumstr (p, (ULONGEST) todo);
5455 p += plenlen;
5458 /* Append ":". */
5459 *p++ = ':';
5460 *p = '\0';
5462 /* Append the packet body. */
5463 if (packet_format == 'X')
5465 /* Binary mode. Send target system values byte by byte, in
5466 increasing byte addresses. Only escape certain critical
5467 characters. */
5468 payload_length = remote_escape_output (myaddr, todo, p, &nr_bytes,
5469 payload_size);
5471 /* If not all TODO bytes fit, then we'll need another packet. Make
5472 a second try to keep the end of the packet aligned. Don't do
5473 this if the packet is tiny. */
5474 if (nr_bytes < todo && nr_bytes > 2 * REMOTE_ALIGN_WRITES)
5476 int new_nr_bytes;
5478 new_nr_bytes = (((memaddr + nr_bytes) & ~(REMOTE_ALIGN_WRITES - 1))
5479 - memaddr);
5480 if (new_nr_bytes != nr_bytes)
5481 payload_length = remote_escape_output (myaddr, new_nr_bytes,
5482 p, &nr_bytes,
5483 payload_size);
5486 p += payload_length;
5487 if (use_length && nr_bytes < todo)
5489 /* Escape chars have filled up the buffer prematurely,
5490 and we have actually sent fewer bytes than planned.
5491 Fix-up the length field of the packet. Use the same
5492 number of characters as before. */
5493 plen += hexnumnstr (plen, (ULONGEST) nr_bytes, plenlen);
5494 *plen = ':'; /* overwrite \0 from hexnumnstr() */
5497 else
5499 /* Normal mode: Send target system values byte by byte, in
5500 increasing byte addresses. Each byte is encoded as a two hex
5501 value. */
5502 nr_bytes = bin2hex (myaddr, p, todo);
5503 p += 2 * nr_bytes;
5506 putpkt_binary (rs->buf, (int) (p - rs->buf));
5507 getpkt (&rs->buf, &rs->buf_size, 0);
5509 if (rs->buf[0] == 'E')
5511 /* There is no correspondance between what the remote protocol
5512 uses for errors and errno codes. We would like a cleaner way
5513 of representing errors (big enough to include errno codes,
5514 bfd_error codes, and others). But for now just return EIO. */
5515 errno = EIO;
5516 return 0;
5519 /* Return NR_BYTES, not TODO, in case escape chars caused us to send
5520 fewer bytes than we'd planned. */
5521 return nr_bytes;
5524 /* Write memory data directly to the remote machine.
5525 This does not inform the data cache; the data cache uses this.
5526 MEMADDR is the address in the remote memory space.
5527 MYADDR is the address of the buffer in our space.
5528 LEN is the number of bytes.
5530 Returns number of bytes transferred, or 0 (setting errno) for
5531 error. Only transfer a single packet. */
5534 remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, int len)
5536 char *packet_format = 0;
5538 /* Check whether the target supports binary download. */
5539 check_binary_download (memaddr);
5541 switch (remote_protocol_packets[PACKET_X].support)
5543 case PACKET_ENABLE:
5544 packet_format = "X";
5545 break;
5546 case PACKET_DISABLE:
5547 packet_format = "M";
5548 break;
5549 case PACKET_SUPPORT_UNKNOWN:
5550 internal_error (__FILE__, __LINE__,
5551 _("remote_write_bytes: bad internal state"));
5552 default:
5553 internal_error (__FILE__, __LINE__, _("bad switch"));
5556 return remote_write_bytes_aux (packet_format,
5557 memaddr, myaddr, len, packet_format[0], 1);
5560 /* Read memory data directly from the remote machine.
5561 This does not use the data cache; the data cache uses this.
5562 MEMADDR is the address in the remote memory space.
5563 MYADDR is the address of the buffer in our space.
5564 LEN is the number of bytes.
5566 Returns number of bytes transferred, or 0 for error. */
5568 /* NOTE: cagney/1999-10-18: This function (and its siblings in other
5569 remote targets) shouldn't attempt to read the entire buffer.
5570 Instead it should read a single packet worth of data and then
5571 return the byte size of that packet to the caller. The caller (its
5572 caller and its callers caller ;-) already contains code for
5573 handling partial reads. */
5576 remote_read_bytes (CORE_ADDR memaddr, gdb_byte *myaddr, int len)
5578 struct remote_state *rs = get_remote_state ();
5579 int max_buf_size; /* Max size of packet output buffer. */
5580 int origlen;
5582 if (len <= 0)
5583 return 0;
5585 max_buf_size = get_memory_read_packet_size ();
5586 /* The packet buffer will be large enough for the payload;
5587 get_memory_packet_size ensures this. */
5589 origlen = len;
5590 while (len > 0)
5592 char *p;
5593 int todo;
5594 int i;
5596 todo = min (len, max_buf_size / 2); /* num bytes that will fit */
5598 /* construct "m"<memaddr>","<len>" */
5599 /* sprintf (rs->buf, "m%lx,%x", (unsigned long) memaddr, todo); */
5600 memaddr = remote_address_masked (memaddr);
5601 p = rs->buf;
5602 *p++ = 'm';
5603 p += hexnumstr (p, (ULONGEST) memaddr);
5604 *p++ = ',';
5605 p += hexnumstr (p, (ULONGEST) todo);
5606 *p = '\0';
5608 putpkt (rs->buf);
5609 getpkt (&rs->buf, &rs->buf_size, 0);
5611 if (rs->buf[0] == 'E'
5612 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
5613 && rs->buf[3] == '\0')
5615 /* There is no correspondance between what the remote
5616 protocol uses for errors and errno codes. We would like
5617 a cleaner way of representing errors (big enough to
5618 include errno codes, bfd_error codes, and others). But
5619 for now just return EIO. */
5620 errno = EIO;
5621 return 0;
5624 /* Reply describes memory byte by byte,
5625 each byte encoded as two hex characters. */
5627 p = rs->buf;
5628 if ((i = hex2bin (p, myaddr, todo)) < todo)
5630 /* Reply is short. This means that we were able to read
5631 only part of what we wanted to. */
5632 return i + (origlen - len);
5634 myaddr += todo;
5635 memaddr += todo;
5636 len -= todo;
5638 return origlen;
5642 /* Remote notification handler. */
5644 static void
5645 handle_notification (char *buf, size_t length)
5647 if (strncmp (buf, "Stop:", 5) == 0)
5649 if (pending_stop_reply)
5650 /* We've already parsed the in-flight stop-reply, but the stub
5651 for some reason thought we didn't, possibly due to timeout
5652 on its side. Just ignore it. */
5654 else
5656 struct cleanup *old_chain;
5657 struct stop_reply *reply = stop_reply_xmalloc ();
5658 old_chain = make_cleanup (do_stop_reply_xfree, reply);
5660 remote_parse_stop_reply (buf + 5, reply);
5662 discard_cleanups (old_chain);
5664 /* Be careful to only set it after parsing, since an error
5665 may be thrown then. */
5666 pending_stop_reply = reply;
5668 /* Notify the event loop there's a stop reply to acknowledge
5669 and that there may be more events to fetch. */
5670 mark_async_event_handler (remote_async_get_pending_events_token);
5673 else
5674 /* We ignore notifications we don't recognize, for compatibility
5675 with newer stubs. */
5680 /* Read or write LEN bytes from inferior memory at MEMADDR,
5681 transferring to or from debugger address BUFFER. Write to inferior
5682 if SHOULD_WRITE is nonzero. Returns length of data written or
5683 read; 0 for error. TARGET is unused. */
5685 static int
5686 remote_xfer_memory (CORE_ADDR mem_addr, gdb_byte *buffer, int mem_len,
5687 int should_write, struct mem_attrib *attrib,
5688 struct target_ops *target)
5690 int res;
5692 set_general_thread (inferior_ptid);
5694 if (should_write)
5695 res = remote_write_bytes (mem_addr, buffer, mem_len);
5696 else
5697 res = remote_read_bytes (mem_addr, buffer, mem_len);
5699 return res;
5702 /* Sends a packet with content determined by the printf format string
5703 FORMAT and the remaining arguments, then gets the reply. Returns
5704 whether the packet was a success, a failure, or unknown. */
5706 enum packet_result
5707 remote_send_printf (const char *format, ...)
5709 struct remote_state *rs = get_remote_state ();
5710 int max_size = get_remote_packet_size ();
5712 va_list ap;
5713 va_start (ap, format);
5715 rs->buf[0] = '\0';
5716 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
5717 internal_error (__FILE__, __LINE__, "Too long remote packet.");
5719 if (putpkt (rs->buf) < 0)
5720 error (_("Communication problem with target."));
5722 rs->buf[0] = '\0';
5723 getpkt (&rs->buf, &rs->buf_size, 0);
5725 return packet_check_result (rs->buf);
5728 static void
5729 restore_remote_timeout (void *p)
5731 int value = *(int *)p;
5732 remote_timeout = value;
5735 /* Flash writing can take quite some time. We'll set
5736 effectively infinite timeout for flash operations.
5737 In future, we'll need to decide on a better approach. */
5738 static const int remote_flash_timeout = 1000;
5740 static void
5741 remote_flash_erase (struct target_ops *ops,
5742 ULONGEST address, LONGEST length)
5744 int saved_remote_timeout = remote_timeout;
5745 enum packet_result ret;
5747 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
5748 &saved_remote_timeout);
5749 remote_timeout = remote_flash_timeout;
5751 ret = remote_send_printf ("vFlashErase:%s,%s",
5752 paddr (address),
5753 phex (length, 4));
5754 switch (ret)
5756 case PACKET_UNKNOWN:
5757 error (_("Remote target does not support flash erase"));
5758 case PACKET_ERROR:
5759 error (_("Error erasing flash with vFlashErase packet"));
5760 default:
5761 break;
5764 do_cleanups (back_to);
5767 static LONGEST
5768 remote_flash_write (struct target_ops *ops,
5769 ULONGEST address, LONGEST length,
5770 const gdb_byte *data)
5772 int saved_remote_timeout = remote_timeout;
5773 int ret;
5774 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
5775 &saved_remote_timeout);
5777 remote_timeout = remote_flash_timeout;
5778 ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length, 'X', 0);
5779 do_cleanups (back_to);
5781 return ret;
5784 static void
5785 remote_flash_done (struct target_ops *ops)
5787 int saved_remote_timeout = remote_timeout;
5788 int ret;
5789 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
5790 &saved_remote_timeout);
5792 remote_timeout = remote_flash_timeout;
5793 ret = remote_send_printf ("vFlashDone");
5794 do_cleanups (back_to);
5796 switch (ret)
5798 case PACKET_UNKNOWN:
5799 error (_("Remote target does not support vFlashDone"));
5800 case PACKET_ERROR:
5801 error (_("Error finishing flash operation"));
5802 default:
5803 break;
5807 static void
5808 remote_files_info (struct target_ops *ignore)
5810 puts_filtered ("Debugging a target over a serial line.\n");
5813 /* Stuff for dealing with the packets which are part of this protocol.
5814 See comment at top of file for details. */
5816 /* Read a single character from the remote end. */
5818 static int
5819 readchar (int timeout)
5821 int ch;
5823 ch = serial_readchar (remote_desc, timeout);
5825 if (ch >= 0)
5826 return ch;
5828 switch ((enum serial_rc) ch)
5830 case SERIAL_EOF:
5831 pop_target ();
5832 error (_("Remote connection closed"));
5833 /* no return */
5834 case SERIAL_ERROR:
5835 perror_with_name (_("Remote communication error"));
5836 /* no return */
5837 case SERIAL_TIMEOUT:
5838 break;
5840 return ch;
5843 /* Send the command in *BUF to the remote machine, and read the reply
5844 into *BUF. Report an error if we get an error reply. Resize
5845 *BUF using xrealloc if necessary to hold the result, and update
5846 *SIZEOF_BUF. */
5848 static void
5849 remote_send (char **buf,
5850 long *sizeof_buf)
5852 putpkt (*buf);
5853 getpkt (buf, sizeof_buf, 0);
5855 if ((*buf)[0] == 'E')
5856 error (_("Remote failure reply: %s"), *buf);
5859 /* Return a pointer to an xmalloc'ed string representing an escaped
5860 version of BUF, of len N. E.g. \n is converted to \\n, \t to \\t,
5861 etc. The caller is responsible for releasing the returned
5862 memory. */
5864 static char *
5865 escape_buffer (const char *buf, int n)
5867 struct cleanup *old_chain;
5868 struct ui_file *stb;
5869 char *str;
5870 long length;
5872 stb = mem_fileopen ();
5873 old_chain = make_cleanup_ui_file_delete (stb);
5875 fputstrn_unfiltered (buf, n, 0, stb);
5876 str = ui_file_xstrdup (stb, &length);
5877 do_cleanups (old_chain);
5878 return str;
5881 /* Display a null-terminated packet on stdout, for debugging, using C
5882 string notation. */
5884 static void
5885 print_packet (char *buf)
5887 puts_filtered ("\"");
5888 fputstr_filtered (buf, '"', gdb_stdout);
5889 puts_filtered ("\"");
5893 putpkt (char *buf)
5895 return putpkt_binary (buf, strlen (buf));
5898 /* Send a packet to the remote machine, with error checking. The data
5899 of the packet is in BUF. The string in BUF can be at most
5900 get_remote_packet_size () - 5 to account for the $, # and checksum,
5901 and for a possible /0 if we are debugging (remote_debug) and want
5902 to print the sent packet as a string. */
5904 static int
5905 putpkt_binary (char *buf, int cnt)
5907 struct remote_state *rs = get_remote_state ();
5908 int i;
5909 unsigned char csum = 0;
5910 char *buf2 = alloca (cnt + 6);
5912 int ch;
5913 int tcount = 0;
5914 char *p;
5916 /* Catch cases like trying to read memory or listing threads while
5917 we're waiting for a stop reply. The remote server wouldn't be
5918 ready to handle this request, so we'd hang and timeout. We don't
5919 have to worry about this in synchronous mode, because in that
5920 case it's not possible to issue a command while the target is
5921 running. This is not a problem in non-stop mode, because in that
5922 case, the stub is always ready to process serial input. */
5923 if (!non_stop && target_can_async_p () && rs->waiting_for_stop_reply)
5924 error (_("Cannot execute this command while the target is running."));
5926 /* We're sending out a new packet. Make sure we don't look at a
5927 stale cached response. */
5928 rs->cached_wait_status = 0;
5930 /* Copy the packet into buffer BUF2, encapsulating it
5931 and giving it a checksum. */
5933 p = buf2;
5934 *p++ = '$';
5936 for (i = 0; i < cnt; i++)
5938 csum += buf[i];
5939 *p++ = buf[i];
5941 *p++ = '#';
5942 *p++ = tohex ((csum >> 4) & 0xf);
5943 *p++ = tohex (csum & 0xf);
5945 /* Send it over and over until we get a positive ack. */
5947 while (1)
5949 int started_error_output = 0;
5951 if (remote_debug)
5953 struct cleanup *old_chain;
5954 char *str;
5956 *p = '\0';
5957 str = escape_buffer (buf2, p - buf2);
5958 old_chain = make_cleanup (xfree, str);
5959 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
5960 gdb_flush (gdb_stdlog);
5961 do_cleanups (old_chain);
5963 if (serial_write (remote_desc, buf2, p - buf2))
5964 perror_with_name (_("putpkt: write failed"));
5966 /* If this is a no acks version of the remote protocol, send the
5967 packet and move on. */
5968 if (rs->noack_mode)
5969 break;
5971 /* Read until either a timeout occurs (-2) or '+' is read.
5972 Handle any notification that arrives in the mean time. */
5973 while (1)
5975 ch = readchar (remote_timeout);
5977 if (remote_debug)
5979 switch (ch)
5981 case '+':
5982 case '-':
5983 case SERIAL_TIMEOUT:
5984 case '$':
5985 case '%':
5986 if (started_error_output)
5988 putchar_unfiltered ('\n');
5989 started_error_output = 0;
5994 switch (ch)
5996 case '+':
5997 if (remote_debug)
5998 fprintf_unfiltered (gdb_stdlog, "Ack\n");
5999 return 1;
6000 case '-':
6001 if (remote_debug)
6002 fprintf_unfiltered (gdb_stdlog, "Nak\n");
6003 case SERIAL_TIMEOUT:
6004 tcount++;
6005 if (tcount > 3)
6006 return 0;
6007 break; /* Retransmit buffer. */
6008 case '$':
6010 if (remote_debug)
6011 fprintf_unfiltered (gdb_stdlog,
6012 "Packet instead of Ack, ignoring it\n");
6013 /* It's probably an old response sent because an ACK
6014 was lost. Gobble up the packet and ack it so it
6015 doesn't get retransmitted when we resend this
6016 packet. */
6017 skip_frame ();
6018 serial_write (remote_desc, "+", 1);
6019 continue; /* Now, go look for +. */
6022 case '%':
6024 int val;
6026 /* If we got a notification, handle it, and go back to looking
6027 for an ack. */
6028 /* We've found the start of a notification. Now
6029 collect the data. */
6030 val = read_frame (&rs->buf, &rs->buf_size);
6031 if (val >= 0)
6033 if (remote_debug)
6035 struct cleanup *old_chain;
6036 char *str;
6038 str = escape_buffer (rs->buf, val);
6039 old_chain = make_cleanup (xfree, str);
6040 fprintf_unfiltered (gdb_stdlog,
6041 " Notification received: %s\n",
6042 str);
6043 do_cleanups (old_chain);
6045 handle_notification (rs->buf, val);
6046 /* We're in sync now, rewait for the ack. */
6047 tcount = 0;
6049 else
6051 if (remote_debug)
6053 if (!started_error_output)
6055 started_error_output = 1;
6056 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
6058 fputc_unfiltered (ch & 0177, gdb_stdlog);
6059 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
6062 continue;
6064 /* fall-through */
6065 default:
6066 if (remote_debug)
6068 if (!started_error_output)
6070 started_error_output = 1;
6071 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
6073 fputc_unfiltered (ch & 0177, gdb_stdlog);
6075 continue;
6077 break; /* Here to retransmit. */
6080 #if 0
6081 /* This is wrong. If doing a long backtrace, the user should be
6082 able to get out next time we call QUIT, without anything as
6083 violent as interrupt_query. If we want to provide a way out of
6084 here without getting to the next QUIT, it should be based on
6085 hitting ^C twice as in remote_wait. */
6086 if (quit_flag)
6088 quit_flag = 0;
6089 interrupt_query ();
6091 #endif
6093 return 0;
6096 /* Come here after finding the start of a frame when we expected an
6097 ack. Do our best to discard the rest of this packet. */
6099 static void
6100 skip_frame (void)
6102 int c;
6104 while (1)
6106 c = readchar (remote_timeout);
6107 switch (c)
6109 case SERIAL_TIMEOUT:
6110 /* Nothing we can do. */
6111 return;
6112 case '#':
6113 /* Discard the two bytes of checksum and stop. */
6114 c = readchar (remote_timeout);
6115 if (c >= 0)
6116 c = readchar (remote_timeout);
6118 return;
6119 case '*': /* Run length encoding. */
6120 /* Discard the repeat count. */
6121 c = readchar (remote_timeout);
6122 if (c < 0)
6123 return;
6124 break;
6125 default:
6126 /* A regular character. */
6127 break;
6132 /* Come here after finding the start of the frame. Collect the rest
6133 into *BUF, verifying the checksum, length, and handling run-length
6134 compression. NUL terminate the buffer. If there is not enough room,
6135 expand *BUF using xrealloc.
6137 Returns -1 on error, number of characters in buffer (ignoring the
6138 trailing NULL) on success. (could be extended to return one of the
6139 SERIAL status indications). */
6141 static long
6142 read_frame (char **buf_p,
6143 long *sizeof_buf)
6145 unsigned char csum;
6146 long bc;
6147 int c;
6148 char *buf = *buf_p;
6149 struct remote_state *rs = get_remote_state ();
6151 csum = 0;
6152 bc = 0;
6154 while (1)
6156 c = readchar (remote_timeout);
6157 switch (c)
6159 case SERIAL_TIMEOUT:
6160 if (remote_debug)
6161 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
6162 return -1;
6163 case '$':
6164 if (remote_debug)
6165 fputs_filtered ("Saw new packet start in middle of old one\n",
6166 gdb_stdlog);
6167 return -1; /* Start a new packet, count retries. */
6168 case '#':
6170 unsigned char pktcsum;
6171 int check_0 = 0;
6172 int check_1 = 0;
6174 buf[bc] = '\0';
6176 check_0 = readchar (remote_timeout);
6177 if (check_0 >= 0)
6178 check_1 = readchar (remote_timeout);
6180 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
6182 if (remote_debug)
6183 fputs_filtered ("Timeout in checksum, retrying\n",
6184 gdb_stdlog);
6185 return -1;
6187 else if (check_0 < 0 || check_1 < 0)
6189 if (remote_debug)
6190 fputs_filtered ("Communication error in checksum\n",
6191 gdb_stdlog);
6192 return -1;
6195 /* Don't recompute the checksum; with no ack packets we
6196 don't have any way to indicate a packet retransmission
6197 is necessary. */
6198 if (rs->noack_mode)
6199 return bc;
6201 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
6202 if (csum == pktcsum)
6203 return bc;
6205 if (remote_debug)
6207 struct cleanup *old_chain;
6208 char *str;
6210 str = escape_buffer (buf, bc);
6211 old_chain = make_cleanup (xfree, str);
6212 fprintf_unfiltered (gdb_stdlog,
6214 Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s\n",
6215 pktcsum, csum, str);
6216 do_cleanups (old_chain);
6218 /* Number of characters in buffer ignoring trailing
6219 NULL. */
6220 return -1;
6222 case '*': /* Run length encoding. */
6224 int repeat;
6225 csum += c;
6227 c = readchar (remote_timeout);
6228 csum += c;
6229 repeat = c - ' ' + 3; /* Compute repeat count. */
6231 /* The character before ``*'' is repeated. */
6233 if (repeat > 0 && repeat <= 255 && bc > 0)
6235 if (bc + repeat - 1 >= *sizeof_buf - 1)
6237 /* Make some more room in the buffer. */
6238 *sizeof_buf += repeat;
6239 *buf_p = xrealloc (*buf_p, *sizeof_buf);
6240 buf = *buf_p;
6243 memset (&buf[bc], buf[bc - 1], repeat);
6244 bc += repeat;
6245 continue;
6248 buf[bc] = '\0';
6249 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
6250 return -1;
6252 default:
6253 if (bc >= *sizeof_buf - 1)
6255 /* Make some more room in the buffer. */
6256 *sizeof_buf *= 2;
6257 *buf_p = xrealloc (*buf_p, *sizeof_buf);
6258 buf = *buf_p;
6261 buf[bc++] = c;
6262 csum += c;
6263 continue;
6268 /* Read a packet from the remote machine, with error checking, and
6269 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
6270 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
6271 rather than timing out; this is used (in synchronous mode) to wait
6272 for a target that is is executing user code to stop. */
6273 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
6274 don't have to change all the calls to getpkt to deal with the
6275 return value, because at the moment I don't know what the right
6276 thing to do it for those. */
6277 void
6278 getpkt (char **buf,
6279 long *sizeof_buf,
6280 int forever)
6282 int timed_out;
6284 timed_out = getpkt_sane (buf, sizeof_buf, forever);
6288 /* Read a packet from the remote machine, with error checking, and
6289 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
6290 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
6291 rather than timing out; this is used (in synchronous mode) to wait
6292 for a target that is is executing user code to stop. If FOREVER ==
6293 0, this function is allowed to time out gracefully and return an
6294 indication of this to the caller. Otherwise return the number of
6295 bytes read. If EXPECTING_NOTIF, consider receiving a notification
6296 enough reason to return to the caller. */
6298 static int
6299 getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
6300 int expecting_notif)
6302 struct remote_state *rs = get_remote_state ();
6303 int c;
6304 int tries;
6305 int timeout;
6306 int val;
6308 /* We're reading a new response. Make sure we don't look at a
6309 previously cached response. */
6310 rs->cached_wait_status = 0;
6312 strcpy (*buf, "timeout");
6314 if (forever)
6315 timeout = watchdog > 0 ? watchdog : -1;
6316 else if (expecting_notif)
6317 timeout = 0; /* There should already be a char in the buffer. If
6318 not, bail out. */
6319 else
6320 timeout = remote_timeout;
6322 #define MAX_TRIES 3
6324 /* Process any number of notifications, and then return when
6325 we get a packet. */
6326 for (;;)
6328 /* If we get a timeout or bad checksm, retry up to MAX_TRIES
6329 times. */
6330 for (tries = 1; tries <= MAX_TRIES; tries++)
6332 /* This can loop forever if the remote side sends us
6333 characters continuously, but if it pauses, we'll get
6334 SERIAL_TIMEOUT from readchar because of timeout. Then
6335 we'll count that as a retry.
6337 Note that even when forever is set, we will only wait
6338 forever prior to the start of a packet. After that, we
6339 expect characters to arrive at a brisk pace. They should
6340 show up within remote_timeout intervals. */
6342 c = readchar (timeout);
6343 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
6345 if (c == SERIAL_TIMEOUT)
6347 if (expecting_notif)
6348 return -1; /* Don't complain, it's normal to not get
6349 anything in this case. */
6351 if (forever) /* Watchdog went off? Kill the target. */
6353 QUIT;
6354 pop_target ();
6355 error (_("Watchdog timeout has expired. Target detached."));
6357 if (remote_debug)
6358 fputs_filtered ("Timed out.\n", gdb_stdlog);
6360 else
6362 /* We've found the start of a packet or notification.
6363 Now collect the data. */
6364 val = read_frame (buf, sizeof_buf);
6365 if (val >= 0)
6366 break;
6369 serial_write (remote_desc, "-", 1);
6372 if (tries > MAX_TRIES)
6374 /* We have tried hard enough, and just can't receive the
6375 packet/notification. Give up. */
6376 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
6378 /* Skip the ack char if we're in no-ack mode. */
6379 if (!rs->noack_mode)
6380 serial_write (remote_desc, "+", 1);
6381 return -1;
6384 /* If we got an ordinary packet, return that to our caller. */
6385 if (c == '$')
6387 if (remote_debug)
6389 struct cleanup *old_chain;
6390 char *str;
6392 str = escape_buffer (*buf, val);
6393 old_chain = make_cleanup (xfree, str);
6394 fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
6395 do_cleanups (old_chain);
6398 /* Skip the ack char if we're in no-ack mode. */
6399 if (!rs->noack_mode)
6400 serial_write (remote_desc, "+", 1);
6401 return val;
6404 /* If we got a notification, handle it, and go back to looking
6405 for a packet. */
6406 else
6408 gdb_assert (c == '%');
6410 if (remote_debug)
6412 struct cleanup *old_chain;
6413 char *str;
6415 str = escape_buffer (*buf, val);
6416 old_chain = make_cleanup (xfree, str);
6417 fprintf_unfiltered (gdb_stdlog,
6418 " Notification received: %s\n",
6419 str);
6420 do_cleanups (old_chain);
6423 handle_notification (*buf, val);
6425 /* Notifications require no acknowledgement. */
6427 if (expecting_notif)
6428 return -1;
6433 static int
6434 getpkt_sane (char **buf, long *sizeof_buf, int forever)
6436 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0);
6439 static int
6440 getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever)
6442 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1);
6446 static void
6447 remote_kill (void)
6449 /* Use catch_errors so the user can quit from gdb even when we
6450 aren't on speaking terms with the remote system. */
6451 catch_errors ((catch_errors_ftype *) putpkt, "k", "", RETURN_MASK_ERROR);
6453 /* Don't wait for it to die. I'm not really sure it matters whether
6454 we do or not. For the existing stubs, kill is a noop. */
6455 target_mourn_inferior ();
6458 static int
6459 remote_vkill (int pid, struct remote_state *rs)
6461 if (remote_protocol_packets[PACKET_vKill].support == PACKET_DISABLE)
6462 return -1;
6464 /* Tell the remote target to detach. */
6465 sprintf (rs->buf, "vKill;%x", pid);
6466 putpkt (rs->buf);
6467 getpkt (&rs->buf, &rs->buf_size, 0);
6469 if (packet_ok (rs->buf,
6470 &remote_protocol_packets[PACKET_vKill]) == PACKET_OK)
6471 return 0;
6472 else if (remote_protocol_packets[PACKET_vKill].support == PACKET_DISABLE)
6473 return -1;
6474 else
6475 return 1;
6478 static void
6479 extended_remote_kill (void)
6481 int res;
6482 int pid = ptid_get_pid (inferior_ptid);
6483 struct remote_state *rs = get_remote_state ();
6485 res = remote_vkill (pid, rs);
6486 if (res == -1 && !remote_multi_process_p (rs))
6488 /* Don't try 'k' on a multi-process aware stub -- it has no way
6489 to specify the pid. */
6491 putpkt ("k");
6492 #if 0
6493 getpkt (&rs->buf, &rs->buf_size, 0);
6494 if (rs->buf[0] != 'O' || rs->buf[0] != 'K')
6495 res = 1;
6496 #else
6497 /* Don't wait for it to die. I'm not really sure it matters whether
6498 we do or not. For the existing stubs, kill is a noop. */
6499 res = 0;
6500 #endif
6503 if (res != 0)
6504 error (_("Can't kill process"));
6506 target_mourn_inferior ();
6509 static void
6510 remote_mourn (struct target_ops *ops)
6512 remote_mourn_1 (ops);
6515 /* Worker function for remote_mourn. */
6516 static void
6517 remote_mourn_1 (struct target_ops *target)
6519 unpush_target (target);
6521 /* remote_close takes care of cleaning up. */
6524 static int
6525 select_new_thread_callback (struct thread_info *th, void* data)
6527 if (!is_exited (th->ptid))
6529 switch_to_thread (th->ptid);
6530 printf_filtered (_("[Switching to %s]\n"),
6531 target_pid_to_str (inferior_ptid));
6532 return 1;
6534 return 0;
6537 static void
6538 extended_remote_mourn_1 (struct target_ops *target)
6540 struct remote_state *rs = get_remote_state ();
6542 /* In case we got here due to an error, but we're going to stay
6543 connected. */
6544 rs->waiting_for_stop_reply = 0;
6546 /* We're no longer interested in these events. */
6547 discard_pending_stop_replies (ptid_get_pid (inferior_ptid));
6549 /* If the current general thread belonged to the process we just
6550 detached from or has exited, the remote side current general
6551 thread becomes undefined. Considering a case like this:
6553 - We just got here due to a detach.
6554 - The process that we're detaching from happens to immediately
6555 report a global breakpoint being hit in non-stop mode, in the
6556 same thread we had selected before.
6557 - GDB attaches to this process again.
6558 - This event happens to be the next event we handle.
6560 GDB would consider that the current general thread didn't need to
6561 be set on the stub side (with Hg), since for all it knew,
6562 GENERAL_THREAD hadn't changed.
6564 Notice that although in all-stop mode, the remote server always
6565 sets the current thread to the thread reporting the stop event,
6566 that doesn't happen in non-stop mode; in non-stop, the stub *must
6567 not* change the current thread when reporting a breakpoint hit,
6568 due to the decoupling of event reporting and event handling.
6570 To keep things simple, we always invalidate our notion of the
6571 current thread. */
6572 record_currthread (minus_one_ptid);
6574 /* Unlike "target remote", we do not want to unpush the target; then
6575 the next time the user says "run", we won't be connected. */
6577 /* Call common code to mark the inferior as not running. */
6578 generic_mourn_inferior ();
6580 if (have_inferiors ())
6582 extern void nullify_last_target_wait_ptid ();
6583 /* Multi-process case. The current process has exited, but
6584 there are other processes to debug. Switch to the first
6585 available. */
6586 iterate_over_threads (select_new_thread_callback, NULL);
6587 nullify_last_target_wait_ptid ();
6589 else
6591 if (!remote_multi_process_p (rs))
6593 /* Check whether the target is running now - some remote stubs
6594 automatically restart after kill. */
6595 putpkt ("?");
6596 getpkt (&rs->buf, &rs->buf_size, 0);
6598 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
6600 /* Assume that the target has been restarted. Set inferior_ptid
6601 so that bits of core GDB realizes there's something here, e.g.,
6602 so that the user can say "kill" again. */
6603 inferior_ptid = magic_null_ptid;
6605 else
6607 /* Mark this (still pushed) target as not executable until we
6608 restart it. */
6609 target_mark_exited (target);
6612 else
6613 /* Always remove execution if this was the last process. */
6614 target_mark_exited (target);
6618 static void
6619 extended_remote_mourn (struct target_ops *ops)
6621 extended_remote_mourn_1 (ops);
6624 static int
6625 extended_remote_run (char *args)
6627 struct remote_state *rs = get_remote_state ();
6628 char *p;
6629 int len;
6631 /* If the user has disabled vRun support, or we have detected that
6632 support is not available, do not try it. */
6633 if (remote_protocol_packets[PACKET_vRun].support == PACKET_DISABLE)
6634 return -1;
6636 strcpy (rs->buf, "vRun;");
6637 len = strlen (rs->buf);
6639 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
6640 error (_("Remote file name too long for run packet"));
6641 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len, 0);
6643 gdb_assert (args != NULL);
6644 if (*args)
6646 struct cleanup *back_to;
6647 int i;
6648 char **argv;
6650 argv = gdb_buildargv (args);
6651 back_to = make_cleanup ((void (*) (void *)) freeargv, argv);
6652 for (i = 0; argv[i] != NULL; i++)
6654 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
6655 error (_("Argument list too long for run packet"));
6656 rs->buf[len++] = ';';
6657 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len, 0);
6659 do_cleanups (back_to);
6662 rs->buf[len++] = '\0';
6664 putpkt (rs->buf);
6665 getpkt (&rs->buf, &rs->buf_size, 0);
6667 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]) == PACKET_OK)
6669 /* We have a wait response; we don't need it, though. All is well. */
6670 return 0;
6672 else if (remote_protocol_packets[PACKET_vRun].support == PACKET_DISABLE)
6673 /* It wasn't disabled before, but it is now. */
6674 return -1;
6675 else
6677 if (remote_exec_file[0] == '\0')
6678 error (_("Running the default executable on the remote target failed; "
6679 "try \"set remote exec-file\"?"));
6680 else
6681 error (_("Running \"%s\" on the remote target failed"),
6682 remote_exec_file);
6686 /* In the extended protocol we want to be able to do things like
6687 "run" and have them basically work as expected. So we need
6688 a special create_inferior function. We support changing the
6689 executable file and the command line arguments, but not the
6690 environment. */
6692 static void
6693 extended_remote_create_inferior_1 (char *exec_file, char *args,
6694 char **env, int from_tty)
6696 /* If running asynchronously, register the target file descriptor
6697 with the event loop. */
6698 if (target_can_async_p ())
6699 target_async (inferior_event_handler, 0);
6701 /* Now restart the remote server. */
6702 if (extended_remote_run (args) == -1)
6704 /* vRun was not supported. Fail if we need it to do what the
6705 user requested. */
6706 if (remote_exec_file[0])
6707 error (_("Remote target does not support \"set remote exec-file\""));
6708 if (args[0])
6709 error (_("Remote target does not support \"set args\" or run <ARGS>"));
6711 /* Fall back to "R". */
6712 extended_remote_restart ();
6715 /* Clean up from the last time we ran, before we mark the target
6716 running again. This will mark breakpoints uninserted, and
6717 get_offsets may insert breakpoints. */
6718 init_thread_list ();
6719 init_wait_for_inferior ();
6721 /* Now mark the inferior as running before we do anything else. */
6722 inferior_ptid = magic_null_ptid;
6724 /* Now, if we have thread information, update inferior_ptid. */
6725 inferior_ptid = remote_current_thread (inferior_ptid);
6727 add_inferior (ptid_get_pid (inferior_ptid));
6728 add_thread_silent (inferior_ptid);
6730 target_mark_running (&extended_remote_ops);
6732 /* Get updated offsets, if the stub uses qOffsets. */
6733 get_offsets ();
6736 static void
6737 extended_remote_create_inferior (struct target_ops *ops,
6738 char *exec_file, char *args,
6739 char **env, int from_tty)
6741 extended_remote_create_inferior_1 (exec_file, args, env, from_tty);
6745 /* Insert a breakpoint. On targets that have software breakpoint
6746 support, we ask the remote target to do the work; on targets
6747 which don't, we insert a traditional memory breakpoint. */
6749 static int
6750 remote_insert_breakpoint (struct bp_target_info *bp_tgt)
6752 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
6753 If it succeeds, then set the support to PACKET_ENABLE. If it
6754 fails, and the user has explicitly requested the Z support then
6755 report an error, otherwise, mark it disabled and go on. */
6757 if (remote_protocol_packets[PACKET_Z0].support != PACKET_DISABLE)
6759 CORE_ADDR addr = bp_tgt->placed_address;
6760 struct remote_state *rs;
6761 char *p;
6762 int bpsize;
6764 gdbarch_breakpoint_from_pc (target_gdbarch, &addr, &bpsize);
6766 rs = get_remote_state ();
6767 p = rs->buf;
6769 *(p++) = 'Z';
6770 *(p++) = '0';
6771 *(p++) = ',';
6772 addr = (ULONGEST) remote_address_masked (addr);
6773 p += hexnumstr (p, addr);
6774 sprintf (p, ",%d", bpsize);
6776 putpkt (rs->buf);
6777 getpkt (&rs->buf, &rs->buf_size, 0);
6779 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
6781 case PACKET_ERROR:
6782 return -1;
6783 case PACKET_OK:
6784 bp_tgt->placed_address = addr;
6785 bp_tgt->placed_size = bpsize;
6786 return 0;
6787 case PACKET_UNKNOWN:
6788 break;
6792 return memory_insert_breakpoint (bp_tgt);
6795 static int
6796 remote_remove_breakpoint (struct bp_target_info *bp_tgt)
6798 CORE_ADDR addr = bp_tgt->placed_address;
6799 struct remote_state *rs = get_remote_state ();
6800 int bp_size;
6802 if (remote_protocol_packets[PACKET_Z0].support != PACKET_DISABLE)
6804 char *p = rs->buf;
6806 *(p++) = 'z';
6807 *(p++) = '0';
6808 *(p++) = ',';
6810 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
6811 p += hexnumstr (p, addr);
6812 sprintf (p, ",%d", bp_tgt->placed_size);
6814 putpkt (rs->buf);
6815 getpkt (&rs->buf, &rs->buf_size, 0);
6817 return (rs->buf[0] == 'E');
6820 return memory_remove_breakpoint (bp_tgt);
6823 static int
6824 watchpoint_to_Z_packet (int type)
6826 switch (type)
6828 case hw_write:
6829 return Z_PACKET_WRITE_WP;
6830 break;
6831 case hw_read:
6832 return Z_PACKET_READ_WP;
6833 break;
6834 case hw_access:
6835 return Z_PACKET_ACCESS_WP;
6836 break;
6837 default:
6838 internal_error (__FILE__, __LINE__,
6839 _("hw_bp_to_z: bad watchpoint type %d"), type);
6843 static int
6844 remote_insert_watchpoint (CORE_ADDR addr, int len, int type)
6846 struct remote_state *rs = get_remote_state ();
6847 char *p;
6848 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
6850 if (remote_protocol_packets[PACKET_Z0 + packet].support == PACKET_DISABLE)
6851 return -1;
6853 sprintf (rs->buf, "Z%x,", packet);
6854 p = strchr (rs->buf, '\0');
6855 addr = remote_address_masked (addr);
6856 p += hexnumstr (p, (ULONGEST) addr);
6857 sprintf (p, ",%x", len);
6859 putpkt (rs->buf);
6860 getpkt (&rs->buf, &rs->buf_size, 0);
6862 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
6864 case PACKET_ERROR:
6865 case PACKET_UNKNOWN:
6866 return -1;
6867 case PACKET_OK:
6868 return 0;
6870 internal_error (__FILE__, __LINE__,
6871 _("remote_insert_watchpoint: reached end of function"));
6875 static int
6876 remote_remove_watchpoint (CORE_ADDR addr, int len, int type)
6878 struct remote_state *rs = get_remote_state ();
6879 char *p;
6880 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
6882 if (remote_protocol_packets[PACKET_Z0 + packet].support == PACKET_DISABLE)
6883 return -1;
6885 sprintf (rs->buf, "z%x,", packet);
6886 p = strchr (rs->buf, '\0');
6887 addr = remote_address_masked (addr);
6888 p += hexnumstr (p, (ULONGEST) addr);
6889 sprintf (p, ",%x", len);
6890 putpkt (rs->buf);
6891 getpkt (&rs->buf, &rs->buf_size, 0);
6893 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
6895 case PACKET_ERROR:
6896 case PACKET_UNKNOWN:
6897 return -1;
6898 case PACKET_OK:
6899 return 0;
6901 internal_error (__FILE__, __LINE__,
6902 _("remote_remove_watchpoint: reached end of function"));
6906 int remote_hw_watchpoint_limit = -1;
6907 int remote_hw_breakpoint_limit = -1;
6909 static int
6910 remote_check_watch_resources (int type, int cnt, int ot)
6912 if (type == bp_hardware_breakpoint)
6914 if (remote_hw_breakpoint_limit == 0)
6915 return 0;
6916 else if (remote_hw_breakpoint_limit < 0)
6917 return 1;
6918 else if (cnt <= remote_hw_breakpoint_limit)
6919 return 1;
6921 else
6923 if (remote_hw_watchpoint_limit == 0)
6924 return 0;
6925 else if (remote_hw_watchpoint_limit < 0)
6926 return 1;
6927 else if (ot)
6928 return -1;
6929 else if (cnt <= remote_hw_watchpoint_limit)
6930 return 1;
6932 return -1;
6935 static int
6936 remote_stopped_by_watchpoint (void)
6938 return remote_stopped_by_watchpoint_p;
6941 static int
6942 remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
6944 int rc = 0;
6945 if (remote_stopped_by_watchpoint ())
6947 *addr_p = remote_watch_data_address;
6948 rc = 1;
6951 return rc;
6955 static int
6956 remote_insert_hw_breakpoint (struct bp_target_info *bp_tgt)
6958 CORE_ADDR addr;
6959 struct remote_state *rs;
6960 char *p;
6962 /* The length field should be set to the size of a breakpoint
6963 instruction, even though we aren't inserting one ourselves. */
6965 gdbarch_breakpoint_from_pc
6966 (target_gdbarch, &bp_tgt->placed_address, &bp_tgt->placed_size);
6968 if (remote_protocol_packets[PACKET_Z1].support == PACKET_DISABLE)
6969 return -1;
6971 rs = get_remote_state ();
6972 p = rs->buf;
6974 *(p++) = 'Z';
6975 *(p++) = '1';
6976 *(p++) = ',';
6978 addr = remote_address_masked (bp_tgt->placed_address);
6979 p += hexnumstr (p, (ULONGEST) addr);
6980 sprintf (p, ",%x", bp_tgt->placed_size);
6982 putpkt (rs->buf);
6983 getpkt (&rs->buf, &rs->buf_size, 0);
6985 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
6987 case PACKET_ERROR:
6988 case PACKET_UNKNOWN:
6989 return -1;
6990 case PACKET_OK:
6991 return 0;
6993 internal_error (__FILE__, __LINE__,
6994 _("remote_insert_hw_breakpoint: reached end of function"));
6998 static int
6999 remote_remove_hw_breakpoint (struct bp_target_info *bp_tgt)
7001 CORE_ADDR addr;
7002 struct remote_state *rs = get_remote_state ();
7003 char *p = rs->buf;
7005 if (remote_protocol_packets[PACKET_Z1].support == PACKET_DISABLE)
7006 return -1;
7008 *(p++) = 'z';
7009 *(p++) = '1';
7010 *(p++) = ',';
7012 addr = remote_address_masked (bp_tgt->placed_address);
7013 p += hexnumstr (p, (ULONGEST) addr);
7014 sprintf (p, ",%x", bp_tgt->placed_size);
7016 putpkt (rs->buf);
7017 getpkt (&rs->buf, &rs->buf_size, 0);
7019 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
7021 case PACKET_ERROR:
7022 case PACKET_UNKNOWN:
7023 return -1;
7024 case PACKET_OK:
7025 return 0;
7027 internal_error (__FILE__, __LINE__,
7028 _("remote_remove_hw_breakpoint: reached end of function"));
7031 /* Table used by the crc32 function to calcuate the checksum. */
7033 static unsigned long crc32_table[256] =
7034 {0, 0};
7036 static unsigned long
7037 crc32 (unsigned char *buf, int len, unsigned int crc)
7039 if (!crc32_table[1])
7041 /* Initialize the CRC table and the decoding table. */
7042 int i, j;
7043 unsigned int c;
7045 for (i = 0; i < 256; i++)
7047 for (c = i << 24, j = 8; j > 0; --j)
7048 c = c & 0x80000000 ? (c << 1) ^ 0x04c11db7 : (c << 1);
7049 crc32_table[i] = c;
7053 while (len--)
7055 crc = (crc << 8) ^ crc32_table[((crc >> 24) ^ *buf) & 255];
7056 buf++;
7058 return crc;
7061 /* compare-sections command
7063 With no arguments, compares each loadable section in the exec bfd
7064 with the same memory range on the target, and reports mismatches.
7065 Useful for verifying the image on the target against the exec file.
7066 Depends on the target understanding the new "qCRC:" request. */
7068 /* FIXME: cagney/1999-10-26: This command should be broken down into a
7069 target method (target verify memory) and generic version of the
7070 actual command. This will allow other high-level code (especially
7071 generic_load()) to make use of this target functionality. */
7073 static void
7074 compare_sections_command (char *args, int from_tty)
7076 struct remote_state *rs = get_remote_state ();
7077 asection *s;
7078 unsigned long host_crc, target_crc;
7079 extern bfd *exec_bfd;
7080 struct cleanup *old_chain;
7081 char *tmp;
7082 char *sectdata;
7083 const char *sectname;
7084 bfd_size_type size;
7085 bfd_vma lma;
7086 int matched = 0;
7087 int mismatched = 0;
7089 if (!exec_bfd)
7090 error (_("command cannot be used without an exec file"));
7091 if (!current_target.to_shortname ||
7092 strcmp (current_target.to_shortname, "remote") != 0)
7093 error (_("command can only be used with remote target"));
7095 for (s = exec_bfd->sections; s; s = s->next)
7097 if (!(s->flags & SEC_LOAD))
7098 continue; /* skip non-loadable section */
7100 size = bfd_get_section_size (s);
7101 if (size == 0)
7102 continue; /* skip zero-length section */
7104 sectname = bfd_get_section_name (exec_bfd, s);
7105 if (args && strcmp (args, sectname) != 0)
7106 continue; /* not the section selected by user */
7108 matched = 1; /* do this section */
7109 lma = s->lma;
7110 /* FIXME: assumes lma can fit into long. */
7111 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
7112 (long) lma, (long) size);
7113 putpkt (rs->buf);
7115 /* Be clever; compute the host_crc before waiting for target
7116 reply. */
7117 sectdata = xmalloc (size);
7118 old_chain = make_cleanup (xfree, sectdata);
7119 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
7120 host_crc = crc32 ((unsigned char *) sectdata, size, 0xffffffff);
7122 getpkt (&rs->buf, &rs->buf_size, 0);
7123 if (rs->buf[0] == 'E')
7124 error (_("target memory fault, section %s, range 0x%s -- 0x%s"),
7125 sectname, paddr (lma), paddr (lma + size));
7126 if (rs->buf[0] != 'C')
7127 error (_("remote target does not support this operation"));
7129 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
7130 target_crc = target_crc * 16 + fromhex (*tmp);
7132 printf_filtered ("Section %s, range 0x%s -- 0x%s: ",
7133 sectname, paddr (lma), paddr (lma + size));
7134 if (host_crc == target_crc)
7135 printf_filtered ("matched.\n");
7136 else
7138 printf_filtered ("MIS-MATCHED!\n");
7139 mismatched++;
7142 do_cleanups (old_chain);
7144 if (mismatched > 0)
7145 warning (_("One or more sections of the remote executable does not match\n\
7146 the loaded file\n"));
7147 if (args && !matched)
7148 printf_filtered (_("No loaded section named '%s'.\n"), args);
7151 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
7152 into remote target. The number of bytes written to the remote
7153 target is returned, or -1 for error. */
7155 static LONGEST
7156 remote_write_qxfer (struct target_ops *ops, const char *object_name,
7157 const char *annex, const gdb_byte *writebuf,
7158 ULONGEST offset, LONGEST len,
7159 struct packet_config *packet)
7161 int i, buf_len;
7162 ULONGEST n;
7163 gdb_byte *wbuf;
7164 struct remote_state *rs = get_remote_state ();
7165 int max_size = get_memory_write_packet_size ();
7167 if (packet->support == PACKET_DISABLE)
7168 return -1;
7170 /* Insert header. */
7171 i = snprintf (rs->buf, max_size,
7172 "qXfer:%s:write:%s:%s:",
7173 object_name, annex ? annex : "",
7174 phex_nz (offset, sizeof offset));
7175 max_size -= (i + 1);
7177 /* Escape as much data as fits into rs->buf. */
7178 buf_len = remote_escape_output
7179 (writebuf, len, (rs->buf + i), &max_size, max_size);
7181 if (putpkt_binary (rs->buf, i + buf_len) < 0
7182 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
7183 || packet_ok (rs->buf, packet) != PACKET_OK)
7184 return -1;
7186 unpack_varlen_hex (rs->buf, &n);
7187 return n;
7190 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
7191 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
7192 number of bytes read is returned, or 0 for EOF, or -1 for error.
7193 The number of bytes read may be less than LEN without indicating an
7194 EOF. PACKET is checked and updated to indicate whether the remote
7195 target supports this object. */
7197 static LONGEST
7198 remote_read_qxfer (struct target_ops *ops, const char *object_name,
7199 const char *annex,
7200 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
7201 struct packet_config *packet)
7203 static char *finished_object;
7204 static char *finished_annex;
7205 static ULONGEST finished_offset;
7207 struct remote_state *rs = get_remote_state ();
7208 unsigned int total = 0;
7209 LONGEST i, n, packet_len;
7211 if (packet->support == PACKET_DISABLE)
7212 return -1;
7214 /* Check whether we've cached an end-of-object packet that matches
7215 this request. */
7216 if (finished_object)
7218 if (strcmp (object_name, finished_object) == 0
7219 && strcmp (annex ? annex : "", finished_annex) == 0
7220 && offset == finished_offset)
7221 return 0;
7223 /* Otherwise, we're now reading something different. Discard
7224 the cache. */
7225 xfree (finished_object);
7226 xfree (finished_annex);
7227 finished_object = NULL;
7228 finished_annex = NULL;
7231 /* Request only enough to fit in a single packet. The actual data
7232 may not, since we don't know how much of it will need to be escaped;
7233 the target is free to respond with slightly less data. We subtract
7234 five to account for the response type and the protocol frame. */
7235 n = min (get_remote_packet_size () - 5, len);
7236 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
7237 object_name, annex ? annex : "",
7238 phex_nz (offset, sizeof offset),
7239 phex_nz (n, sizeof n));
7240 i = putpkt (rs->buf);
7241 if (i < 0)
7242 return -1;
7244 rs->buf[0] = '\0';
7245 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
7246 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
7247 return -1;
7249 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
7250 error (_("Unknown remote qXfer reply: %s"), rs->buf);
7252 /* 'm' means there is (or at least might be) more data after this
7253 batch. That does not make sense unless there's at least one byte
7254 of data in this reply. */
7255 if (rs->buf[0] == 'm' && packet_len == 1)
7256 error (_("Remote qXfer reply contained no data."));
7258 /* Got some data. */
7259 i = remote_unescape_input (rs->buf + 1, packet_len - 1, readbuf, n);
7261 /* 'l' is an EOF marker, possibly including a final block of data,
7262 or possibly empty. If we have the final block of a non-empty
7263 object, record this fact to bypass a subsequent partial read. */
7264 if (rs->buf[0] == 'l' && offset + i > 0)
7266 finished_object = xstrdup (object_name);
7267 finished_annex = xstrdup (annex ? annex : "");
7268 finished_offset = offset + i;
7271 return i;
7274 static LONGEST
7275 remote_xfer_partial (struct target_ops *ops, enum target_object object,
7276 const char *annex, gdb_byte *readbuf,
7277 const gdb_byte *writebuf, ULONGEST offset, LONGEST len)
7279 struct remote_state *rs;
7280 int i;
7281 char *p2;
7282 char query_type;
7284 set_general_thread (inferior_ptid);
7286 rs = get_remote_state ();
7288 /* Handle memory using the standard memory routines. */
7289 if (object == TARGET_OBJECT_MEMORY)
7291 int xfered;
7292 errno = 0;
7294 /* If the remote target is connected but not running, we should
7295 pass this request down to a lower stratum (e.g. the executable
7296 file). */
7297 if (!target_has_execution)
7298 return 0;
7300 if (writebuf != NULL)
7301 xfered = remote_write_bytes (offset, writebuf, len);
7302 else
7303 xfered = remote_read_bytes (offset, readbuf, len);
7305 if (xfered > 0)
7306 return xfered;
7307 else if (xfered == 0 && errno == 0)
7308 return 0;
7309 else
7310 return -1;
7313 /* Handle SPU memory using qxfer packets. */
7314 if (object == TARGET_OBJECT_SPU)
7316 if (readbuf)
7317 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
7318 &remote_protocol_packets
7319 [PACKET_qXfer_spu_read]);
7320 else
7321 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
7322 &remote_protocol_packets
7323 [PACKET_qXfer_spu_write]);
7326 /* Only handle flash writes. */
7327 if (writebuf != NULL)
7329 LONGEST xfered;
7331 switch (object)
7333 case TARGET_OBJECT_FLASH:
7334 xfered = remote_flash_write (ops, offset, len, writebuf);
7336 if (xfered > 0)
7337 return xfered;
7338 else if (xfered == 0 && errno == 0)
7339 return 0;
7340 else
7341 return -1;
7343 default:
7344 return -1;
7348 /* Map pre-existing objects onto letters. DO NOT do this for new
7349 objects!!! Instead specify new query packets. */
7350 switch (object)
7352 case TARGET_OBJECT_AVR:
7353 query_type = 'R';
7354 break;
7356 case TARGET_OBJECT_AUXV:
7357 gdb_assert (annex == NULL);
7358 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
7359 &remote_protocol_packets[PACKET_qXfer_auxv]);
7361 case TARGET_OBJECT_AVAILABLE_FEATURES:
7362 return remote_read_qxfer
7363 (ops, "features", annex, readbuf, offset, len,
7364 &remote_protocol_packets[PACKET_qXfer_features]);
7366 case TARGET_OBJECT_LIBRARIES:
7367 return remote_read_qxfer
7368 (ops, "libraries", annex, readbuf, offset, len,
7369 &remote_protocol_packets[PACKET_qXfer_libraries]);
7371 case TARGET_OBJECT_MEMORY_MAP:
7372 gdb_assert (annex == NULL);
7373 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
7374 &remote_protocol_packets[PACKET_qXfer_memory_map]);
7376 case TARGET_OBJECT_OSDATA:
7377 /* Should only get here if we're connected. */
7378 gdb_assert (remote_desc);
7379 return remote_read_qxfer
7380 (ops, "osdata", annex, readbuf, offset, len,
7381 &remote_protocol_packets[PACKET_qXfer_osdata]);
7383 default:
7384 return -1;
7387 /* Note: a zero OFFSET and LEN can be used to query the minimum
7388 buffer size. */
7389 if (offset == 0 && len == 0)
7390 return (get_remote_packet_size ());
7391 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
7392 large enough let the caller deal with it. */
7393 if (len < get_remote_packet_size ())
7394 return -1;
7395 len = get_remote_packet_size ();
7397 /* Except for querying the minimum buffer size, target must be open. */
7398 if (!remote_desc)
7399 error (_("remote query is only available after target open"));
7401 gdb_assert (annex != NULL);
7402 gdb_assert (readbuf != NULL);
7404 p2 = rs->buf;
7405 *p2++ = 'q';
7406 *p2++ = query_type;
7408 /* We used one buffer char for the remote protocol q command and
7409 another for the query type. As the remote protocol encapsulation
7410 uses 4 chars plus one extra in case we are debugging
7411 (remote_debug), we have PBUFZIZ - 7 left to pack the query
7412 string. */
7413 i = 0;
7414 while (annex[i] && (i < (get_remote_packet_size () - 8)))
7416 /* Bad caller may have sent forbidden characters. */
7417 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
7418 *p2++ = annex[i];
7419 i++;
7421 *p2 = '\0';
7422 gdb_assert (annex[i] == '\0');
7424 i = putpkt (rs->buf);
7425 if (i < 0)
7426 return i;
7428 getpkt (&rs->buf, &rs->buf_size, 0);
7429 strcpy ((char *) readbuf, rs->buf);
7431 return strlen ((char *) readbuf);
7434 static int
7435 remote_search_memory (struct target_ops* ops,
7436 CORE_ADDR start_addr, ULONGEST search_space_len,
7437 const gdb_byte *pattern, ULONGEST pattern_len,
7438 CORE_ADDR *found_addrp)
7440 struct remote_state *rs = get_remote_state ();
7441 int max_size = get_memory_write_packet_size ();
7442 struct packet_config *packet =
7443 &remote_protocol_packets[PACKET_qSearch_memory];
7444 /* number of packet bytes used to encode the pattern,
7445 this could be more than PATTERN_LEN due to escape characters */
7446 int escaped_pattern_len;
7447 /* amount of pattern that was encodable in the packet */
7448 int used_pattern_len;
7449 int i;
7450 int found;
7451 ULONGEST found_addr;
7453 /* Don't go to the target if we don't have to.
7454 This is done before checking packet->support to avoid the possibility that
7455 a success for this edge case means the facility works in general. */
7456 if (pattern_len > search_space_len)
7457 return 0;
7458 if (pattern_len == 0)
7460 *found_addrp = start_addr;
7461 return 1;
7464 /* If we already know the packet isn't supported, fall back to the simple
7465 way of searching memory. */
7467 if (packet->support == PACKET_DISABLE)
7469 /* Target doesn't provided special support, fall back and use the
7470 standard support (copy memory and do the search here). */
7471 return simple_search_memory (ops, start_addr, search_space_len,
7472 pattern, pattern_len, found_addrp);
7475 /* Insert header. */
7476 i = snprintf (rs->buf, max_size,
7477 "qSearch:memory:%s;%s;",
7478 paddr_nz (start_addr),
7479 phex_nz (search_space_len, sizeof (search_space_len)));
7480 max_size -= (i + 1);
7482 /* Escape as much data as fits into rs->buf. */
7483 escaped_pattern_len =
7484 remote_escape_output (pattern, pattern_len, (rs->buf + i),
7485 &used_pattern_len, max_size);
7487 /* Bail if the pattern is too large. */
7488 if (used_pattern_len != pattern_len)
7489 error ("Pattern is too large to transmit to remote target.");
7491 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
7492 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
7493 || packet_ok (rs->buf, packet) != PACKET_OK)
7495 /* The request may not have worked because the command is not
7496 supported. If so, fall back to the simple way. */
7497 if (packet->support == PACKET_DISABLE)
7499 return simple_search_memory (ops, start_addr, search_space_len,
7500 pattern, pattern_len, found_addrp);
7502 return -1;
7505 if (rs->buf[0] == '0')
7506 found = 0;
7507 else if (rs->buf[0] == '1')
7509 found = 1;
7510 if (rs->buf[1] != ',')
7511 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
7512 unpack_varlen_hex (rs->buf + 2, &found_addr);
7513 *found_addrp = found_addr;
7515 else
7516 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
7518 return found;
7521 static void
7522 remote_rcmd (char *command,
7523 struct ui_file *outbuf)
7525 struct remote_state *rs = get_remote_state ();
7526 char *p = rs->buf;
7528 if (!remote_desc)
7529 error (_("remote rcmd is only available after target open"));
7531 /* Send a NULL command across as an empty command. */
7532 if (command == NULL)
7533 command = "";
7535 /* The query prefix. */
7536 strcpy (rs->buf, "qRcmd,");
7537 p = strchr (rs->buf, '\0');
7539 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/) > get_remote_packet_size ())
7540 error (_("\"monitor\" command ``%s'' is too long."), command);
7542 /* Encode the actual command. */
7543 bin2hex ((gdb_byte *) command, p, 0);
7545 if (putpkt (rs->buf) < 0)
7546 error (_("Communication problem with target."));
7548 /* get/display the response */
7549 while (1)
7551 char *buf;
7553 /* XXX - see also tracepoint.c:remote_get_noisy_reply(). */
7554 rs->buf[0] = '\0';
7555 getpkt (&rs->buf, &rs->buf_size, 0);
7556 buf = rs->buf;
7557 if (buf[0] == '\0')
7558 error (_("Target does not support this command."));
7559 if (buf[0] == 'O' && buf[1] != 'K')
7561 remote_console_output (buf + 1); /* 'O' message from stub. */
7562 continue;
7564 if (strcmp (buf, "OK") == 0)
7565 break;
7566 if (strlen (buf) == 3 && buf[0] == 'E'
7567 && isdigit (buf[1]) && isdigit (buf[2]))
7569 error (_("Protocol error with Rcmd"));
7571 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
7573 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
7574 fputc_unfiltered (c, outbuf);
7576 break;
7580 static VEC(mem_region_s) *
7581 remote_memory_map (struct target_ops *ops)
7583 VEC(mem_region_s) *result = NULL;
7584 char *text = target_read_stralloc (&current_target,
7585 TARGET_OBJECT_MEMORY_MAP, NULL);
7587 if (text)
7589 struct cleanup *back_to = make_cleanup (xfree, text);
7590 result = parse_memory_map (text);
7591 do_cleanups (back_to);
7594 return result;
7597 static void
7598 packet_command (char *args, int from_tty)
7600 struct remote_state *rs = get_remote_state ();
7602 if (!remote_desc)
7603 error (_("command can only be used with remote target"));
7605 if (!args)
7606 error (_("remote-packet command requires packet text as argument"));
7608 puts_filtered ("sending: ");
7609 print_packet (args);
7610 puts_filtered ("\n");
7611 putpkt (args);
7613 getpkt (&rs->buf, &rs->buf_size, 0);
7614 puts_filtered ("received: ");
7615 print_packet (rs->buf);
7616 puts_filtered ("\n");
7619 #if 0
7620 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
7622 static void display_thread_info (struct gdb_ext_thread_info *info);
7624 static void threadset_test_cmd (char *cmd, int tty);
7626 static void threadalive_test (char *cmd, int tty);
7628 static void threadlist_test_cmd (char *cmd, int tty);
7630 int get_and_display_threadinfo (threadref *ref);
7632 static void threadinfo_test_cmd (char *cmd, int tty);
7634 static int thread_display_step (threadref *ref, void *context);
7636 static void threadlist_update_test_cmd (char *cmd, int tty);
7638 static void init_remote_threadtests (void);
7640 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
7642 static void
7643 threadset_test_cmd (char *cmd, int tty)
7645 int sample_thread = SAMPLE_THREAD;
7647 printf_filtered (_("Remote threadset test\n"));
7648 set_general_thread (sample_thread);
7652 static void
7653 threadalive_test (char *cmd, int tty)
7655 int sample_thread = SAMPLE_THREAD;
7656 int pid = ptid_get_pid (inferior_ptid);
7657 ptid_t ptid = ptid_build (pid, 0, sample_thread);
7659 if (remote_thread_alive (ptid))
7660 printf_filtered ("PASS: Thread alive test\n");
7661 else
7662 printf_filtered ("FAIL: Thread alive test\n");
7665 void output_threadid (char *title, threadref *ref);
7667 void
7668 output_threadid (char *title, threadref *ref)
7670 char hexid[20];
7672 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
7673 hexid[16] = 0;
7674 printf_filtered ("%s %s\n", title, (&hexid[0]));
7677 static void
7678 threadlist_test_cmd (char *cmd, int tty)
7680 int startflag = 1;
7681 threadref nextthread;
7682 int done, result_count;
7683 threadref threadlist[3];
7685 printf_filtered ("Remote Threadlist test\n");
7686 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
7687 &result_count, &threadlist[0]))
7688 printf_filtered ("FAIL: threadlist test\n");
7689 else
7691 threadref *scan = threadlist;
7692 threadref *limit = scan + result_count;
7694 while (scan < limit)
7695 output_threadid (" thread ", scan++);
7699 void
7700 display_thread_info (struct gdb_ext_thread_info *info)
7702 output_threadid ("Threadid: ", &info->threadid);
7703 printf_filtered ("Name: %s\n ", info->shortname);
7704 printf_filtered ("State: %s\n", info->display);
7705 printf_filtered ("other: %s\n\n", info->more_display);
7709 get_and_display_threadinfo (threadref *ref)
7711 int result;
7712 int set;
7713 struct gdb_ext_thread_info threadinfo;
7715 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
7716 | TAG_MOREDISPLAY | TAG_DISPLAY;
7717 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
7718 display_thread_info (&threadinfo);
7719 return result;
7722 static void
7723 threadinfo_test_cmd (char *cmd, int tty)
7725 int athread = SAMPLE_THREAD;
7726 threadref thread;
7727 int set;
7729 int_to_threadref (&thread, athread);
7730 printf_filtered ("Remote Threadinfo test\n");
7731 if (!get_and_display_threadinfo (&thread))
7732 printf_filtered ("FAIL cannot get thread info\n");
7735 static int
7736 thread_display_step (threadref *ref, void *context)
7738 /* output_threadid(" threadstep ",ref); *//* simple test */
7739 return get_and_display_threadinfo (ref);
7742 static void
7743 threadlist_update_test_cmd (char *cmd, int tty)
7745 printf_filtered ("Remote Threadlist update test\n");
7746 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
7749 static void
7750 init_remote_threadtests (void)
7752 add_com ("tlist", class_obscure, threadlist_test_cmd, _("\
7753 Fetch and print the remote list of thread identifiers, one pkt only"));
7754 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
7755 _("Fetch and display info about one thread"));
7756 add_com ("tset", class_obscure, threadset_test_cmd,
7757 _("Test setting to a different thread"));
7758 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
7759 _("Iterate through updating all remote thread info"));
7760 add_com ("talive", class_obscure, threadalive_test,
7761 _(" Remote thread alive test "));
7764 #endif /* 0 */
7766 /* Convert a thread ID to a string. Returns the string in a static
7767 buffer. */
7769 static char *
7770 remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
7772 static char buf[64];
7773 struct remote_state *rs = get_remote_state ();
7775 if (ptid_equal (magic_null_ptid, ptid))
7777 xsnprintf (buf, sizeof buf, "Thread <main>");
7778 return buf;
7780 else if (remote_multi_process_p (rs)
7781 && ptid_get_tid (ptid) != 0 && ptid_get_pid (ptid) != 0)
7783 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
7784 ptid_get_pid (ptid), ptid_get_tid (ptid));
7785 return buf;
7787 else if (ptid_get_tid (ptid) != 0)
7789 xsnprintf (buf, sizeof buf, "Thread %ld",
7790 ptid_get_tid (ptid));
7791 return buf;
7794 return normal_pid_to_str (ptid);
7797 /* Get the address of the thread local variable in OBJFILE which is
7798 stored at OFFSET within the thread local storage for thread PTID. */
7800 static CORE_ADDR
7801 remote_get_thread_local_address (struct target_ops *ops,
7802 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
7804 if (remote_protocol_packets[PACKET_qGetTLSAddr].support != PACKET_DISABLE)
7806 struct remote_state *rs = get_remote_state ();
7807 char *p = rs->buf;
7808 char *endp = rs->buf + get_remote_packet_size ();
7809 enum packet_result result;
7811 strcpy (p, "qGetTLSAddr:");
7812 p += strlen (p);
7813 p = write_ptid (p, endp, ptid);
7814 *p++ = ',';
7815 p += hexnumstr (p, offset);
7816 *p++ = ',';
7817 p += hexnumstr (p, lm);
7818 *p++ = '\0';
7820 putpkt (rs->buf);
7821 getpkt (&rs->buf, &rs->buf_size, 0);
7822 result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_qGetTLSAddr]);
7823 if (result == PACKET_OK)
7825 ULONGEST result;
7827 unpack_varlen_hex (rs->buf, &result);
7828 return result;
7830 else if (result == PACKET_UNKNOWN)
7831 throw_error (TLS_GENERIC_ERROR,
7832 _("Remote target doesn't support qGetTLSAddr packet"));
7833 else
7834 throw_error (TLS_GENERIC_ERROR,
7835 _("Remote target failed to process qGetTLSAddr request"));
7837 else
7838 throw_error (TLS_GENERIC_ERROR,
7839 _("TLS not supported or disabled on this target"));
7840 /* Not reached. */
7841 return 0;
7844 /* Support for inferring a target description based on the current
7845 architecture and the size of a 'g' packet. While the 'g' packet
7846 can have any size (since optional registers can be left off the
7847 end), some sizes are easily recognizable given knowledge of the
7848 approximate architecture. */
7850 struct remote_g_packet_guess
7852 int bytes;
7853 const struct target_desc *tdesc;
7855 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
7856 DEF_VEC_O(remote_g_packet_guess_s);
7858 struct remote_g_packet_data
7860 VEC(remote_g_packet_guess_s) *guesses;
7863 static struct gdbarch_data *remote_g_packet_data_handle;
7865 static void *
7866 remote_g_packet_data_init (struct obstack *obstack)
7868 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
7871 void
7872 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
7873 const struct target_desc *tdesc)
7875 struct remote_g_packet_data *data
7876 = gdbarch_data (gdbarch, remote_g_packet_data_handle);
7877 struct remote_g_packet_guess new_guess, *guess;
7878 int ix;
7880 gdb_assert (tdesc != NULL);
7882 for (ix = 0;
7883 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
7884 ix++)
7885 if (guess->bytes == bytes)
7886 internal_error (__FILE__, __LINE__,
7887 "Duplicate g packet description added for size %d",
7888 bytes);
7890 new_guess.bytes = bytes;
7891 new_guess.tdesc = tdesc;
7892 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
7895 /* Return 1 if remote_read_description would do anything on this target
7896 and architecture, 0 otherwise. */
7898 static int
7899 remote_read_description_p (struct target_ops *target)
7901 struct remote_g_packet_data *data
7902 = gdbarch_data (target_gdbarch, remote_g_packet_data_handle);
7904 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
7905 return 1;
7907 return 0;
7910 static const struct target_desc *
7911 remote_read_description (struct target_ops *target)
7913 struct remote_g_packet_data *data
7914 = gdbarch_data (target_gdbarch, remote_g_packet_data_handle);
7916 /* Do not try this during initial connection, when we do not know
7917 whether there is a running but stopped thread. */
7918 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
7919 return NULL;
7921 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
7923 struct remote_g_packet_guess *guess;
7924 int ix;
7925 int bytes = send_g_packet ();
7927 for (ix = 0;
7928 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
7929 ix++)
7930 if (guess->bytes == bytes)
7931 return guess->tdesc;
7933 /* We discard the g packet. A minor optimization would be to
7934 hold on to it, and fill the register cache once we have selected
7935 an architecture, but it's too tricky to do safely. */
7938 return NULL;
7941 /* Remote file transfer support. This is host-initiated I/O, not
7942 target-initiated; for target-initiated, see remote-fileio.c. */
7944 /* If *LEFT is at least the length of STRING, copy STRING to
7945 *BUFFER, update *BUFFER to point to the new end of the buffer, and
7946 decrease *LEFT. Otherwise raise an error. */
7948 static void
7949 remote_buffer_add_string (char **buffer, int *left, char *string)
7951 int len = strlen (string);
7953 if (len > *left)
7954 error (_("Packet too long for target."));
7956 memcpy (*buffer, string, len);
7957 *buffer += len;
7958 *left -= len;
7960 /* NUL-terminate the buffer as a convenience, if there is
7961 room. */
7962 if (*left)
7963 **buffer = '\0';
7966 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
7967 *BUFFER, update *BUFFER to point to the new end of the buffer, and
7968 decrease *LEFT. Otherwise raise an error. */
7970 static void
7971 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
7972 int len)
7974 if (2 * len > *left)
7975 error (_("Packet too long for target."));
7977 bin2hex (bytes, *buffer, len);
7978 *buffer += 2 * len;
7979 *left -= 2 * len;
7981 /* NUL-terminate the buffer as a convenience, if there is
7982 room. */
7983 if (*left)
7984 **buffer = '\0';
7987 /* If *LEFT is large enough, convert VALUE to hex and add it to
7988 *BUFFER, update *BUFFER to point to the new end of the buffer, and
7989 decrease *LEFT. Otherwise raise an error. */
7991 static void
7992 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
7994 int len = hexnumlen (value);
7996 if (len > *left)
7997 error (_("Packet too long for target."));
7999 hexnumstr (*buffer, value);
8000 *buffer += len;
8001 *left -= len;
8003 /* NUL-terminate the buffer as a convenience, if there is
8004 room. */
8005 if (*left)
8006 **buffer = '\0';
8009 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
8010 value, *REMOTE_ERRNO to the remote error number or zero if none
8011 was included, and *ATTACHMENT to point to the start of the annex
8012 if any. The length of the packet isn't needed here; there may
8013 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
8015 Return 0 if the packet could be parsed, -1 if it could not. If
8016 -1 is returned, the other variables may not be initialized. */
8018 static int
8019 remote_hostio_parse_result (char *buffer, int *retcode,
8020 int *remote_errno, char **attachment)
8022 char *p, *p2;
8024 *remote_errno = 0;
8025 *attachment = NULL;
8027 if (buffer[0] != 'F')
8028 return -1;
8030 errno = 0;
8031 *retcode = strtol (&buffer[1], &p, 16);
8032 if (errno != 0 || p == &buffer[1])
8033 return -1;
8035 /* Check for ",errno". */
8036 if (*p == ',')
8038 errno = 0;
8039 *remote_errno = strtol (p + 1, &p2, 16);
8040 if (errno != 0 || p + 1 == p2)
8041 return -1;
8042 p = p2;
8045 /* Check for ";attachment". If there is no attachment, the
8046 packet should end here. */
8047 if (*p == ';')
8049 *attachment = p + 1;
8050 return 0;
8052 else if (*p == '\0')
8053 return 0;
8054 else
8055 return -1;
8058 /* Send a prepared I/O packet to the target and read its response.
8059 The prepared packet is in the global RS->BUF before this function
8060 is called, and the answer is there when we return.
8062 COMMAND_BYTES is the length of the request to send, which may include
8063 binary data. WHICH_PACKET is the packet configuration to check
8064 before attempting a packet. If an error occurs, *REMOTE_ERRNO
8065 is set to the error number and -1 is returned. Otherwise the value
8066 returned by the function is returned.
8068 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
8069 attachment is expected; an error will be reported if there's a
8070 mismatch. If one is found, *ATTACHMENT will be set to point into
8071 the packet buffer and *ATTACHMENT_LEN will be set to the
8072 attachment's length. */
8074 static int
8075 remote_hostio_send_command (int command_bytes, int which_packet,
8076 int *remote_errno, char **attachment,
8077 int *attachment_len)
8079 struct remote_state *rs = get_remote_state ();
8080 int ret, bytes_read;
8081 char *attachment_tmp;
8083 if (!remote_desc
8084 || remote_protocol_packets[which_packet].support == PACKET_DISABLE)
8086 *remote_errno = FILEIO_ENOSYS;
8087 return -1;
8090 putpkt_binary (rs->buf, command_bytes);
8091 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
8093 /* If it timed out, something is wrong. Don't try to parse the
8094 buffer. */
8095 if (bytes_read < 0)
8097 *remote_errno = FILEIO_EINVAL;
8098 return -1;
8101 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
8103 case PACKET_ERROR:
8104 *remote_errno = FILEIO_EINVAL;
8105 return -1;
8106 case PACKET_UNKNOWN:
8107 *remote_errno = FILEIO_ENOSYS;
8108 return -1;
8109 case PACKET_OK:
8110 break;
8113 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
8114 &attachment_tmp))
8116 *remote_errno = FILEIO_EINVAL;
8117 return -1;
8120 /* Make sure we saw an attachment if and only if we expected one. */
8121 if ((attachment_tmp == NULL && attachment != NULL)
8122 || (attachment_tmp != NULL && attachment == NULL))
8124 *remote_errno = FILEIO_EINVAL;
8125 return -1;
8128 /* If an attachment was found, it must point into the packet buffer;
8129 work out how many bytes there were. */
8130 if (attachment_tmp != NULL)
8132 *attachment = attachment_tmp;
8133 *attachment_len = bytes_read - (*attachment - rs->buf);
8136 return ret;
8139 /* Open FILENAME on the remote target, using FLAGS and MODE. Return a
8140 remote file descriptor, or -1 if an error occurs (and set
8141 *REMOTE_ERRNO). */
8143 static int
8144 remote_hostio_open (const char *filename, int flags, int mode,
8145 int *remote_errno)
8147 struct remote_state *rs = get_remote_state ();
8148 char *p = rs->buf;
8149 int left = get_remote_packet_size () - 1;
8151 remote_buffer_add_string (&p, &left, "vFile:open:");
8153 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
8154 strlen (filename));
8155 remote_buffer_add_string (&p, &left, ",");
8157 remote_buffer_add_int (&p, &left, flags);
8158 remote_buffer_add_string (&p, &left, ",");
8160 remote_buffer_add_int (&p, &left, mode);
8162 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
8163 remote_errno, NULL, NULL);
8166 /* Write up to LEN bytes from WRITE_BUF to FD on the remote target.
8167 Return the number of bytes written, or -1 if an error occurs (and
8168 set *REMOTE_ERRNO). */
8170 static int
8171 remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
8172 ULONGEST offset, int *remote_errno)
8174 struct remote_state *rs = get_remote_state ();
8175 char *p = rs->buf;
8176 int left = get_remote_packet_size ();
8177 int out_len;
8179 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
8181 remote_buffer_add_int (&p, &left, fd);
8182 remote_buffer_add_string (&p, &left, ",");
8184 remote_buffer_add_int (&p, &left, offset);
8185 remote_buffer_add_string (&p, &left, ",");
8187 p += remote_escape_output (write_buf, len, p, &out_len,
8188 get_remote_packet_size () - (p - rs->buf));
8190 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
8191 remote_errno, NULL, NULL);
8194 /* Read up to LEN bytes FD on the remote target into READ_BUF
8195 Return the number of bytes read, or -1 if an error occurs (and
8196 set *REMOTE_ERRNO). */
8198 static int
8199 remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
8200 ULONGEST offset, int *remote_errno)
8202 struct remote_state *rs = get_remote_state ();
8203 char *p = rs->buf;
8204 char *attachment;
8205 int left = get_remote_packet_size ();
8206 int ret, attachment_len;
8207 int read_len;
8209 remote_buffer_add_string (&p, &left, "vFile:pread:");
8211 remote_buffer_add_int (&p, &left, fd);
8212 remote_buffer_add_string (&p, &left, ",");
8214 remote_buffer_add_int (&p, &left, len);
8215 remote_buffer_add_string (&p, &left, ",");
8217 remote_buffer_add_int (&p, &left, offset);
8219 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
8220 remote_errno, &attachment,
8221 &attachment_len);
8223 if (ret < 0)
8224 return ret;
8226 read_len = remote_unescape_input (attachment, attachment_len,
8227 read_buf, len);
8228 if (read_len != ret)
8229 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
8231 return ret;
8234 /* Close FD on the remote target. Return 0, or -1 if an error occurs
8235 (and set *REMOTE_ERRNO). */
8237 static int
8238 remote_hostio_close (int fd, int *remote_errno)
8240 struct remote_state *rs = get_remote_state ();
8241 char *p = rs->buf;
8242 int left = get_remote_packet_size () - 1;
8244 remote_buffer_add_string (&p, &left, "vFile:close:");
8246 remote_buffer_add_int (&p, &left, fd);
8248 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
8249 remote_errno, NULL, NULL);
8252 /* Unlink FILENAME on the remote target. Return 0, or -1 if an error
8253 occurs (and set *REMOTE_ERRNO). */
8255 static int
8256 remote_hostio_unlink (const char *filename, int *remote_errno)
8258 struct remote_state *rs = get_remote_state ();
8259 char *p = rs->buf;
8260 int left = get_remote_packet_size () - 1;
8262 remote_buffer_add_string (&p, &left, "vFile:unlink:");
8264 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
8265 strlen (filename));
8267 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
8268 remote_errno, NULL, NULL);
8271 static int
8272 remote_fileio_errno_to_host (int errnum)
8274 switch (errnum)
8276 case FILEIO_EPERM:
8277 return EPERM;
8278 case FILEIO_ENOENT:
8279 return ENOENT;
8280 case FILEIO_EINTR:
8281 return EINTR;
8282 case FILEIO_EIO:
8283 return EIO;
8284 case FILEIO_EBADF:
8285 return EBADF;
8286 case FILEIO_EACCES:
8287 return EACCES;
8288 case FILEIO_EFAULT:
8289 return EFAULT;
8290 case FILEIO_EBUSY:
8291 return EBUSY;
8292 case FILEIO_EEXIST:
8293 return EEXIST;
8294 case FILEIO_ENODEV:
8295 return ENODEV;
8296 case FILEIO_ENOTDIR:
8297 return ENOTDIR;
8298 case FILEIO_EISDIR:
8299 return EISDIR;
8300 case FILEIO_EINVAL:
8301 return EINVAL;
8302 case FILEIO_ENFILE:
8303 return ENFILE;
8304 case FILEIO_EMFILE:
8305 return EMFILE;
8306 case FILEIO_EFBIG:
8307 return EFBIG;
8308 case FILEIO_ENOSPC:
8309 return ENOSPC;
8310 case FILEIO_ESPIPE:
8311 return ESPIPE;
8312 case FILEIO_EROFS:
8313 return EROFS;
8314 case FILEIO_ENOSYS:
8315 return ENOSYS;
8316 case FILEIO_ENAMETOOLONG:
8317 return ENAMETOOLONG;
8319 return -1;
8322 static char *
8323 remote_hostio_error (int errnum)
8325 int host_error = remote_fileio_errno_to_host (errnum);
8327 if (host_error == -1)
8328 error (_("Unknown remote I/O error %d"), errnum);
8329 else
8330 error (_("Remote I/O error: %s"), safe_strerror (host_error));
8333 static void
8334 remote_hostio_close_cleanup (void *opaque)
8336 int fd = *(int *) opaque;
8337 int remote_errno;
8339 remote_hostio_close (fd, &remote_errno);
8343 static void *
8344 remote_bfd_iovec_open (struct bfd *abfd, void *open_closure)
8346 const char *filename = bfd_get_filename (abfd);
8347 int fd, remote_errno;
8348 int *stream;
8350 gdb_assert (remote_filename_p (filename));
8352 fd = remote_hostio_open (filename + 7, FILEIO_O_RDONLY, 0, &remote_errno);
8353 if (fd == -1)
8355 errno = remote_fileio_errno_to_host (remote_errno);
8356 bfd_set_error (bfd_error_system_call);
8357 return NULL;
8360 stream = xmalloc (sizeof (int));
8361 *stream = fd;
8362 return stream;
8365 static int
8366 remote_bfd_iovec_close (struct bfd *abfd, void *stream)
8368 int fd = *(int *)stream;
8369 int remote_errno;
8371 xfree (stream);
8373 /* Ignore errors on close; these may happen if the remote
8374 connection was already torn down. */
8375 remote_hostio_close (fd, &remote_errno);
8377 return 1;
8380 static file_ptr
8381 remote_bfd_iovec_pread (struct bfd *abfd, void *stream, void *buf,
8382 file_ptr nbytes, file_ptr offset)
8384 int fd = *(int *)stream;
8385 int remote_errno;
8386 file_ptr pos, bytes;
8388 pos = 0;
8389 while (nbytes > pos)
8391 bytes = remote_hostio_pread (fd, (char *)buf + pos, nbytes - pos,
8392 offset + pos, &remote_errno);
8393 if (bytes == 0)
8394 /* Success, but no bytes, means end-of-file. */
8395 break;
8396 if (bytes == -1)
8398 errno = remote_fileio_errno_to_host (remote_errno);
8399 bfd_set_error (bfd_error_system_call);
8400 return -1;
8403 pos += bytes;
8406 return pos;
8409 static int
8410 remote_bfd_iovec_stat (struct bfd *abfd, void *stream, struct stat *sb)
8412 /* FIXME: We should probably implement remote_hostio_stat. */
8413 sb->st_size = INT_MAX;
8414 return 0;
8418 remote_filename_p (const char *filename)
8420 return strncmp (filename, "remote:", 7) == 0;
8423 bfd *
8424 remote_bfd_open (const char *remote_file, const char *target)
8426 return bfd_openr_iovec (remote_file, target,
8427 remote_bfd_iovec_open, NULL,
8428 remote_bfd_iovec_pread,
8429 remote_bfd_iovec_close,
8430 remote_bfd_iovec_stat);
8433 void
8434 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
8436 struct cleanup *back_to, *close_cleanup;
8437 int retcode, fd, remote_errno, bytes, io_size;
8438 FILE *file;
8439 gdb_byte *buffer;
8440 int bytes_in_buffer;
8441 int saw_eof;
8442 ULONGEST offset;
8444 if (!remote_desc)
8445 error (_("command can only be used with remote target"));
8447 file = fopen (local_file, "rb");
8448 if (file == NULL)
8449 perror_with_name (local_file);
8450 back_to = make_cleanup_fclose (file);
8452 fd = remote_hostio_open (remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
8453 | FILEIO_O_TRUNC),
8454 0700, &remote_errno);
8455 if (fd == -1)
8456 remote_hostio_error (remote_errno);
8458 /* Send up to this many bytes at once. They won't all fit in the
8459 remote packet limit, so we'll transfer slightly fewer. */
8460 io_size = get_remote_packet_size ();
8461 buffer = xmalloc (io_size);
8462 make_cleanup (xfree, buffer);
8464 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
8466 bytes_in_buffer = 0;
8467 saw_eof = 0;
8468 offset = 0;
8469 while (bytes_in_buffer || !saw_eof)
8471 if (!saw_eof)
8473 bytes = fread (buffer + bytes_in_buffer, 1, io_size - bytes_in_buffer,
8474 file);
8475 if (bytes == 0)
8477 if (ferror (file))
8478 error (_("Error reading %s."), local_file);
8479 else
8481 /* EOF. Unless there is something still in the
8482 buffer from the last iteration, we are done. */
8483 saw_eof = 1;
8484 if (bytes_in_buffer == 0)
8485 break;
8489 else
8490 bytes = 0;
8492 bytes += bytes_in_buffer;
8493 bytes_in_buffer = 0;
8495 retcode = remote_hostio_pwrite (fd, buffer, bytes, offset, &remote_errno);
8497 if (retcode < 0)
8498 remote_hostio_error (remote_errno);
8499 else if (retcode == 0)
8500 error (_("Remote write of %d bytes returned 0!"), bytes);
8501 else if (retcode < bytes)
8503 /* Short write. Save the rest of the read data for the next
8504 write. */
8505 bytes_in_buffer = bytes - retcode;
8506 memmove (buffer, buffer + retcode, bytes_in_buffer);
8509 offset += retcode;
8512 discard_cleanups (close_cleanup);
8513 if (remote_hostio_close (fd, &remote_errno))
8514 remote_hostio_error (remote_errno);
8516 if (from_tty)
8517 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
8518 do_cleanups (back_to);
8521 void
8522 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
8524 struct cleanup *back_to, *close_cleanup;
8525 int retcode, fd, remote_errno, bytes, io_size;
8526 FILE *file;
8527 gdb_byte *buffer;
8528 ULONGEST offset;
8530 if (!remote_desc)
8531 error (_("command can only be used with remote target"));
8533 fd = remote_hostio_open (remote_file, FILEIO_O_RDONLY, 0, &remote_errno);
8534 if (fd == -1)
8535 remote_hostio_error (remote_errno);
8537 file = fopen (local_file, "wb");
8538 if (file == NULL)
8539 perror_with_name (local_file);
8540 back_to = make_cleanup_fclose (file);
8542 /* Send up to this many bytes at once. They won't all fit in the
8543 remote packet limit, so we'll transfer slightly fewer. */
8544 io_size = get_remote_packet_size ();
8545 buffer = xmalloc (io_size);
8546 make_cleanup (xfree, buffer);
8548 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
8550 offset = 0;
8551 while (1)
8553 bytes = remote_hostio_pread (fd, buffer, io_size, offset, &remote_errno);
8554 if (bytes == 0)
8555 /* Success, but no bytes, means end-of-file. */
8556 break;
8557 if (bytes == -1)
8558 remote_hostio_error (remote_errno);
8560 offset += bytes;
8562 bytes = fwrite (buffer, 1, bytes, file);
8563 if (bytes == 0)
8564 perror_with_name (local_file);
8567 discard_cleanups (close_cleanup);
8568 if (remote_hostio_close (fd, &remote_errno))
8569 remote_hostio_error (remote_errno);
8571 if (from_tty)
8572 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
8573 do_cleanups (back_to);
8576 void
8577 remote_file_delete (const char *remote_file, int from_tty)
8579 int retcode, remote_errno;
8581 if (!remote_desc)
8582 error (_("command can only be used with remote target"));
8584 retcode = remote_hostio_unlink (remote_file, &remote_errno);
8585 if (retcode == -1)
8586 remote_hostio_error (remote_errno);
8588 if (from_tty)
8589 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
8592 static void
8593 remote_put_command (char *args, int from_tty)
8595 struct cleanup *back_to;
8596 char **argv;
8598 if (args == NULL)
8599 error_no_arg (_("file to put"));
8601 argv = gdb_buildargv (args);
8602 back_to = make_cleanup_freeargv (argv);
8603 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
8604 error (_("Invalid parameters to remote put"));
8606 remote_file_put (argv[0], argv[1], from_tty);
8608 do_cleanups (back_to);
8611 static void
8612 remote_get_command (char *args, int from_tty)
8614 struct cleanup *back_to;
8615 char **argv;
8617 if (args == NULL)
8618 error_no_arg (_("file to get"));
8620 argv = gdb_buildargv (args);
8621 back_to = make_cleanup_freeargv (argv);
8622 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
8623 error (_("Invalid parameters to remote get"));
8625 remote_file_get (argv[0], argv[1], from_tty);
8627 do_cleanups (back_to);
8630 static void
8631 remote_delete_command (char *args, int from_tty)
8633 struct cleanup *back_to;
8634 char **argv;
8636 if (args == NULL)
8637 error_no_arg (_("file to delete"));
8639 argv = gdb_buildargv (args);
8640 back_to = make_cleanup_freeargv (argv);
8641 if (argv[0] == NULL || argv[1] != NULL)
8642 error (_("Invalid parameters to remote delete"));
8644 remote_file_delete (argv[0], from_tty);
8646 do_cleanups (back_to);
8649 static void
8650 remote_command (char *args, int from_tty)
8652 help_list (remote_cmdlist, "remote ", -1, gdb_stdout);
8655 static int remote_target_can_reverse = 1;
8657 static int
8658 remote_can_execute_reverse (void)
8660 return remote_target_can_reverse;
8663 static int
8664 remote_supports_non_stop (void)
8666 return 1;
8669 static int
8670 remote_supports_multi_process (void)
8672 struct remote_state *rs = get_remote_state ();
8673 return remote_multi_process_p (rs);
8676 static void
8677 init_remote_ops (void)
8679 remote_ops.to_shortname = "remote";
8680 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
8681 remote_ops.to_doc =
8682 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
8683 Specify the serial device it is connected to\n\
8684 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
8685 remote_ops.to_open = remote_open;
8686 remote_ops.to_close = remote_close;
8687 remote_ops.to_detach = remote_detach;
8688 remote_ops.to_disconnect = remote_disconnect;
8689 remote_ops.to_resume = remote_resume;
8690 remote_ops.to_wait = remote_wait;
8691 remote_ops.to_fetch_registers = remote_fetch_registers;
8692 remote_ops.to_store_registers = remote_store_registers;
8693 remote_ops.to_prepare_to_store = remote_prepare_to_store;
8694 remote_ops.deprecated_xfer_memory = remote_xfer_memory;
8695 remote_ops.to_files_info = remote_files_info;
8696 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
8697 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
8698 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
8699 remote_ops.to_stopped_data_address = remote_stopped_data_address;
8700 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
8701 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
8702 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
8703 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
8704 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
8705 remote_ops.to_kill = remote_kill;
8706 remote_ops.to_load = generic_load;
8707 remote_ops.to_mourn_inferior = remote_mourn;
8708 remote_ops.to_thread_alive = remote_thread_alive;
8709 remote_ops.to_find_new_threads = remote_threads_info;
8710 remote_ops.to_pid_to_str = remote_pid_to_str;
8711 remote_ops.to_extra_thread_info = remote_threads_extra_info;
8712 remote_ops.to_stop = remote_stop;
8713 remote_ops.to_xfer_partial = remote_xfer_partial;
8714 remote_ops.to_rcmd = remote_rcmd;
8715 remote_ops.to_log_command = serial_log_command;
8716 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
8717 remote_ops.to_stratum = process_stratum;
8718 remote_ops.to_has_all_memory = 1;
8719 remote_ops.to_has_memory = 1;
8720 remote_ops.to_has_stack = 1;
8721 remote_ops.to_has_registers = 1;
8722 remote_ops.to_has_execution = 1;
8723 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
8724 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
8725 remote_ops.to_magic = OPS_MAGIC;
8726 remote_ops.to_memory_map = remote_memory_map;
8727 remote_ops.to_flash_erase = remote_flash_erase;
8728 remote_ops.to_flash_done = remote_flash_done;
8729 remote_ops.to_read_description = remote_read_description;
8730 remote_ops.to_search_memory = remote_search_memory;
8731 remote_ops.to_can_async_p = remote_can_async_p;
8732 remote_ops.to_is_async_p = remote_is_async_p;
8733 remote_ops.to_async = remote_async;
8734 remote_ops.to_async_mask = remote_async_mask;
8735 remote_ops.to_terminal_inferior = remote_terminal_inferior;
8736 remote_ops.to_terminal_ours = remote_terminal_ours;
8737 remote_ops.to_supports_non_stop = remote_supports_non_stop;
8738 remote_ops.to_supports_multi_process = remote_supports_multi_process;
8741 /* Set up the extended remote vector by making a copy of the standard
8742 remote vector and adding to it. */
8744 static void
8745 init_extended_remote_ops (void)
8747 extended_remote_ops = remote_ops;
8749 extended_remote_ops.to_shortname = "extended-remote";
8750 extended_remote_ops.to_longname =
8751 "Extended remote serial target in gdb-specific protocol";
8752 extended_remote_ops.to_doc =
8753 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
8754 Specify the serial device it is connected to (e.g. /dev/ttya).";
8755 extended_remote_ops.to_open = extended_remote_open;
8756 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
8757 extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
8758 extended_remote_ops.to_detach = extended_remote_detach;
8759 extended_remote_ops.to_attach = extended_remote_attach;
8760 extended_remote_ops.to_kill = extended_remote_kill;
8763 static int
8764 remote_can_async_p (void)
8766 if (!target_async_permitted)
8767 /* We only enable async when the user specifically asks for it. */
8768 return 0;
8770 /* We're async whenever the serial device is. */
8771 return remote_async_mask_value && serial_can_async_p (remote_desc);
8774 static int
8775 remote_is_async_p (void)
8777 if (!target_async_permitted)
8778 /* We only enable async when the user specifically asks for it. */
8779 return 0;
8781 /* We're async whenever the serial device is. */
8782 return remote_async_mask_value && serial_is_async_p (remote_desc);
8785 /* Pass the SERIAL event on and up to the client. One day this code
8786 will be able to delay notifying the client of an event until the
8787 point where an entire packet has been received. */
8789 static void (*async_client_callback) (enum inferior_event_type event_type,
8790 void *context);
8791 static void *async_client_context;
8792 static serial_event_ftype remote_async_serial_handler;
8794 static void
8795 remote_async_serial_handler (struct serial *scb, void *context)
8797 /* Don't propogate error information up to the client. Instead let
8798 the client find out about the error by querying the target. */
8799 async_client_callback (INF_REG_EVENT, async_client_context);
8802 static void
8803 remote_async_inferior_event_handler (gdb_client_data data)
8805 inferior_event_handler (INF_REG_EVENT, NULL);
8808 static void
8809 remote_async_get_pending_events_handler (gdb_client_data data)
8811 remote_get_pending_stop_replies ();
8814 static void
8815 remote_async (void (*callback) (enum inferior_event_type event_type,
8816 void *context), void *context)
8818 if (remote_async_mask_value == 0)
8819 internal_error (__FILE__, __LINE__,
8820 _("Calling remote_async when async is masked"));
8822 if (callback != NULL)
8824 serial_async (remote_desc, remote_async_serial_handler, NULL);
8825 async_client_callback = callback;
8826 async_client_context = context;
8828 else
8829 serial_async (remote_desc, NULL, NULL);
8832 static int
8833 remote_async_mask (int new_mask)
8835 int curr_mask = remote_async_mask_value;
8836 remote_async_mask_value = new_mask;
8837 return curr_mask;
8840 static void
8841 set_remote_cmd (char *args, int from_tty)
8843 help_list (remote_set_cmdlist, "set remote ", -1, gdb_stdout);
8846 static void
8847 show_remote_cmd (char *args, int from_tty)
8849 /* We can't just use cmd_show_list here, because we want to skip
8850 the redundant "show remote Z-packet" and the legacy aliases. */
8851 struct cleanup *showlist_chain;
8852 struct cmd_list_element *list = remote_show_cmdlist;
8854 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
8855 for (; list != NULL; list = list->next)
8856 if (strcmp (list->name, "Z-packet") == 0)
8857 continue;
8858 else if (list->type == not_set_cmd)
8859 /* Alias commands are exactly like the original, except they
8860 don't have the normal type. */
8861 continue;
8862 else
8864 struct cleanup *option_chain
8865 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
8866 ui_out_field_string (uiout, "name", list->name);
8867 ui_out_text (uiout, ": ");
8868 if (list->type == show_cmd)
8869 do_setshow_command ((char *) NULL, from_tty, list);
8870 else
8871 cmd_func (list, NULL, from_tty);
8872 /* Close the tuple. */
8873 do_cleanups (option_chain);
8876 /* Close the tuple. */
8877 do_cleanups (showlist_chain);
8881 /* Function to be called whenever a new objfile (shlib) is detected. */
8882 static void
8883 remote_new_objfile (struct objfile *objfile)
8885 if (remote_desc != 0) /* Have a remote connection. */
8886 remote_check_symbols (objfile);
8889 void
8890 _initialize_remote (void)
8892 struct remote_state *rs;
8894 /* architecture specific data */
8895 remote_gdbarch_data_handle =
8896 gdbarch_data_register_post_init (init_remote_state);
8897 remote_g_packet_data_handle =
8898 gdbarch_data_register_pre_init (remote_g_packet_data_init);
8900 /* Initialize the per-target state. At the moment there is only one
8901 of these, not one per target. Only one target is active at a
8902 time. The default buffer size is unimportant; it will be expanded
8903 whenever a larger buffer is needed. */
8904 rs = get_remote_state_raw ();
8905 rs->buf_size = 400;
8906 rs->buf = xmalloc (rs->buf_size);
8908 init_remote_ops ();
8909 add_target (&remote_ops);
8911 init_extended_remote_ops ();
8912 add_target (&extended_remote_ops);
8914 /* Hook into new objfile notification. */
8915 observer_attach_new_objfile (remote_new_objfile);
8917 /* Set up signal handlers. */
8918 sigint_remote_token =
8919 create_async_signal_handler (async_remote_interrupt, NULL);
8920 sigint_remote_twice_token =
8921 create_async_signal_handler (inferior_event_handler_wrapper, NULL);
8923 #if 0
8924 init_remote_threadtests ();
8925 #endif
8927 /* set/show remote ... */
8929 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
8930 Remote protocol specific variables\n\
8931 Configure various remote-protocol specific variables such as\n\
8932 the packets being used"),
8933 &remote_set_cmdlist, "set remote ",
8934 0 /* allow-unknown */, &setlist);
8935 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
8936 Remote protocol specific variables\n\
8937 Configure various remote-protocol specific variables such as\n\
8938 the packets being used"),
8939 &remote_show_cmdlist, "show remote ",
8940 0 /* allow-unknown */, &showlist);
8942 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
8943 Compare section data on target to the exec file.\n\
8944 Argument is a single section name (default: all loaded sections)."),
8945 &cmdlist);
8947 add_cmd ("packet", class_maintenance, packet_command, _("\
8948 Send an arbitrary packet to a remote target.\n\
8949 maintenance packet TEXT\n\
8950 If GDB is talking to an inferior via the GDB serial protocol, then\n\
8951 this command sends the string TEXT to the inferior, and displays the\n\
8952 response packet. GDB supplies the initial `$' character, and the\n\
8953 terminating `#' character and checksum."),
8954 &maintenancelist);
8956 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
8957 Set whether to send break if interrupted."), _("\
8958 Show whether to send break if interrupted."), _("\
8959 If set, a break, instead of a cntrl-c, is sent to the remote target."),
8960 NULL, NULL, /* FIXME: i18n: Whether to send break if interrupted is %s. */
8961 &setlist, &showlist);
8963 /* Install commands for configuring memory read/write packets. */
8965 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
8966 Set the maximum number of bytes per memory write packet (deprecated)."),
8967 &setlist);
8968 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
8969 Show the maximum number of bytes per memory write packet (deprecated)."),
8970 &showlist);
8971 add_cmd ("memory-write-packet-size", no_class,
8972 set_memory_write_packet_size, _("\
8973 Set the maximum number of bytes per memory-write packet.\n\
8974 Specify the number of bytes in a packet or 0 (zero) for the\n\
8975 default packet size. The actual limit is further reduced\n\
8976 dependent on the target. Specify ``fixed'' to disable the\n\
8977 further restriction and ``limit'' to enable that restriction."),
8978 &remote_set_cmdlist);
8979 add_cmd ("memory-read-packet-size", no_class,
8980 set_memory_read_packet_size, _("\
8981 Set the maximum number of bytes per memory-read packet.\n\
8982 Specify the number of bytes in a packet or 0 (zero) for the\n\
8983 default packet size. The actual limit is further reduced\n\
8984 dependent on the target. Specify ``fixed'' to disable the\n\
8985 further restriction and ``limit'' to enable that restriction."),
8986 &remote_set_cmdlist);
8987 add_cmd ("memory-write-packet-size", no_class,
8988 show_memory_write_packet_size,
8989 _("Show the maximum number of bytes per memory-write packet."),
8990 &remote_show_cmdlist);
8991 add_cmd ("memory-read-packet-size", no_class,
8992 show_memory_read_packet_size,
8993 _("Show the maximum number of bytes per memory-read packet."),
8994 &remote_show_cmdlist);
8996 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
8997 &remote_hw_watchpoint_limit, _("\
8998 Set the maximum number of target hardware watchpoints."), _("\
8999 Show the maximum number of target hardware watchpoints."), _("\
9000 Specify a negative limit for unlimited."),
9001 NULL, NULL, /* FIXME: i18n: The maximum number of target hardware watchpoints is %s. */
9002 &remote_set_cmdlist, &remote_show_cmdlist);
9003 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
9004 &remote_hw_breakpoint_limit, _("\
9005 Set the maximum number of target hardware breakpoints."), _("\
9006 Show the maximum number of target hardware breakpoints."), _("\
9007 Specify a negative limit for unlimited."),
9008 NULL, NULL, /* FIXME: i18n: The maximum number of target hardware breakpoints is %s. */
9009 &remote_set_cmdlist, &remote_show_cmdlist);
9011 add_setshow_integer_cmd ("remoteaddresssize", class_obscure,
9012 &remote_address_size, _("\
9013 Set the maximum size of the address (in bits) in a memory packet."), _("\
9014 Show the maximum size of the address (in bits) in a memory packet."), NULL,
9015 NULL,
9016 NULL, /* FIXME: i18n: */
9017 &setlist, &showlist);
9019 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
9020 "X", "binary-download", 1);
9022 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
9023 "vCont", "verbose-resume", 0);
9025 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
9026 "QPassSignals", "pass-signals", 0);
9028 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
9029 "qSymbol", "symbol-lookup", 0);
9031 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
9032 "P", "set-register", 1);
9034 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
9035 "p", "fetch-register", 1);
9037 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
9038 "Z0", "software-breakpoint", 0);
9040 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
9041 "Z1", "hardware-breakpoint", 0);
9043 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
9044 "Z2", "write-watchpoint", 0);
9046 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
9047 "Z3", "read-watchpoint", 0);
9049 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
9050 "Z4", "access-watchpoint", 0);
9052 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
9053 "qXfer:auxv:read", "read-aux-vector", 0);
9055 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
9056 "qXfer:features:read", "target-features", 0);
9058 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
9059 "qXfer:libraries:read", "library-info", 0);
9061 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
9062 "qXfer:memory-map:read", "memory-map", 0);
9064 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
9065 "qXfer:spu:read", "read-spu-object", 0);
9067 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
9068 "qXfer:spu:write", "write-spu-object", 0);
9070 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
9071 "qXfer:osdata:read", "osdata", 0);
9073 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
9074 "qGetTLSAddr", "get-thread-local-storage-address",
9077 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
9078 "qSupported", "supported-packets", 0);
9080 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
9081 "qSearch:memory", "search-memory", 0);
9083 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
9084 "vFile:open", "hostio-open", 0);
9086 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
9087 "vFile:pread", "hostio-pread", 0);
9089 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
9090 "vFile:pwrite", "hostio-pwrite", 0);
9092 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
9093 "vFile:close", "hostio-close", 0);
9095 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
9096 "vFile:unlink", "hostio-unlink", 0);
9098 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
9099 "vAttach", "attach", 0);
9101 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
9102 "vRun", "run", 0);
9104 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
9105 "QStartNoAckMode", "noack", 0);
9107 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
9108 "vKill", "kill", 0);
9110 /* Keep the old ``set remote Z-packet ...'' working. Each individual
9111 Z sub-packet has its own set and show commands, but users may
9112 have sets to this variable in their .gdbinit files (or in their
9113 documentation). */
9114 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
9115 &remote_Z_packet_detect, _("\
9116 Set use of remote protocol `Z' packets"), _("\
9117 Show use of remote protocol `Z' packets "), _("\
9118 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
9119 packets."),
9120 set_remote_protocol_Z_packet_cmd,
9121 show_remote_protocol_Z_packet_cmd, /* FIXME: i18n: Use of remote protocol `Z' packets is %s. */
9122 &remote_set_cmdlist, &remote_show_cmdlist);
9124 add_prefix_cmd ("remote", class_files, remote_command, _("\
9125 Manipulate files on the remote system\n\
9126 Transfer files to and from the remote target system."),
9127 &remote_cmdlist, "remote ",
9128 0 /* allow-unknown */, &cmdlist);
9130 add_cmd ("put", class_files, remote_put_command,
9131 _("Copy a local file to the remote system."),
9132 &remote_cmdlist);
9134 add_cmd ("get", class_files, remote_get_command,
9135 _("Copy a remote file to the local system."),
9136 &remote_cmdlist);
9138 add_cmd ("delete", class_files, remote_delete_command,
9139 _("Delete a remote file."),
9140 &remote_cmdlist);
9142 remote_exec_file = xstrdup ("");
9143 add_setshow_string_noescape_cmd ("exec-file", class_files,
9144 &remote_exec_file, _("\
9145 Set the remote pathname for \"run\""), _("\
9146 Show the remote pathname for \"run\""), NULL, NULL, NULL,
9147 &remote_set_cmdlist, &remote_show_cmdlist);
9149 /* Eventually initialize fileio. See fileio.c */
9150 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
9152 /* Take advantage of the fact that the LWP field is not used, to tag
9153 special ptids with it set to != 0. */
9154 magic_null_ptid = ptid_build (42000, 1, -1);
9155 not_sent_ptid = ptid_build (42000, 1, -2);
9156 any_thread_ptid = ptid_build (42000, 1, 0);