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 2010 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. */
25 #include "gdb_string.h"
31 #include "exceptions.h"
33 /*#include "terminal.h" */
36 #include "gdb-stabs.h"
37 #include "gdbthread.h"
41 #include "gdb_assert.h"
44 #include "cli/cli-decode.h"
45 #include "cli/cli-setshow.h"
46 #include "target-descriptions.h"
51 #include "event-loop.h"
52 #include "event-top.h"
58 #include "gdbcore.h" /* for exec_bfd */
60 #include "remote-fileio.h"
61 #include "gdb/fileio.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,
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_open (char *name, int from_tty);
96 static void extended_remote_open (char *name, int from_tty);
98 static void remote_open_1 (char *, int, struct target_ops *, int extended_p);
100 static void remote_close (int quitting);
102 static void remote_mourn (struct target_ops *ops);
104 static void extended_remote_restart (void);
106 static void extended_remote_mourn (struct target_ops *);
108 static void remote_mourn_1 (struct target_ops *);
110 static void remote_send (char **buf, long *sizeof_buf_p);
112 static int readchar (int timeout);
114 static void remote_kill (struct target_ops *ops);
116 static int tohex (int nib);
118 static int remote_can_async_p (void);
120 static int remote_is_async_p (void);
122 static void remote_async (void (*callback) (enum inferior_event_type event_type,
123 void *context), void *context);
125 static int remote_async_mask (int new_mask);
127 static void remote_detach (struct target_ops *ops, char *args, int from_tty);
129 static void remote_interrupt (int signo);
131 static void remote_interrupt_twice (int signo);
133 static void interrupt_query (void);
135 static void set_general_thread (struct ptid ptid);
136 static void set_continue_thread (struct ptid ptid);
138 static void get_offsets (void);
140 static void skip_frame (void);
142 static long read_frame (char **buf_p, long *sizeof_buf);
144 static int hexnumlen (ULONGEST num);
146 static void init_remote_ops (void);
148 static void init_extended_remote_ops (void);
150 static void remote_stop (ptid_t);
152 static int ishex (int ch, int *val);
154 static int stubhex (int ch);
156 static int hexnumstr (char *, ULONGEST);
158 static int hexnumnstr (char *, ULONGEST, int);
160 static CORE_ADDR remote_address_masked (CORE_ADDR);
162 static void print_packet (char *);
164 static unsigned long crc32 (unsigned char *, int, unsigned int);
166 static void compare_sections_command (char *, int);
168 static void packet_command (char *, int);
170 static int stub_unpack_int (char *buff, int fieldlength);
172 static ptid_t remote_current_thread (ptid_t oldptid);
174 static void remote_find_new_threads (void);
176 static void record_currthread (ptid_t currthread);
178 static int fromhex (int a);
180 static int hex2bin (const char *hex, gdb_byte *bin, int count);
182 static int bin2hex (const gdb_byte *bin, char *hex, int count);
184 static int putpkt_binary (char *buf, int cnt);
186 static void check_binary_download (CORE_ADDR addr);
188 struct packet_config;
190 static void show_packet_config_cmd (struct packet_config *config);
192 static void update_packet_config (struct packet_config *config);
194 static void set_remote_protocol_packet_cmd (char *args, int from_tty,
195 struct cmd_list_element *c);
197 static void show_remote_protocol_packet_cmd (struct ui_file *file,
199 struct cmd_list_element *c,
202 static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
203 static ptid_t read_ptid (char *buf, char **obuf);
205 static void remote_query_supported (void);
207 static void remote_check_symbols (struct objfile *objfile);
209 void _initialize_remote (void);
212 static struct stop_reply *stop_reply_xmalloc (void);
213 static void stop_reply_xfree (struct stop_reply *);
214 static void do_stop_reply_xfree (void *arg);
215 static void remote_parse_stop_reply (char *buf, struct stop_reply *);
216 static void push_stop_reply (struct stop_reply *);
217 static void remote_get_pending_stop_replies (void);
218 static void discard_pending_stop_replies (int pid);
219 static int peek_stop_reply (ptid_t ptid);
221 static void remote_async_inferior_event_handler (gdb_client_data);
222 static void remote_async_get_pending_events_handler (gdb_client_data);
224 static void remote_terminal_ours (void);
226 static int remote_read_description_p (struct target_ops *target);
228 /* The non-stop remote protocol provisions for one pending stop reply.
229 This is where we keep it until it is acknowledged. */
231 static struct stop_reply *pending_stop_reply = NULL;
235 static struct cmd_list_element *remote_cmdlist;
237 /* For "set remote" and "show remote". */
239 static struct cmd_list_element *remote_set_cmdlist;
240 static struct cmd_list_element *remote_show_cmdlist;
242 /* Description of the remote protocol state for the currently
243 connected target. This is per-target state, and independent of the
244 selected architecture. */
248 /* A buffer to use for incoming packets, and its current size. The
249 buffer is grown dynamically for larger incoming packets.
250 Outgoing packets may also be constructed in this buffer.
251 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
252 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
257 /* If we negotiated packet size explicitly (and thus can bypass
258 heuristics for the largest packet size that will not overflow
259 a buffer in the stub), this will be set to that packet size.
260 Otherwise zero, meaning to use the guessed size. */
261 long explicit_packet_size;
263 /* remote_wait is normally called when the target is running and
264 waits for a stop reply packet. But sometimes we need to call it
265 when the target is already stopped. We can send a "?" packet
266 and have remote_wait read the response. Or, if we already have
267 the response, we can stash it in BUF and tell remote_wait to
268 skip calling getpkt. This flag is set when BUF contains a
269 stop reply packet and the target is not waiting. */
270 int cached_wait_status;
272 /* True, if in no ack mode. That is, neither GDB nor the stub will
273 expect acks from each other. The connection is assumed to be
277 /* True if we're connected in extended remote mode. */
280 /* True if the stub reported support for multi-process
282 int multi_process_aware;
284 /* True if we resumed the target and we're waiting for the target to
285 stop. In the mean time, we can't start another command/query.
286 The remote server wouldn't be ready to process it, so we'd
287 timeout waiting for a reply that would never come and eventually
288 we'd close the connection. This can happen in asynchronous mode
289 because we allow GDB commands while the target is running. */
290 int waiting_for_stop_reply;
292 /* True if the stub reports support for non-stop mode. */
295 /* True if the stub reports support for vCont;t. */
298 /* True if the stub reports support for conditional tracepoints. */
299 int cond_tracepoints;
301 /* True if the stub reports support for fast tracepoints. */
302 int fast_tracepoints;
304 /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
305 responded to that. */
309 /* Returns true if the multi-process extensions are in effect. */
311 remote_multi_process_p (struct remote_state *rs)
313 return rs->extended && rs->multi_process_aware;
316 /* This data could be associated with a target, but we do not always
317 have access to the current target when we need it, so for now it is
318 static. This will be fine for as long as only one target is in use
320 static struct remote_state remote_state;
322 static struct remote_state *
323 get_remote_state_raw (void)
325 return &remote_state;
328 /* Description of the remote protocol for a given architecture. */
332 long offset; /* Offset into G packet. */
333 long regnum; /* GDB's internal register number. */
334 LONGEST pnum; /* Remote protocol register number. */
335 int in_g_packet; /* Always part of G packet. */
336 /* long size in bytes; == register_size (target_gdbarch, regnum);
338 /* char *name; == gdbarch_register_name (target_gdbarch, regnum);
342 struct remote_arch_state
344 /* Description of the remote protocol registers. */
345 long sizeof_g_packet;
347 /* Description of the remote protocol registers indexed by REGNUM
348 (making an array gdbarch_num_regs in size). */
349 struct packet_reg *regs;
351 /* This is the size (in chars) of the first response to the ``g''
352 packet. It is used as a heuristic when determining the maximum
353 size of memory-read and memory-write packets. A target will
354 typically only reserve a buffer large enough to hold the ``g''
355 packet. The size does not include packet overhead (headers and
357 long actual_register_packet_size;
359 /* This is the maximum size (in chars) of a non read/write packet.
360 It is also used as a cap on the size of read/write packets. */
361 long remote_packet_size;
365 /* Handle for retreving the remote protocol data from gdbarch. */
366 static struct gdbarch_data *remote_gdbarch_data_handle;
368 static struct remote_arch_state *
369 get_remote_arch_state (void)
371 return gdbarch_data (target_gdbarch, remote_gdbarch_data_handle);
374 /* Fetch the global remote target state. */
376 static struct remote_state *
377 get_remote_state (void)
379 /* Make sure that the remote architecture state has been
380 initialized, because doing so might reallocate rs->buf. Any
381 function which calls getpkt also needs to be mindful of changes
382 to rs->buf, but this call limits the number of places which run
384 get_remote_arch_state ();
386 return get_remote_state_raw ();
390 compare_pnums (const void *lhs_, const void *rhs_)
392 const struct packet_reg * const *lhs = lhs_;
393 const struct packet_reg * const *rhs = rhs_;
395 if ((*lhs)->pnum < (*rhs)->pnum)
397 else if ((*lhs)->pnum == (*rhs)->pnum)
404 init_remote_state (struct gdbarch *gdbarch)
406 int regnum, num_remote_regs, offset;
407 struct remote_state *rs = get_remote_state_raw ();
408 struct remote_arch_state *rsa;
409 struct packet_reg **remote_regs;
411 rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
413 /* Use the architecture to build a regnum<->pnum table, which will be
414 1:1 unless a feature set specifies otherwise. */
415 rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
416 gdbarch_num_regs (gdbarch),
418 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
420 struct packet_reg *r = &rsa->regs[regnum];
422 if (register_size (gdbarch, regnum) == 0)
423 /* Do not try to fetch zero-sized (placeholder) registers. */
426 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
431 /* Define the g/G packet format as the contents of each register
432 with a remote protocol number, in order of ascending protocol
435 remote_regs = alloca (gdbarch_num_regs (gdbarch)
436 * sizeof (struct packet_reg *));
437 for (num_remote_regs = 0, regnum = 0;
438 regnum < gdbarch_num_regs (gdbarch);
440 if (rsa->regs[regnum].pnum != -1)
441 remote_regs[num_remote_regs++] = &rsa->regs[regnum];
443 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
446 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
448 remote_regs[regnum]->in_g_packet = 1;
449 remote_regs[regnum]->offset = offset;
450 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
453 /* Record the maximum possible size of the g packet - it may turn out
455 rsa->sizeof_g_packet = offset;
457 /* Default maximum number of characters in a packet body. Many
458 remote stubs have a hardwired buffer size of 400 bytes
459 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
460 as the maximum packet-size to ensure that the packet and an extra
461 NUL character can always fit in the buffer. This stops GDB
462 trashing stubs that try to squeeze an extra NUL into what is
463 already a full buffer (As of 1999-12-04 that was most stubs). */
464 rsa->remote_packet_size = 400 - 1;
466 /* This one is filled in when a ``g'' packet is received. */
467 rsa->actual_register_packet_size = 0;
469 /* Should rsa->sizeof_g_packet needs more space than the
470 default, adjust the size accordingly. Remember that each byte is
471 encoded as two characters. 32 is the overhead for the packet
472 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
473 (``$NN:G...#NN'') is a better guess, the below has been padded a
475 if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
476 rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
478 /* Make sure that the packet buffer is plenty big enough for
479 this architecture. */
480 if (rs->buf_size < rsa->remote_packet_size)
482 rs->buf_size = 2 * rsa->remote_packet_size;
483 rs->buf = xrealloc (rs->buf, rs->buf_size);
489 /* Return the current allowed size of a remote packet. This is
490 inferred from the current architecture, and should be used to
491 limit the length of outgoing packets. */
493 get_remote_packet_size (void)
495 struct remote_state *rs = get_remote_state ();
496 struct remote_arch_state *rsa = get_remote_arch_state ();
498 if (rs->explicit_packet_size)
499 return rs->explicit_packet_size;
501 return rsa->remote_packet_size;
504 static struct packet_reg *
505 packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
507 if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch))
511 struct packet_reg *r = &rsa->regs[regnum];
512 gdb_assert (r->regnum == regnum);
517 static struct packet_reg *
518 packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
521 for (i = 0; i < gdbarch_num_regs (target_gdbarch); i++)
523 struct packet_reg *r = &rsa->regs[i];
530 /* FIXME: graces/2002-08-08: These variables should eventually be
531 bound to an instance of the target object (as in gdbarch-tdep()),
532 when such a thing exists. */
534 /* This is set to the data address of the access causing the target
535 to stop for a watchpoint. */
536 static CORE_ADDR remote_watch_data_address;
538 /* This is non-zero if target stopped for a watchpoint. */
539 static int remote_stopped_by_watchpoint_p;
541 static struct target_ops remote_ops;
543 static struct target_ops extended_remote_ops;
545 static int remote_async_mask_value = 1;
547 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
548 ``forever'' still use the normal timeout mechanism. This is
549 currently used by the ASYNC code to guarentee that target reads
550 during the initial connect always time-out. Once getpkt has been
551 modified to return a timeout indication and, in turn
552 remote_wait()/wait_for_inferior() have gained a timeout parameter
554 static int wait_forever_enabled_p = 1;
556 /* Allow the user to specify what sequence to send to the remote
557 when he requests a program interruption: Although ^C is usually
558 what remote systems expect (this is the default, here), it is
559 sometimes preferable to send a break. On other systems such
560 as the Linux kernel, a break followed by g, which is Magic SysRq g
561 is required in order to interrupt the execution. */
562 const char interrupt_sequence_control_c[] = "Ctrl-C";
563 const char interrupt_sequence_break[] = "BREAK";
564 const char interrupt_sequence_break_g[] = "BREAK-g";
565 static const char *interrupt_sequence_modes[] =
567 interrupt_sequence_control_c,
568 interrupt_sequence_break,
569 interrupt_sequence_break_g,
572 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
575 show_interrupt_sequence (struct ui_file *file, int from_tty,
576 struct cmd_list_element *c,
579 if (interrupt_sequence_mode == interrupt_sequence_control_c)
580 fprintf_filtered (file,
581 _("Send the ASCII ETX character (Ctrl-c) "
582 "to the remote target to interrupt the "
583 "execution of the program.\n"));
584 else if (interrupt_sequence_mode == interrupt_sequence_break)
585 fprintf_filtered (file,
586 _("send a break signal to the remote target "
587 "to interrupt the execution of the program.\n"));
588 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
589 fprintf_filtered (file,
590 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
591 "the remote target to interrupt the execution "
592 "of Linux kernel.\n"));
594 internal_error (__FILE__, __LINE__,
595 _("Invalid value for interrupt_sequence_mode: %s."),
596 interrupt_sequence_mode);
599 /* This boolean variable specifies whether interrupt_sequence is sent
600 to the remote target when gdb connects to it.
601 This is mostly needed when you debug the Linux kernel: The Linux kernel
602 expects BREAK g which is Magic SysRq g for connecting gdb. */
603 static int interrupt_on_connect = 0;
605 /* This variable is used to implement the "set/show remotebreak" commands.
606 Since these commands are now deprecated in favor of "set/show remote
607 interrupt-sequence", it no longer has any effect on the code. */
608 static int remote_break;
611 set_remotebreak (char *args, int from_tty, struct cmd_list_element *c)
614 interrupt_sequence_mode = interrupt_sequence_break;
616 interrupt_sequence_mode = interrupt_sequence_control_c;
620 show_remotebreak (struct ui_file *file, int from_tty,
621 struct cmd_list_element *c,
626 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
627 remote_open knows that we don't have a file open when the program
629 static struct serial *remote_desc = NULL;
631 /* This variable sets the number of bits in an address that are to be
632 sent in a memory ("M" or "m") packet. Normally, after stripping
633 leading zeros, the entire address would be sent. This variable
634 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
635 initial implementation of remote.c restricted the address sent in
636 memory packets to ``host::sizeof long'' bytes - (typically 32
637 bits). Consequently, for 64 bit targets, the upper 32 bits of an
638 address was never sent. Since fixing this bug may cause a break in
639 some remote targets this variable is principly provided to
640 facilitate backward compatibility. */
642 static int remote_address_size;
644 /* Temporary to track who currently owns the terminal. See
645 remote_terminal_* for more details. */
647 static int remote_async_terminal_ours_p;
649 /* The executable file to use for "run" on the remote side. */
651 static char *remote_exec_file = "";
654 /* User configurable variables for the number of characters in a
655 memory read/write packet. MIN (rsa->remote_packet_size,
656 rsa->sizeof_g_packet) is the default. Some targets need smaller
657 values (fifo overruns, et.al.) and some users need larger values
658 (speed up transfers). The variables ``preferred_*'' (the user
659 request), ``current_*'' (what was actually set) and ``forced_*''
660 (Positive - a soft limit, negative - a hard limit). */
662 struct memory_packet_config
669 /* Compute the current size of a read/write packet. Since this makes
670 use of ``actual_register_packet_size'' the computation is dynamic. */
673 get_memory_packet_size (struct memory_packet_config *config)
675 struct remote_state *rs = get_remote_state ();
676 struct remote_arch_state *rsa = get_remote_arch_state ();
678 /* NOTE: The somewhat arbitrary 16k comes from the knowledge (folk
679 law?) that some hosts don't cope very well with large alloca()
680 calls. Eventually the alloca() code will be replaced by calls to
681 xmalloc() and make_cleanups() allowing this restriction to either
682 be lifted or removed. */
683 #ifndef MAX_REMOTE_PACKET_SIZE
684 #define MAX_REMOTE_PACKET_SIZE 16384
686 /* NOTE: 20 ensures we can write at least one byte. */
687 #ifndef MIN_REMOTE_PACKET_SIZE
688 #define MIN_REMOTE_PACKET_SIZE 20
693 if (config->size <= 0)
694 what_they_get = MAX_REMOTE_PACKET_SIZE;
696 what_they_get = config->size;
700 what_they_get = get_remote_packet_size ();
701 /* Limit the packet to the size specified by the user. */
703 && what_they_get > config->size)
704 what_they_get = config->size;
706 /* Limit it to the size of the targets ``g'' response unless we have
707 permission from the stub to use a larger packet size. */
708 if (rs->explicit_packet_size == 0
709 && rsa->actual_register_packet_size > 0
710 && what_they_get > rsa->actual_register_packet_size)
711 what_they_get = rsa->actual_register_packet_size;
713 if (what_they_get > MAX_REMOTE_PACKET_SIZE)
714 what_they_get = MAX_REMOTE_PACKET_SIZE;
715 if (what_they_get < MIN_REMOTE_PACKET_SIZE)
716 what_they_get = MIN_REMOTE_PACKET_SIZE;
718 /* Make sure there is room in the global buffer for this packet
719 (including its trailing NUL byte). */
720 if (rs->buf_size < what_they_get + 1)
722 rs->buf_size = 2 * what_they_get;
723 rs->buf = xrealloc (rs->buf, 2 * what_they_get);
726 return what_they_get;
729 /* Update the size of a read/write packet. If they user wants
730 something really big then do a sanity check. */
733 set_memory_packet_size (char *args, struct memory_packet_config *config)
735 int fixed_p = config->fixed_p;
736 long size = config->size;
738 error (_("Argument required (integer, `fixed' or `limited')."));
739 else if (strcmp (args, "hard") == 0
740 || strcmp (args, "fixed") == 0)
742 else if (strcmp (args, "soft") == 0
743 || strcmp (args, "limit") == 0)
748 size = strtoul (args, &end, 0);
750 error (_("Invalid %s (bad syntax)."), config->name);
752 /* Instead of explicitly capping the size of a packet to
753 MAX_REMOTE_PACKET_SIZE or dissallowing it, the user is
754 instead allowed to set the size to something arbitrarily
756 if (size > MAX_REMOTE_PACKET_SIZE)
757 error (_("Invalid %s (too large)."), config->name);
761 if (fixed_p && !config->fixed_p)
763 if (! query (_("The target may not be able to correctly handle a %s\n"
764 "of %ld bytes. Change the packet size? "),
766 error (_("Packet size not changed."));
768 /* Update the config. */
769 config->fixed_p = fixed_p;
774 show_memory_packet_size (struct memory_packet_config *config)
776 printf_filtered (_("The %s is %ld. "), config->name, config->size);
778 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
779 get_memory_packet_size (config));
781 printf_filtered (_("Packets are limited to %ld bytes.\n"),
782 get_memory_packet_size (config));
785 static struct memory_packet_config memory_write_packet_config =
787 "memory-write-packet-size",
791 set_memory_write_packet_size (char *args, int from_tty)
793 set_memory_packet_size (args, &memory_write_packet_config);
797 show_memory_write_packet_size (char *args, int from_tty)
799 show_memory_packet_size (&memory_write_packet_config);
803 get_memory_write_packet_size (void)
805 return get_memory_packet_size (&memory_write_packet_config);
808 static struct memory_packet_config memory_read_packet_config =
810 "memory-read-packet-size",
814 set_memory_read_packet_size (char *args, int from_tty)
816 set_memory_packet_size (args, &memory_read_packet_config);
820 show_memory_read_packet_size (char *args, int from_tty)
822 show_memory_packet_size (&memory_read_packet_config);
826 get_memory_read_packet_size (void)
828 long size = get_memory_packet_size (&memory_read_packet_config);
829 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
830 extra buffer size argument before the memory read size can be
831 increased beyond this. */
832 if (size > get_remote_packet_size ())
833 size = get_remote_packet_size ();
838 /* Generic configuration support for packets the stub optionally
839 supports. Allows the user to specify the use of the packet as well
840 as allowing GDB to auto-detect support in the remote stub. */
844 PACKET_SUPPORT_UNKNOWN = 0,
853 enum auto_boolean detect;
854 enum packet_support support;
857 /* Analyze a packet's return value and update the packet config
868 update_packet_config (struct packet_config *config)
870 switch (config->detect)
872 case AUTO_BOOLEAN_TRUE:
873 config->support = PACKET_ENABLE;
875 case AUTO_BOOLEAN_FALSE:
876 config->support = PACKET_DISABLE;
878 case AUTO_BOOLEAN_AUTO:
879 config->support = PACKET_SUPPORT_UNKNOWN;
885 show_packet_config_cmd (struct packet_config *config)
887 char *support = "internal-error";
888 switch (config->support)
894 support = "disabled";
896 case PACKET_SUPPORT_UNKNOWN:
900 switch (config->detect)
902 case AUTO_BOOLEAN_AUTO:
903 printf_filtered (_("Support for the `%s' packet is auto-detected, currently %s.\n"),
904 config->name, support);
906 case AUTO_BOOLEAN_TRUE:
907 case AUTO_BOOLEAN_FALSE:
908 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
909 config->name, support);
915 add_packet_config_cmd (struct packet_config *config, const char *name,
916 const char *title, int legacy)
923 config->title = title;
924 config->detect = AUTO_BOOLEAN_AUTO;
925 config->support = PACKET_SUPPORT_UNKNOWN;
926 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
928 show_doc = xstrprintf ("Show current use of remote protocol `%s' (%s) packet",
930 /* set/show TITLE-packet {auto,on,off} */
931 cmd_name = xstrprintf ("%s-packet", title);
932 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
933 &config->detect, set_doc, show_doc, NULL, /* help_doc */
934 set_remote_protocol_packet_cmd,
935 show_remote_protocol_packet_cmd,
936 &remote_set_cmdlist, &remote_show_cmdlist);
937 /* The command code copies the documentation strings. */
940 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
944 legacy_name = xstrprintf ("%s-packet", name);
945 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
946 &remote_set_cmdlist);
947 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
948 &remote_show_cmdlist);
952 static enum packet_result
953 packet_check_result (const char *buf)
957 /* The stub recognized the packet request. Check that the
958 operation succeeded. */
960 && isxdigit (buf[1]) && isxdigit (buf[2])
962 /* "Enn" - definitly an error. */
965 /* Always treat "E." as an error. This will be used for
966 more verbose error messages, such as E.memtypes. */
967 if (buf[0] == 'E' && buf[1] == '.')
970 /* The packet may or may not be OK. Just assume it is. */
974 /* The stub does not support the packet. */
975 return PACKET_UNKNOWN;
978 static enum packet_result
979 packet_ok (const char *buf, struct packet_config *config)
981 enum packet_result result;
983 result = packet_check_result (buf);
988 /* The stub recognized the packet request. */
989 switch (config->support)
991 case PACKET_SUPPORT_UNKNOWN:
993 fprintf_unfiltered (gdb_stdlog,
994 "Packet %s (%s) is supported\n",
995 config->name, config->title);
996 config->support = PACKET_ENABLE;
999 internal_error (__FILE__, __LINE__,
1000 _("packet_ok: attempt to use a disabled packet"));
1006 case PACKET_UNKNOWN:
1007 /* The stub does not support the packet. */
1008 switch (config->support)
1011 if (config->detect == AUTO_BOOLEAN_AUTO)
1012 /* If the stub previously indicated that the packet was
1013 supported then there is a protocol error.. */
1014 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1015 config->name, config->title);
1017 /* The user set it wrong. */
1018 error (_("Enabled packet %s (%s) not recognized by stub"),
1019 config->name, config->title);
1021 case PACKET_SUPPORT_UNKNOWN:
1023 fprintf_unfiltered (gdb_stdlog,
1024 "Packet %s (%s) is NOT supported\n",
1025 config->name, config->title);
1026 config->support = PACKET_DISABLE;
1028 case PACKET_DISABLE:
1050 PACKET_vFile_pwrite,
1052 PACKET_vFile_unlink,
1054 PACKET_qXfer_features,
1055 PACKET_qXfer_libraries,
1056 PACKET_qXfer_memory_map,
1057 PACKET_qXfer_spu_read,
1058 PACKET_qXfer_spu_write,
1059 PACKET_qXfer_osdata,
1062 PACKET_QPassSignals,
1063 PACKET_qSearch_memory,
1066 PACKET_QStartNoAckMode,
1068 PACKET_qXfer_siginfo_read,
1069 PACKET_qXfer_siginfo_write,
1071 PACKET_ConditionalTracepoints,
1072 PACKET_FastTracepoints,
1078 static struct packet_config remote_protocol_packets[PACKET_MAX];
1081 set_remote_protocol_packet_cmd (char *args, int from_tty,
1082 struct cmd_list_element *c)
1084 struct packet_config *packet;
1086 for (packet = remote_protocol_packets;
1087 packet < &remote_protocol_packets[PACKET_MAX];
1090 if (&packet->detect == c->var)
1092 update_packet_config (packet);
1096 internal_error (__FILE__, __LINE__, "Could not find config for %s",
1101 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1102 struct cmd_list_element *c,
1105 struct packet_config *packet;
1107 for (packet = remote_protocol_packets;
1108 packet < &remote_protocol_packets[PACKET_MAX];
1111 if (&packet->detect == c->var)
1113 show_packet_config_cmd (packet);
1117 internal_error (__FILE__, __LINE__, "Could not find config for %s",
1121 /* Should we try one of the 'Z' requests? */
1125 Z_PACKET_SOFTWARE_BP,
1126 Z_PACKET_HARDWARE_BP,
1133 /* For compatibility with older distributions. Provide a ``set remote
1134 Z-packet ...'' command that updates all the Z packet types. */
1136 static enum auto_boolean remote_Z_packet_detect;
1139 set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1140 struct cmd_list_element *c)
1143 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1145 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
1146 update_packet_config (&remote_protocol_packets[PACKET_Z0 + i]);
1151 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1152 struct cmd_list_element *c,
1156 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1158 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
1162 /* Should we try the 'ThreadInfo' query packet?
1164 This variable (NOT available to the user: auto-detect only!)
1165 determines whether GDB will use the new, simpler "ThreadInfo"
1166 query or the older, more complex syntax for thread queries.
1167 This is an auto-detect variable (set to true at each connect,
1168 and set to false when the target fails to recognize it). */
1170 static int use_threadinfo_query;
1171 static int use_threadextra_query;
1173 /* Tokens for use by the asynchronous signal handlers for SIGINT. */
1174 static struct async_signal_handler *sigint_remote_twice_token;
1175 static struct async_signal_handler *sigint_remote_token;
1178 /* Asynchronous signal handle registered as event loop source for
1179 when we have pending events ready to be passed to the core. */
1181 static struct async_event_handler *remote_async_inferior_event_token;
1183 /* Asynchronous signal handle registered as event loop source for when
1184 the remote sent us a %Stop notification. The registered callback
1185 will do a vStopped sequence to pull the rest of the events out of
1186 the remote side into our event queue. */
1188 static struct async_event_handler *remote_async_get_pending_events_token;
1191 static ptid_t magic_null_ptid;
1192 static ptid_t not_sent_ptid;
1193 static ptid_t any_thread_ptid;
1195 /* These are the threads which we last sent to the remote system. The
1196 TID member will be -1 for all or -2 for not sent yet. */
1198 static ptid_t general_thread;
1199 static ptid_t continue_thread;
1201 /* Find out if the stub attached to PID (and hence GDB should offer to
1202 detach instead of killing it when bailing out). */
1205 remote_query_attached (int pid)
1207 struct remote_state *rs = get_remote_state ();
1209 if (remote_protocol_packets[PACKET_qAttached].support == PACKET_DISABLE)
1212 if (remote_multi_process_p (rs))
1213 sprintf (rs->buf, "qAttached:%x", pid);
1215 sprintf (rs->buf, "qAttached");
1218 getpkt (&rs->buf, &rs->buf_size, 0);
1220 switch (packet_ok (rs->buf,
1221 &remote_protocol_packets[PACKET_qAttached]))
1224 if (strcmp (rs->buf, "1") == 0)
1228 warning (_("Remote failure reply: %s"), rs->buf);
1230 case PACKET_UNKNOWN:
1237 /* Add PID to GDB's inferior table. Since we can be connected to a
1238 remote system before before knowing about any inferior, mark the
1239 target with execution when we find the first inferior. If ATTACHED
1240 is 1, then we had just attached to this inferior. If it is 0, then
1241 we just created this inferior. If it is -1, then try querying the
1242 remote stub to find out if it had attached to the inferior or
1245 static struct inferior *
1246 remote_add_inferior (int pid, int attached)
1248 struct inferior *inf;
1250 /* Check whether this process we're learning about is to be
1251 considered attached, or if is to be considered to have been
1252 spawned by the stub. */
1254 attached = remote_query_attached (pid);
1256 if (gdbarch_has_global_solist (target_gdbarch))
1258 /* If the target shares code across all inferiors, then every
1259 attach adds a new inferior. */
1260 inf = add_inferior (pid);
1262 /* ... and every inferior is bound to the same program space.
1263 However, each inferior may still have its own address
1265 inf->aspace = maybe_new_address_space ();
1266 inf->pspace = current_program_space;
1270 /* In the traditional debugging scenario, there's a 1-1 match
1271 between program/address spaces. We simply bind the inferior
1272 to the program space's address space. */
1273 inf = current_inferior ();
1274 inferior_appeared (inf, pid);
1277 inf->attach_flag = attached;
1282 /* Add thread PTID to GDB's thread list. Tag it as executing/running
1283 according to RUNNING. */
1286 remote_add_thread (ptid_t ptid, int running)
1290 set_executing (ptid, running);
1291 set_running (ptid, running);
1294 /* Come here when we learn about a thread id from the remote target.
1295 It may be the first time we hear about such thread, so take the
1296 opportunity to add it to GDB's thread list. In case this is the
1297 first time we're noticing its corresponding inferior, add it to
1298 GDB's inferior list as well. */
1301 remote_notice_new_inferior (ptid_t currthread, int running)
1303 /* If this is a new thread, add it to GDB's thread list.
1304 If we leave it up to WFI to do this, bad things will happen. */
1306 if (in_thread_list (currthread) && is_exited (currthread))
1308 /* We're seeing an event on a thread id we knew had exited.
1309 This has to be a new thread reusing the old id. Add it. */
1310 remote_add_thread (currthread, running);
1314 if (!in_thread_list (currthread))
1316 struct inferior *inf = NULL;
1317 int pid = ptid_get_pid (currthread);
1319 if (ptid_is_pid (inferior_ptid)
1320 && pid == ptid_get_pid (inferior_ptid))
1322 /* inferior_ptid has no thread member yet. This can happen
1323 with the vAttach -> remote_wait,"TAAthread:" path if the
1324 stub doesn't support qC. This is the first stop reported
1325 after an attach, so this is the main thread. Update the
1326 ptid in the thread list. */
1327 if (in_thread_list (pid_to_ptid (pid)))
1328 thread_change_ptid (inferior_ptid, currthread);
1331 remote_add_thread (currthread, running);
1332 inferior_ptid = currthread;
1337 if (ptid_equal (magic_null_ptid, inferior_ptid))
1339 /* inferior_ptid is not set yet. This can happen with the
1340 vRun -> remote_wait,"TAAthread:" path if the stub
1341 doesn't support qC. This is the first stop reported
1342 after an attach, so this is the main thread. Update the
1343 ptid in the thread list. */
1344 thread_change_ptid (inferior_ptid, currthread);
1348 /* When connecting to a target remote, or to a target
1349 extended-remote which already was debugging an inferior, we
1350 may not know about it yet. Add it before adding its child
1351 thread, so notifications are emitted in a sensible order. */
1352 if (!in_inferior_list (ptid_get_pid (currthread)))
1353 inf = remote_add_inferior (ptid_get_pid (currthread), -1);
1355 /* This is really a new thread. Add it. */
1356 remote_add_thread (currthread, running);
1358 /* If we found a new inferior, let the common code do whatever
1359 it needs to with it (e.g., read shared libraries, insert
1362 notice_new_inferior (currthread, running, 0);
1366 /* Call this function as a result of
1367 1) A halt indication (T packet) containing a thread id
1368 2) A direct query of currthread
1369 3) Successful execution of set thread
1373 record_currthread (ptid_t currthread)
1375 general_thread = currthread;
1377 if (ptid_equal (currthread, minus_one_ptid))
1378 /* We're just invalidating the local thread mirror. */
1381 remote_notice_new_inferior (currthread, 0);
1384 static char *last_pass_packet;
1386 /* If 'QPassSignals' is supported, tell the remote stub what signals
1387 it can simply pass through to the inferior without reporting. */
1390 remote_pass_signals (void)
1392 if (remote_protocol_packets[PACKET_QPassSignals].support != PACKET_DISABLE)
1394 char *pass_packet, *p;
1395 int numsigs = (int) TARGET_SIGNAL_LAST;
1398 gdb_assert (numsigs < 256);
1399 for (i = 0; i < numsigs; i++)
1401 if (signal_stop_state (i) == 0
1402 && signal_print_state (i) == 0
1403 && signal_pass_state (i) == 1)
1406 pass_packet = xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
1407 strcpy (pass_packet, "QPassSignals:");
1408 p = pass_packet + strlen (pass_packet);
1409 for (i = 0; i < numsigs; i++)
1411 if (signal_stop_state (i) == 0
1412 && signal_print_state (i) == 0
1413 && signal_pass_state (i) == 1)
1416 *p++ = tohex (i >> 4);
1417 *p++ = tohex (i & 15);
1426 if (!last_pass_packet || strcmp (last_pass_packet, pass_packet))
1428 struct remote_state *rs = get_remote_state ();
1429 char *buf = rs->buf;
1431 putpkt (pass_packet);
1432 getpkt (&rs->buf, &rs->buf_size, 0);
1433 packet_ok (buf, &remote_protocol_packets[PACKET_QPassSignals]);
1434 if (last_pass_packet)
1435 xfree (last_pass_packet);
1436 last_pass_packet = pass_packet;
1439 xfree (pass_packet);
1443 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
1444 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
1445 thread. If GEN is set, set the general thread, if not, then set
1446 the step/continue thread. */
1448 set_thread (struct ptid ptid, int gen)
1450 struct remote_state *rs = get_remote_state ();
1451 ptid_t state = gen ? general_thread : continue_thread;
1452 char *buf = rs->buf;
1453 char *endbuf = rs->buf + get_remote_packet_size ();
1455 if (ptid_equal (state, ptid))
1459 *buf++ = gen ? 'g' : 'c';
1460 if (ptid_equal (ptid, magic_null_ptid))
1461 xsnprintf (buf, endbuf - buf, "0");
1462 else if (ptid_equal (ptid, any_thread_ptid))
1463 xsnprintf (buf, endbuf - buf, "0");
1464 else if (ptid_equal (ptid, minus_one_ptid))
1465 xsnprintf (buf, endbuf - buf, "-1");
1467 write_ptid (buf, endbuf, ptid);
1469 getpkt (&rs->buf, &rs->buf_size, 0);
1471 general_thread = ptid;
1473 continue_thread = ptid;
1477 set_general_thread (struct ptid ptid)
1479 set_thread (ptid, 1);
1483 set_continue_thread (struct ptid ptid)
1485 set_thread (ptid, 0);
1488 /* Change the remote current process. Which thread within the process
1489 ends up selected isn't important, as long as it is the same process
1490 as what INFERIOR_PTID points to.
1492 This comes from that fact that there is no explicit notion of
1493 "selected process" in the protocol. The selected process for
1494 general operations is the process the selected general thread
1498 set_general_process (void)
1500 struct remote_state *rs = get_remote_state ();
1502 /* If the remote can't handle multiple processes, don't bother. */
1503 if (!remote_multi_process_p (rs))
1506 /* We only need to change the remote current thread if it's pointing
1507 at some other process. */
1508 if (ptid_get_pid (general_thread) != ptid_get_pid (inferior_ptid))
1509 set_general_thread (inferior_ptid);
1513 /* Return nonzero if the thread PTID is still alive on the remote
1517 remote_thread_alive (struct target_ops *ops, ptid_t ptid)
1519 struct remote_state *rs = get_remote_state ();
1522 if (ptid_equal (ptid, magic_null_ptid))
1523 /* The main thread is always alive. */
1526 if (ptid_get_pid (ptid) != 0 && ptid_get_tid (ptid) == 0)
1527 /* The main thread is always alive. This can happen after a
1528 vAttach, if the remote side doesn't support
1533 endp = rs->buf + get_remote_packet_size ();
1536 write_ptid (p, endp, ptid);
1539 getpkt (&rs->buf, &rs->buf_size, 0);
1540 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
1543 /* About these extended threadlist and threadinfo packets. They are
1544 variable length packets but, the fields within them are often fixed
1545 length. They are redundent enough to send over UDP as is the
1546 remote protocol in general. There is a matching unit test module
1549 #define OPAQUETHREADBYTES 8
1551 /* a 64 bit opaque identifier */
1552 typedef unsigned char threadref[OPAQUETHREADBYTES];
1554 /* WARNING: This threadref data structure comes from the remote O.S.,
1555 libstub protocol encoding, and remote.c. it is not particularly
1558 /* Right now, the internal structure is int. We want it to be bigger.
1562 typedef int gdb_threadref; /* Internal GDB thread reference. */
1564 /* gdb_ext_thread_info is an internal GDB data structure which is
1565 equivalent to the reply of the remote threadinfo packet. */
1567 struct gdb_ext_thread_info
1569 threadref threadid; /* External form of thread reference. */
1570 int active; /* Has state interesting to GDB?
1572 char display[256]; /* Brief state display, name,
1573 blocked/suspended. */
1574 char shortname[32]; /* To be used to name threads. */
1575 char more_display[256]; /* Long info, statistics, queue depth,
1579 /* The volume of remote transfers can be limited by submitting
1580 a mask containing bits specifying the desired information.
1581 Use a union of these values as the 'selection' parameter to
1582 get_thread_info. FIXME: Make these TAG names more thread specific.
1585 #define TAG_THREADID 1
1586 #define TAG_EXISTS 2
1587 #define TAG_DISPLAY 4
1588 #define TAG_THREADNAME 8
1589 #define TAG_MOREDISPLAY 16
1591 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
1593 char *unpack_varlen_hex (char *buff, ULONGEST *result);
1595 static char *unpack_nibble (char *buf, int *val);
1597 static char *pack_nibble (char *buf, int nibble);
1599 static char *pack_hex_byte (char *pkt, int /* unsigned char */ byte);
1601 static char *unpack_byte (char *buf, int *value);
1603 static char *pack_int (char *buf, int value);
1605 static char *unpack_int (char *buf, int *value);
1607 static char *unpack_string (char *src, char *dest, int length);
1609 static char *pack_threadid (char *pkt, threadref *id);
1611 static char *unpack_threadid (char *inbuf, threadref *id);
1613 void int_to_threadref (threadref *id, int value);
1615 static int threadref_to_int (threadref *ref);
1617 static void copy_threadref (threadref *dest, threadref *src);
1619 static int threadmatch (threadref *dest, threadref *src);
1621 static char *pack_threadinfo_request (char *pkt, int mode,
1624 static int remote_unpack_thread_info_response (char *pkt,
1625 threadref *expectedref,
1626 struct gdb_ext_thread_info
1630 static int remote_get_threadinfo (threadref *threadid,
1631 int fieldset, /*TAG mask */
1632 struct gdb_ext_thread_info *info);
1634 static char *pack_threadlist_request (char *pkt, int startflag,
1636 threadref *nextthread);
1638 static int parse_threadlist_response (char *pkt,
1640 threadref *original_echo,
1641 threadref *resultlist,
1644 static int remote_get_threadlist (int startflag,
1645 threadref *nextthread,
1649 threadref *threadlist);
1651 typedef int (*rmt_thread_action) (threadref *ref, void *context);
1653 static int remote_threadlist_iterator (rmt_thread_action stepfunction,
1654 void *context, int looplimit);
1656 static int remote_newthread_step (threadref *ref, void *context);
1659 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
1660 buffer we're allowed to write to. Returns
1661 BUF+CHARACTERS_WRITTEN. */
1664 write_ptid (char *buf, const char *endbuf, ptid_t ptid)
1667 struct remote_state *rs = get_remote_state ();
1669 if (remote_multi_process_p (rs))
1671 pid = ptid_get_pid (ptid);
1673 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
1675 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
1677 tid = ptid_get_tid (ptid);
1679 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
1681 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
1686 /* Extract a PTID from BUF. If non-null, OBUF is set to the to one
1687 passed the last parsed char. Returns null_ptid on error. */
1690 read_ptid (char *buf, char **obuf)
1694 ULONGEST pid = 0, tid = 0;
1698 /* Multi-process ptid. */
1699 pp = unpack_varlen_hex (p + 1, &pid);
1701 error (_("invalid remote ptid: %s\n"), p);
1704 pp = unpack_varlen_hex (p + 1, &tid);
1707 return ptid_build (pid, 0, tid);
1710 /* No multi-process. Just a tid. */
1711 pp = unpack_varlen_hex (p, &tid);
1713 /* Since the stub is not sending a process id, then default to
1714 what's in inferior_ptid, unless it's null at this point. If so,
1715 then since there's no way to know the pid of the reported
1716 threads, use the magic number. */
1717 if (ptid_equal (inferior_ptid, null_ptid))
1718 pid = ptid_get_pid (magic_null_ptid);
1720 pid = ptid_get_pid (inferior_ptid);
1724 return ptid_build (pid, 0, tid);
1727 /* Encode 64 bits in 16 chars of hex. */
1729 static const char hexchars[] = "0123456789abcdef";
1732 ishex (int ch, int *val)
1734 if ((ch >= 'a') && (ch <= 'f'))
1736 *val = ch - 'a' + 10;
1739 if ((ch >= 'A') && (ch <= 'F'))
1741 *val = ch - 'A' + 10;
1744 if ((ch >= '0') && (ch <= '9'))
1755 if (ch >= 'a' && ch <= 'f')
1756 return ch - 'a' + 10;
1757 if (ch >= '0' && ch <= '9')
1759 if (ch >= 'A' && ch <= 'F')
1760 return ch - 'A' + 10;
1765 stub_unpack_int (char *buff, int fieldlength)
1772 nibble = stubhex (*buff++);
1776 retval = retval << 4;
1782 unpack_varlen_hex (char *buff, /* packet to parse */
1786 ULONGEST retval = 0;
1788 while (ishex (*buff, &nibble))
1791 retval = retval << 4;
1792 retval |= nibble & 0x0f;
1799 unpack_nibble (char *buf, int *val)
1801 *val = fromhex (*buf++);
1806 pack_nibble (char *buf, int nibble)
1808 *buf++ = hexchars[(nibble & 0x0f)];
1813 pack_hex_byte (char *pkt, int byte)
1815 *pkt++ = hexchars[(byte >> 4) & 0xf];
1816 *pkt++ = hexchars[(byte & 0xf)];
1821 unpack_byte (char *buf, int *value)
1823 *value = stub_unpack_int (buf, 2);
1828 pack_int (char *buf, int value)
1830 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
1831 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
1832 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
1833 buf = pack_hex_byte (buf, (value & 0xff));
1838 unpack_int (char *buf, int *value)
1840 *value = stub_unpack_int (buf, 8);
1844 #if 0 /* Currently unused, uncomment when needed. */
1845 static char *pack_string (char *pkt, char *string);
1848 pack_string (char *pkt, char *string)
1853 len = strlen (string);
1855 len = 200; /* Bigger than most GDB packets, junk??? */
1856 pkt = pack_hex_byte (pkt, len);
1860 if ((ch == '\0') || (ch == '#'))
1861 ch = '*'; /* Protect encapsulation. */
1866 #endif /* 0 (unused) */
1869 unpack_string (char *src, char *dest, int length)
1878 pack_threadid (char *pkt, threadref *id)
1881 unsigned char *altid;
1883 altid = (unsigned char *) id;
1884 limit = pkt + BUF_THREAD_ID_SIZE;
1886 pkt = pack_hex_byte (pkt, *altid++);
1892 unpack_threadid (char *inbuf, threadref *id)
1895 char *limit = inbuf + BUF_THREAD_ID_SIZE;
1898 altref = (char *) id;
1900 while (inbuf < limit)
1902 x = stubhex (*inbuf++);
1903 y = stubhex (*inbuf++);
1904 *altref++ = (x << 4) | y;
1909 /* Externally, threadrefs are 64 bits but internally, they are still
1910 ints. This is due to a mismatch of specifications. We would like
1911 to use 64bit thread references internally. This is an adapter
1915 int_to_threadref (threadref *id, int value)
1917 unsigned char *scan;
1919 scan = (unsigned char *) id;
1925 *scan++ = (value >> 24) & 0xff;
1926 *scan++ = (value >> 16) & 0xff;
1927 *scan++ = (value >> 8) & 0xff;
1928 *scan++ = (value & 0xff);
1932 threadref_to_int (threadref *ref)
1935 unsigned char *scan;
1941 value = (value << 8) | ((*scan++) & 0xff);
1946 copy_threadref (threadref *dest, threadref *src)
1949 unsigned char *csrc, *cdest;
1951 csrc = (unsigned char *) src;
1952 cdest = (unsigned char *) dest;
1959 threadmatch (threadref *dest, threadref *src)
1961 /* Things are broken right now, so just assume we got a match. */
1963 unsigned char *srcp, *destp;
1965 srcp = (char *) src;
1966 destp = (char *) dest;
1970 result &= (*srcp++ == *destp++) ? 1 : 0;
1977 threadid:1, # always request threadid
1984 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
1987 pack_threadinfo_request (char *pkt, int mode, threadref *id)
1989 *pkt++ = 'q'; /* Info Query */
1990 *pkt++ = 'P'; /* process or thread info */
1991 pkt = pack_int (pkt, mode); /* mode */
1992 pkt = pack_threadid (pkt, id); /* threadid */
1993 *pkt = '\0'; /* terminate */
1997 /* These values tag the fields in a thread info response packet. */
1998 /* Tagging the fields allows us to request specific fields and to
1999 add more fields as time goes by. */
2001 #define TAG_THREADID 1 /* Echo the thread identifier. */
2002 #define TAG_EXISTS 2 /* Is this process defined enough to
2003 fetch registers and its stack? */
2004 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
2005 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
2006 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
2010 remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2011 struct gdb_ext_thread_info *info)
2013 struct remote_state *rs = get_remote_state ();
2017 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
2020 /* info->threadid = 0; FIXME: implement zero_threadref. */
2022 info->display[0] = '\0';
2023 info->shortname[0] = '\0';
2024 info->more_display[0] = '\0';
2026 /* Assume the characters indicating the packet type have been
2028 pkt = unpack_int (pkt, &mask); /* arg mask */
2029 pkt = unpack_threadid (pkt, &ref);
2032 warning (_("Incomplete response to threadinfo request."));
2033 if (!threadmatch (&ref, expectedref))
2034 { /* This is an answer to a different request. */
2035 warning (_("ERROR RMT Thread info mismatch."));
2038 copy_threadref (&info->threadid, &ref);
2040 /* Loop on tagged fields , try to bail if somthing goes wrong. */
2042 /* Packets are terminated with nulls. */
2043 while ((pkt < limit) && mask && *pkt)
2045 pkt = unpack_int (pkt, &tag); /* tag */
2046 pkt = unpack_byte (pkt, &length); /* length */
2047 if (!(tag & mask)) /* Tags out of synch with mask. */
2049 warning (_("ERROR RMT: threadinfo tag mismatch."));
2053 if (tag == TAG_THREADID)
2057 warning (_("ERROR RMT: length of threadid is not 16."));
2061 pkt = unpack_threadid (pkt, &ref);
2062 mask = mask & ~TAG_THREADID;
2065 if (tag == TAG_EXISTS)
2067 info->active = stub_unpack_int (pkt, length);
2069 mask = mask & ~(TAG_EXISTS);
2072 warning (_("ERROR RMT: 'exists' length too long."));
2078 if (tag == TAG_THREADNAME)
2080 pkt = unpack_string (pkt, &info->shortname[0], length);
2081 mask = mask & ~TAG_THREADNAME;
2084 if (tag == TAG_DISPLAY)
2086 pkt = unpack_string (pkt, &info->display[0], length);
2087 mask = mask & ~TAG_DISPLAY;
2090 if (tag == TAG_MOREDISPLAY)
2092 pkt = unpack_string (pkt, &info->more_display[0], length);
2093 mask = mask & ~TAG_MOREDISPLAY;
2096 warning (_("ERROR RMT: unknown thread info tag."));
2097 break; /* Not a tag we know about. */
2103 remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
2104 struct gdb_ext_thread_info *info)
2106 struct remote_state *rs = get_remote_state ();
2109 pack_threadinfo_request (rs->buf, fieldset, threadid);
2111 getpkt (&rs->buf, &rs->buf_size, 0);
2113 if (rs->buf[0] == '\0')
2116 result = remote_unpack_thread_info_response (rs->buf + 2,
2121 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
2124 pack_threadlist_request (char *pkt, int startflag, int threadcount,
2125 threadref *nextthread)
2127 *pkt++ = 'q'; /* info query packet */
2128 *pkt++ = 'L'; /* Process LIST or threadLIST request */
2129 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
2130 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
2131 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
2136 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2139 parse_threadlist_response (char *pkt, int result_limit,
2140 threadref *original_echo, threadref *resultlist,
2143 struct remote_state *rs = get_remote_state ();
2145 int count, resultcount, done;
2148 /* Assume the 'q' and 'M chars have been stripped. */
2149 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
2150 /* done parse past here */
2151 pkt = unpack_byte (pkt, &count); /* count field */
2152 pkt = unpack_nibble (pkt, &done);
2153 /* The first threadid is the argument threadid. */
2154 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
2155 while ((count-- > 0) && (pkt < limit))
2157 pkt = unpack_threadid (pkt, resultlist++);
2158 if (resultcount++ >= result_limit)
2167 remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2168 int *done, int *result_count, threadref *threadlist)
2170 struct remote_state *rs = get_remote_state ();
2171 static threadref echo_nextthread;
2174 /* Trancate result limit to be smaller than the packet size. */
2175 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10) >= get_remote_packet_size ())
2176 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
2178 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2180 getpkt (&rs->buf, &rs->buf_size, 0);
2182 if (*rs->buf == '\0')
2186 parse_threadlist_response (rs->buf + 2, result_limit, &echo_nextthread,
2189 if (!threadmatch (&echo_nextthread, nextthread))
2191 /* FIXME: This is a good reason to drop the packet. */
2192 /* Possably, there is a duplicate response. */
2194 retransmit immediatly - race conditions
2195 retransmit after timeout - yes
2197 wait for packet, then exit
2199 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
2200 return 0; /* I choose simply exiting. */
2202 if (*result_count <= 0)
2206 warning (_("RMT ERROR : failed to get remote thread list."));
2209 return result; /* break; */
2211 if (*result_count > result_limit)
2214 warning (_("RMT ERROR: threadlist response longer than requested."));
2220 /* This is the interface between remote and threads, remotes upper
2223 /* remote_find_new_threads retrieves the thread list and for each
2224 thread in the list, looks up the thread in GDB's internal list,
2225 adding the thread if it does not already exist. This involves
2226 getting partial thread lists from the remote target so, polling the
2227 quit_flag is required. */
2230 /* About this many threadisds fit in a packet. */
2232 #define MAXTHREADLISTRESULTS 32
2235 remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2238 int done, i, result_count;
2242 static threadref nextthread;
2243 static threadref resultthreadlist[MAXTHREADLISTRESULTS];
2248 if (loopcount++ > looplimit)
2251 warning (_("Remote fetch threadlist -infinite loop-."));
2254 if (!remote_get_threadlist (startflag, &nextthread, MAXTHREADLISTRESULTS,
2255 &done, &result_count, resultthreadlist))
2260 /* Clear for later iterations. */
2262 /* Setup to resume next batch of thread references, set nextthread. */
2263 if (result_count >= 1)
2264 copy_threadref (&nextthread, &resultthreadlist[result_count - 1]);
2266 while (result_count--)
2267 if (!(result = (*stepfunction) (&resultthreadlist[i++], context)))
2274 remote_newthread_step (threadref *ref, void *context)
2276 int pid = ptid_get_pid (inferior_ptid);
2277 ptid_t ptid = ptid_build (pid, 0, threadref_to_int (ref));
2279 if (!in_thread_list (ptid))
2281 return 1; /* continue iterator */
2284 #define CRAZY_MAX_THREADS 1000
2287 remote_current_thread (ptid_t oldpid)
2289 struct remote_state *rs = get_remote_state ();
2292 getpkt (&rs->buf, &rs->buf_size, 0);
2293 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
2294 return read_ptid (&rs->buf[2], NULL);
2299 /* Find new threads for info threads command.
2300 * Original version, using John Metzler's thread protocol.
2304 remote_find_new_threads (void)
2306 remote_threadlist_iterator (remote_newthread_step, 0,
2311 * Find all threads for info threads command.
2312 * Uses new thread protocol contributed by Cisco.
2313 * Falls back and attempts to use the older method (above)
2314 * if the target doesn't respond to the new method.
2318 remote_threads_info (struct target_ops *ops)
2320 struct remote_state *rs = get_remote_state ();
2324 if (remote_desc == 0) /* paranoia */
2325 error (_("Command can only be used when connected to the remote target."));
2327 if (use_threadinfo_query)
2329 putpkt ("qfThreadInfo");
2330 getpkt (&rs->buf, &rs->buf_size, 0);
2332 if (bufp[0] != '\0') /* q packet recognized */
2334 while (*bufp++ == 'm') /* reply contains one or more TID */
2338 new_thread = read_ptid (bufp, &bufp);
2339 if (!ptid_equal (new_thread, null_ptid))
2341 /* In non-stop mode, we assume new found threads
2342 are running until proven otherwise with a
2343 stop reply. In all-stop, we can only get
2344 here if all threads are stopped. */
2345 int running = non_stop ? 1 : 0;
2347 remote_notice_new_inferior (new_thread, running);
2350 while (*bufp++ == ','); /* comma-separated list */
2351 putpkt ("qsThreadInfo");
2352 getpkt (&rs->buf, &rs->buf_size, 0);
2359 /* Only qfThreadInfo is supported in non-stop mode. */
2363 /* Else fall back to old method based on jmetzler protocol. */
2364 use_threadinfo_query = 0;
2365 remote_find_new_threads ();
2370 * Collect a descriptive string about the given thread.
2371 * The target may say anything it wants to about the thread
2372 * (typically info about its blocked / runnable state, name, etc.).
2373 * This string will appear in the info threads display.
2375 * Optional: targets are not required to implement this function.
2379 remote_threads_extra_info (struct thread_info *tp)
2381 struct remote_state *rs = get_remote_state ();
2385 struct gdb_ext_thread_info threadinfo;
2386 static char display_buf[100]; /* arbitrary... */
2387 int n = 0; /* position in display_buf */
2389 if (remote_desc == 0) /* paranoia */
2390 internal_error (__FILE__, __LINE__,
2391 _("remote_threads_extra_info"));
2393 if (ptid_equal (tp->ptid, magic_null_ptid)
2394 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_tid (tp->ptid) == 0))
2395 /* This is the main thread which was added by GDB. The remote
2396 server doesn't know about it. */
2399 if (use_threadextra_query)
2402 char *endb = rs->buf + get_remote_packet_size ();
2404 xsnprintf (b, endb - b, "qThreadExtraInfo,");
2406 write_ptid (b, endb, tp->ptid);
2409 getpkt (&rs->buf, &rs->buf_size, 0);
2410 if (rs->buf[0] != 0)
2412 n = min (strlen (rs->buf) / 2, sizeof (display_buf));
2413 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
2414 display_buf [result] = '\0';
2419 /* If the above query fails, fall back to the old method. */
2420 use_threadextra_query = 0;
2421 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
2422 | TAG_MOREDISPLAY | TAG_DISPLAY;
2423 int_to_threadref (&id, ptid_get_tid (tp->ptid));
2424 if (remote_get_threadinfo (&id, set, &threadinfo))
2425 if (threadinfo.active)
2427 if (*threadinfo.shortname)
2428 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
2429 " Name: %s,", threadinfo.shortname);
2430 if (*threadinfo.display)
2431 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
2432 " State: %s,", threadinfo.display);
2433 if (*threadinfo.more_display)
2434 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
2435 " Priority: %s", threadinfo.more_display);
2439 /* For purely cosmetic reasons, clear up trailing commas. */
2440 if (',' == display_buf[n-1])
2441 display_buf[n-1] = ' ';
2449 /* Restart the remote side; this is an extended protocol operation. */
2452 extended_remote_restart (void)
2454 struct remote_state *rs = get_remote_state ();
2456 /* Send the restart command; for reasons I don't understand the
2457 remote side really expects a number after the "R". */
2458 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
2461 remote_fileio_reset ();
2464 /* Clean up connection to a remote debugger. */
2467 remote_close (int quitting)
2469 if (remote_desc == NULL)
2470 return; /* already closed */
2472 /* Make sure we leave stdin registered in the event loop, and we
2473 don't leave the async SIGINT signal handler installed. */
2474 remote_terminal_ours ();
2476 serial_close (remote_desc);
2479 /* We don't have a connection to the remote stub anymore. Get rid
2480 of all the inferiors and their threads we were controlling. */
2481 discard_all_inferiors ();
2483 /* We're no longer interested in any of these events. */
2484 discard_pending_stop_replies (-1);
2486 if (remote_async_inferior_event_token)
2487 delete_async_event_handler (&remote_async_inferior_event_token);
2488 if (remote_async_get_pending_events_token)
2489 delete_async_event_handler (&remote_async_get_pending_events_token);
2492 /* Query the remote side for the text, data and bss offsets. */
2497 struct remote_state *rs = get_remote_state ();
2500 int lose, num_segments = 0, do_sections, do_segments;
2501 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
2502 struct section_offsets *offs;
2503 struct symfile_segment_data *data;
2505 if (symfile_objfile == NULL)
2508 putpkt ("qOffsets");
2509 getpkt (&rs->buf, &rs->buf_size, 0);
2512 if (buf[0] == '\000')
2513 return; /* Return silently. Stub doesn't support
2517 warning (_("Remote failure reply: %s"), buf);
2521 /* Pick up each field in turn. This used to be done with scanf, but
2522 scanf will make trouble if CORE_ADDR size doesn't match
2523 conversion directives correctly. The following code will work
2524 with any size of CORE_ADDR. */
2525 text_addr = data_addr = bss_addr = 0;
2529 if (strncmp (ptr, "Text=", 5) == 0)
2532 /* Don't use strtol, could lose on big values. */
2533 while (*ptr && *ptr != ';')
2534 text_addr = (text_addr << 4) + fromhex (*ptr++);
2536 if (strncmp (ptr, ";Data=", 6) == 0)
2539 while (*ptr && *ptr != ';')
2540 data_addr = (data_addr << 4) + fromhex (*ptr++);
2545 if (!lose && strncmp (ptr, ";Bss=", 5) == 0)
2548 while (*ptr && *ptr != ';')
2549 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
2551 if (bss_addr != data_addr)
2552 warning (_("Target reported unsupported offsets: %s"), buf);
2557 else if (strncmp (ptr, "TextSeg=", 8) == 0)
2560 /* Don't use strtol, could lose on big values. */
2561 while (*ptr && *ptr != ';')
2562 text_addr = (text_addr << 4) + fromhex (*ptr++);
2565 if (strncmp (ptr, ";DataSeg=", 9) == 0)
2568 while (*ptr && *ptr != ';')
2569 data_addr = (data_addr << 4) + fromhex (*ptr++);
2577 error (_("Malformed response to offset query, %s"), buf);
2578 else if (*ptr != '\0')
2579 warning (_("Target reported unsupported offsets: %s"), buf);
2581 offs = ((struct section_offsets *)
2582 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
2583 memcpy (offs, symfile_objfile->section_offsets,
2584 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
2586 data = get_symfile_segment_data (symfile_objfile->obfd);
2587 do_segments = (data != NULL);
2588 do_sections = num_segments == 0;
2590 if (num_segments > 0)
2592 segments[0] = text_addr;
2593 segments[1] = data_addr;
2595 /* If we have two segments, we can still try to relocate everything
2596 by assuming that the .text and .data offsets apply to the whole
2597 text and data segments. Convert the offsets given in the packet
2598 to base addresses for symfile_map_offsets_to_segments. */
2599 else if (data && data->num_segments == 2)
2601 segments[0] = data->segment_bases[0] + text_addr;
2602 segments[1] = data->segment_bases[1] + data_addr;
2605 /* If the object file has only one segment, assume that it is text
2606 rather than data; main programs with no writable data are rare,
2607 but programs with no code are useless. Of course the code might
2608 have ended up in the data segment... to detect that we would need
2609 the permissions here. */
2610 else if (data && data->num_segments == 1)
2612 segments[0] = data->segment_bases[0] + text_addr;
2615 /* There's no way to relocate by segment. */
2621 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
2622 offs, num_segments, segments);
2624 if (ret == 0 && !do_sections)
2625 error (_("Can not handle qOffsets TextSeg response with this symbol file"));
2632 free_symfile_segment_data (data);
2636 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
2638 /* This is a temporary kludge to force data and bss to use the same offsets
2639 because that's what nlmconv does now. The real solution requires changes
2640 to the stub and remote.c that I don't have time to do right now. */
2642 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
2643 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
2646 objfile_relocate (symfile_objfile, offs);
2649 /* Callback for iterate_over_threads. Set the STOP_REQUESTED flags in
2650 threads we know are stopped already. This is used during the
2651 initial remote connection in non-stop mode --- threads that are
2652 reported as already being stopped are left stopped. */
2655 set_stop_requested_callback (struct thread_info *thread, void *data)
2657 /* If we have a stop reply for this thread, it must be stopped. */
2658 if (peek_stop_reply (thread->ptid))
2659 set_stop_requested (thread->ptid, 1);
2664 /* Stub for catch_exception. */
2666 struct start_remote_args
2670 /* The current target. */
2671 struct target_ops *target;
2673 /* Non-zero if this is an extended-remote target. */
2677 /* Send interrupt_sequence to remote target. */
2679 send_interrupt_sequence ()
2681 if (interrupt_sequence_mode == interrupt_sequence_control_c)
2682 serial_write (remote_desc, "\x03", 1);
2683 else if (interrupt_sequence_mode == interrupt_sequence_break)
2684 serial_send_break (remote_desc);
2685 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
2687 serial_send_break (remote_desc);
2688 serial_write (remote_desc, "g", 1);
2691 internal_error (__FILE__, __LINE__,
2692 _("Invalid value for interrupt_sequence_mode: %s."),
2693 interrupt_sequence_mode);
2697 remote_start_remote (struct ui_out *uiout, void *opaque)
2699 struct start_remote_args *args = opaque;
2700 struct remote_state *rs = get_remote_state ();
2701 struct packet_config *noack_config;
2702 char *wait_status = NULL;
2704 immediate_quit++; /* Allow user to interrupt it. */
2706 /* Ack any packet which the remote side has already sent. */
2707 serial_write (remote_desc, "+", 1);
2709 if (interrupt_on_connect)
2710 send_interrupt_sequence ();
2712 /* The first packet we send to the target is the optional "supported
2713 packets" request. If the target can answer this, it will tell us
2714 which later probes to skip. */
2715 remote_query_supported ();
2717 /* Next, we possibly activate noack mode.
2719 If the QStartNoAckMode packet configuration is set to AUTO,
2720 enable noack mode if the stub reported a wish for it with
2723 If set to TRUE, then enable noack mode even if the stub didn't
2724 report it in qSupported. If the stub doesn't reply OK, the
2725 session ends with an error.
2727 If FALSE, then don't activate noack mode, regardless of what the
2728 stub claimed should be the default with qSupported. */
2730 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
2732 if (noack_config->detect == AUTO_BOOLEAN_TRUE
2733 || (noack_config->detect == AUTO_BOOLEAN_AUTO
2734 && noack_config->support == PACKET_ENABLE))
2736 putpkt ("QStartNoAckMode");
2737 getpkt (&rs->buf, &rs->buf_size, 0);
2738 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
2742 if (args->extended_p)
2744 /* Tell the remote that we are using the extended protocol. */
2746 getpkt (&rs->buf, &rs->buf_size, 0);
2749 /* Next, if the target can specify a description, read it. We do
2750 this before anything involving memory or registers. */
2751 target_find_description ();
2753 /* Next, now that we know something about the target, update the
2754 address spaces in the program spaces. */
2755 update_address_spaces ();
2757 /* On OSs where the list of libraries is global to all
2758 processes, we fetch them early. */
2759 if (gdbarch_has_global_solist (target_gdbarch))
2760 solib_add (NULL, args->from_tty, args->target, auto_solib_add);
2764 if (!rs->non_stop_aware)
2765 error (_("Non-stop mode requested, but remote does not support non-stop"));
2767 putpkt ("QNonStop:1");
2768 getpkt (&rs->buf, &rs->buf_size, 0);
2770 if (strcmp (rs->buf, "OK") != 0)
2771 error ("Remote refused setting non-stop mode with: %s", rs->buf);
2773 /* Find about threads and processes the stub is already
2774 controlling. We default to adding them in the running state.
2775 The '?' query below will then tell us about which threads are
2777 remote_threads_info (args->target);
2779 else if (rs->non_stop_aware)
2781 /* Don't assume that the stub can operate in all-stop mode.
2782 Request it explicitely. */
2783 putpkt ("QNonStop:0");
2784 getpkt (&rs->buf, &rs->buf_size, 0);
2786 if (strcmp (rs->buf, "OK") != 0)
2787 error ("Remote refused setting all-stop mode with: %s", rs->buf);
2790 /* Check whether the target is running now. */
2792 getpkt (&rs->buf, &rs->buf_size, 0);
2796 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
2798 if (!args->extended_p)
2799 error (_("The target is not running (try extended-remote?)"));
2801 /* We're connected, but not running. Drop out before we
2802 call start_remote. */
2807 /* Save the reply for later. */
2808 wait_status = alloca (strlen (rs->buf) + 1);
2809 strcpy (wait_status, rs->buf);
2812 /* Let the stub know that we want it to return the thread. */
2813 set_continue_thread (minus_one_ptid);
2815 /* Without this, some commands which require an active target
2816 (such as kill) won't work. This variable serves (at least)
2817 double duty as both the pid of the target process (if it has
2818 such), and as a flag indicating that a target is active.
2819 These functions should be split out into seperate variables,
2820 especially since GDB will someday have a notion of debugging
2821 several processes. */
2822 inferior_ptid = magic_null_ptid;
2824 /* Now, if we have thread information, update inferior_ptid. */
2825 inferior_ptid = remote_current_thread (inferior_ptid);
2827 remote_add_inferior (ptid_get_pid (inferior_ptid), -1);
2829 /* Always add the main thread. */
2830 add_thread_silent (inferior_ptid);
2832 get_offsets (); /* Get text, data & bss offsets. */
2834 /* If we could not find a description using qXfer, and we know
2835 how to do it some other way, try again. This is not
2836 supported for non-stop; it could be, but it is tricky if
2837 there are no stopped threads when we connect. */
2838 if (remote_read_description_p (args->target)
2839 && gdbarch_target_desc (target_gdbarch) == NULL)
2841 target_clear_description ();
2842 target_find_description ();
2845 /* Use the previously fetched status. */
2846 gdb_assert (wait_status != NULL);
2847 strcpy (rs->buf, wait_status);
2848 rs->cached_wait_status = 1;
2851 start_remote (args->from_tty); /* Initialize gdb process mechanisms. */
2855 /* Clear WFI global state. Do this before finding about new
2856 threads and inferiors, and setting the current inferior.
2857 Otherwise we would clear the proceed status of the current
2858 inferior when we want its stop_soon state to be preserved
2859 (see notice_new_inferior). */
2860 init_wait_for_inferior ();
2862 /* In non-stop, we will either get an "OK", meaning that there
2863 are no stopped threads at this time; or, a regular stop
2864 reply. In the latter case, there may be more than one thread
2865 stopped --- we pull them all out using the vStopped
2867 if (strcmp (rs->buf, "OK") != 0)
2869 struct stop_reply *stop_reply;
2870 struct cleanup *old_chain;
2872 stop_reply = stop_reply_xmalloc ();
2873 old_chain = make_cleanup (do_stop_reply_xfree, stop_reply);
2875 remote_parse_stop_reply (rs->buf, stop_reply);
2876 discard_cleanups (old_chain);
2878 /* get_pending_stop_replies acks this one, and gets the rest
2880 pending_stop_reply = stop_reply;
2881 remote_get_pending_stop_replies ();
2883 /* Make sure that threads that were stopped remain
2885 iterate_over_threads (set_stop_requested_callback, NULL);
2888 if (target_can_async_p ())
2889 target_async (inferior_event_handler, 0);
2891 if (thread_count () == 0)
2893 if (!args->extended_p)
2894 error (_("The target is not running (try extended-remote?)"));
2896 /* We're connected, but not running. Drop out before we
2897 call start_remote. */
2901 /* Let the stub know that we want it to return the thread. */
2903 /* Force the stub to choose a thread. */
2904 set_general_thread (null_ptid);
2907 inferior_ptid = remote_current_thread (minus_one_ptid);
2908 if (ptid_equal (inferior_ptid, minus_one_ptid))
2909 error (_("remote didn't report the current thread in non-stop mode"));
2911 get_offsets (); /* Get text, data & bss offsets. */
2913 /* In non-stop mode, any cached wait status will be stored in
2914 the stop reply queue. */
2915 gdb_assert (wait_status == NULL);
2918 /* If we connected to a live target, do some additional setup. */
2919 if (target_has_execution)
2921 if (exec_bfd) /* No use without an exec file. */
2922 remote_check_symbols (symfile_objfile);
2925 /* If breakpoints are global, insert them now. */
2926 if (gdbarch_has_global_breakpoints (target_gdbarch)
2927 && breakpoints_always_inserted_mode ())
2928 insert_breakpoints ();
2931 /* Open a connection to a remote debugger.
2932 NAME is the filename used for communication. */
2935 remote_open (char *name, int from_tty)
2937 remote_open_1 (name, from_tty, &remote_ops, 0);
2940 /* Open a connection to a remote debugger using the extended
2941 remote gdb protocol. NAME is the filename used for communication. */
2944 extended_remote_open (char *name, int from_tty)
2946 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
2949 /* Generic code for opening a connection to a remote target. */
2952 init_all_packet_configs (void)
2955 for (i = 0; i < PACKET_MAX; i++)
2956 update_packet_config (&remote_protocol_packets[i]);
2959 /* Symbol look-up. */
2962 remote_check_symbols (struct objfile *objfile)
2964 struct remote_state *rs = get_remote_state ();
2965 char *msg, *reply, *tmp;
2966 struct minimal_symbol *sym;
2969 if (remote_protocol_packets[PACKET_qSymbol].support == PACKET_DISABLE)
2972 /* Make sure the remote is pointing at the right process. */
2973 set_general_process ();
2975 /* Allocate a message buffer. We can't reuse the input buffer in RS,
2976 because we need both at the same time. */
2977 msg = alloca (get_remote_packet_size ());
2979 /* Invite target to request symbol lookups. */
2981 putpkt ("qSymbol::");
2982 getpkt (&rs->buf, &rs->buf_size, 0);
2983 packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSymbol]);
2986 while (strncmp (reply, "qSymbol:", 8) == 0)
2989 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
2991 sym = lookup_minimal_symbol (msg, NULL, NULL);
2993 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
2996 int addr_size = gdbarch_addr_bit (target_gdbarch) / 8;
2997 CORE_ADDR sym_addr = SYMBOL_VALUE_ADDRESS (sym);
2999 /* If this is a function address, return the start of code
3000 instead of any data function descriptor. */
3001 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch,
3005 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
3006 phex_nz (sym_addr, addr_size), &reply[8]);
3010 getpkt (&rs->buf, &rs->buf_size, 0);
3015 static struct serial *
3016 remote_serial_open (char *name)
3018 static int udp_warning = 0;
3020 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
3021 of in ser-tcp.c, because it is the remote protocol assuming that the
3022 serial connection is reliable and not the serial connection promising
3024 if (!udp_warning && strncmp (name, "udp:", 4) == 0)
3027 The remote protocol may be unreliable over UDP.\n\
3028 Some events may be lost, rendering further debugging impossible."));
3032 return serial_open (name);
3035 /* This type describes each known response to the qSupported
3037 struct protocol_feature
3039 /* The name of this protocol feature. */
3042 /* The default for this protocol feature. */
3043 enum packet_support default_support;
3045 /* The function to call when this feature is reported, or after
3046 qSupported processing if the feature is not supported.
3047 The first argument points to this structure. The second
3048 argument indicates whether the packet requested support be
3049 enabled, disabled, or probed (or the default, if this function
3050 is being called at the end of processing and this feature was
3051 not reported). The third argument may be NULL; if not NULL, it
3052 is a NUL-terminated string taken from the packet following
3053 this feature's name and an equals sign. */
3054 void (*func) (const struct protocol_feature *, enum packet_support,
3057 /* The corresponding packet for this feature. Only used if
3058 FUNC is remote_supported_packet. */
3063 remote_supported_packet (const struct protocol_feature *feature,
3064 enum packet_support support,
3065 const char *argument)
3069 warning (_("Remote qSupported response supplied an unexpected value for"
3070 " \"%s\"."), feature->name);
3074 if (remote_protocol_packets[feature->packet].support
3075 == PACKET_SUPPORT_UNKNOWN)
3076 remote_protocol_packets[feature->packet].support = support;
3080 remote_packet_size (const struct protocol_feature *feature,
3081 enum packet_support support, const char *value)
3083 struct remote_state *rs = get_remote_state ();
3088 if (support != PACKET_ENABLE)
3091 if (value == NULL || *value == '\0')
3093 warning (_("Remote target reported \"%s\" without a size."),
3099 packet_size = strtol (value, &value_end, 16);
3100 if (errno != 0 || *value_end != '\0' || packet_size < 0)
3102 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
3103 feature->name, value);
3107 if (packet_size > MAX_REMOTE_PACKET_SIZE)
3109 warning (_("limiting remote suggested packet size (%d bytes) to %d"),
3110 packet_size, MAX_REMOTE_PACKET_SIZE);
3111 packet_size = MAX_REMOTE_PACKET_SIZE;
3114 /* Record the new maximum packet size. */
3115 rs->explicit_packet_size = packet_size;
3119 remote_multi_process_feature (const struct protocol_feature *feature,
3120 enum packet_support support, const char *value)
3122 struct remote_state *rs = get_remote_state ();
3123 rs->multi_process_aware = (support == PACKET_ENABLE);
3127 remote_non_stop_feature (const struct protocol_feature *feature,
3128 enum packet_support support, const char *value)
3130 struct remote_state *rs = get_remote_state ();
3131 rs->non_stop_aware = (support == PACKET_ENABLE);
3135 remote_cond_tracepoint_feature (const struct protocol_feature *feature,
3136 enum packet_support support,
3139 struct remote_state *rs = get_remote_state ();
3140 rs->cond_tracepoints = (support == PACKET_ENABLE);
3144 remote_fast_tracepoint_feature (const struct protocol_feature *feature,
3145 enum packet_support support,
3148 struct remote_state *rs = get_remote_state ();
3149 rs->fast_tracepoints = (support == PACKET_ENABLE);
3152 static struct protocol_feature remote_protocol_features[] = {
3153 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
3154 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
3155 PACKET_qXfer_auxv },
3156 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
3157 PACKET_qXfer_features },
3158 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
3159 PACKET_qXfer_libraries },
3160 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
3161 PACKET_qXfer_memory_map },
3162 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
3163 PACKET_qXfer_spu_read },
3164 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
3165 PACKET_qXfer_spu_write },
3166 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
3167 PACKET_qXfer_osdata },
3168 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
3169 PACKET_QPassSignals },
3170 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
3171 PACKET_QStartNoAckMode },
3172 { "multiprocess", PACKET_DISABLE, remote_multi_process_feature, -1 },
3173 { "QNonStop", PACKET_DISABLE, remote_non_stop_feature, -1 },
3174 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
3175 PACKET_qXfer_siginfo_read },
3176 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
3177 PACKET_qXfer_siginfo_write },
3178 { "ConditionalTracepoints", PACKET_DISABLE, remote_cond_tracepoint_feature,
3179 PACKET_ConditionalTracepoints },
3180 { "FastTracepoints", PACKET_DISABLE, remote_fast_tracepoint_feature,
3181 PACKET_FastTracepoints },
3182 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
3184 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
3189 remote_query_supported (void)
3191 struct remote_state *rs = get_remote_state ();
3194 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
3196 /* The packet support flags are handled differently for this packet
3197 than for most others. We treat an error, a disabled packet, and
3198 an empty response identically: any features which must be reported
3199 to be used will be automatically disabled. An empty buffer
3200 accomplishes this, since that is also the representation for a list
3201 containing no features. */
3204 if (remote_protocol_packets[PACKET_qSupported].support != PACKET_DISABLE)
3207 putpkt ("qSupported:multiprocess+");
3209 putpkt ("qSupported");
3211 getpkt (&rs->buf, &rs->buf_size, 0);
3213 /* If an error occured, warn, but do not return - just reset the
3214 buffer to empty and go on to disable features. */
3215 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
3218 warning (_("Remote failure reply: %s"), rs->buf);
3223 memset (seen, 0, sizeof (seen));
3228 enum packet_support is_supported;
3229 char *p, *end, *name_end, *value;
3231 /* First separate out this item from the rest of the packet. If
3232 there's another item after this, we overwrite the separator
3233 (terminated strings are much easier to work with). */
3235 end = strchr (p, ';');
3238 end = p + strlen (p);
3248 warning (_("empty item in \"qSupported\" response"));
3253 name_end = strchr (p, '=');
3256 /* This is a name=value entry. */
3257 is_supported = PACKET_ENABLE;
3258 value = name_end + 1;
3267 is_supported = PACKET_ENABLE;
3271 is_supported = PACKET_DISABLE;
3275 is_supported = PACKET_SUPPORT_UNKNOWN;
3279 warning (_("unrecognized item \"%s\" in \"qSupported\" response"), p);
3285 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
3286 if (strcmp (remote_protocol_features[i].name, p) == 0)
3288 const struct protocol_feature *feature;
3291 feature = &remote_protocol_features[i];
3292 feature->func (feature, is_supported, value);
3297 /* If we increased the packet size, make sure to increase the global
3298 buffer size also. We delay this until after parsing the entire
3299 qSupported packet, because this is the same buffer we were
3301 if (rs->buf_size < rs->explicit_packet_size)
3303 rs->buf_size = rs->explicit_packet_size;
3304 rs->buf = xrealloc (rs->buf, rs->buf_size);
3307 /* Handle the defaults for unmentioned features. */
3308 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
3311 const struct protocol_feature *feature;
3313 feature = &remote_protocol_features[i];
3314 feature->func (feature, feature->default_support, NULL);
3320 remote_open_1 (char *name, int from_tty, struct target_ops *target, int extended_p)
3322 struct remote_state *rs = get_remote_state ();
3325 error (_("To open a remote debug connection, you need to specify what\n"
3326 "serial device is attached to the remote system\n"
3327 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
3329 /* See FIXME above. */
3330 if (!target_async_permitted)
3331 wait_forever_enabled_p = 1;
3333 /* If we're connected to a running target, target_preopen will kill it.
3334 But if we're connected to a target system with no running process,
3335 then we will still be connected when it returns. Ask this question
3336 first, before target_preopen has a chance to kill anything. */
3337 if (remote_desc != NULL && !have_inferiors ())
3340 || query (_("Already connected to a remote target. Disconnect? ")))
3343 error (_("Still connected."));
3346 target_preopen (from_tty);
3348 unpush_target (target);
3350 /* This time without a query. If we were connected to an
3351 extended-remote target and target_preopen killed the running
3352 process, we may still be connected. If we are starting "target
3353 remote" now, the extended-remote target will not have been
3354 removed by unpush_target. */
3355 if (remote_desc != NULL && !have_inferiors ())
3358 /* Make sure we send the passed signals list the next time we resume. */
3359 xfree (last_pass_packet);
3360 last_pass_packet = NULL;
3362 remote_fileio_reset ();
3363 reopen_exec_file ();
3366 remote_desc = remote_serial_open (name);
3368 perror_with_name (name);
3370 if (baud_rate != -1)
3372 if (serial_setbaudrate (remote_desc, baud_rate))
3374 /* The requested speed could not be set. Error out to
3375 top level after closing remote_desc. Take care to
3376 set remote_desc to NULL to avoid closing remote_desc
3378 serial_close (remote_desc);
3380 perror_with_name (name);
3384 serial_raw (remote_desc);
3386 /* If there is something sitting in the buffer we might take it as a
3387 response to a command, which would be bad. */
3388 serial_flush_input (remote_desc);
3392 puts_filtered ("Remote debugging using ");
3393 puts_filtered (name);
3394 puts_filtered ("\n");
3396 push_target (target); /* Switch to using remote target now. */
3398 /* Register extra event sources in the event loop. */
3399 remote_async_inferior_event_token
3400 = create_async_event_handler (remote_async_inferior_event_handler,
3402 remote_async_get_pending_events_token
3403 = create_async_event_handler (remote_async_get_pending_events_handler,
3406 /* Reset the target state; these things will be queried either by
3407 remote_query_supported or as they are needed. */
3408 init_all_packet_configs ();
3409 rs->cached_wait_status = 0;
3410 rs->explicit_packet_size = 0;
3412 rs->multi_process_aware = 0;
3413 rs->extended = extended_p;
3414 rs->non_stop_aware = 0;
3415 rs->waiting_for_stop_reply = 0;
3416 rs->ctrlc_pending_p = 0;
3418 general_thread = not_sent_ptid;
3419 continue_thread = not_sent_ptid;
3421 /* Probe for ability to use "ThreadInfo" query, as required. */
3422 use_threadinfo_query = 1;
3423 use_threadextra_query = 1;
3425 if (target_async_permitted)
3427 /* With this target we start out by owning the terminal. */
3428 remote_async_terminal_ours_p = 1;
3430 /* FIXME: cagney/1999-09-23: During the initial connection it is
3431 assumed that the target is already ready and able to respond to
3432 requests. Unfortunately remote_start_remote() eventually calls
3433 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
3434 around this. Eventually a mechanism that allows
3435 wait_for_inferior() to expect/get timeouts will be
3437 wait_forever_enabled_p = 0;
3440 /* First delete any symbols previously loaded from shared libraries. */
3441 no_shared_libraries (NULL, 0);
3444 init_thread_list ();
3446 /* Start the remote connection. If error() or QUIT, discard this
3447 target (we'd otherwise be in an inconsistent state) and then
3448 propogate the error on up the exception chain. This ensures that
3449 the caller doesn't stumble along blindly assuming that the
3450 function succeeded. The CLI doesn't have this problem but other
3451 UI's, such as MI do.
3453 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
3454 this function should return an error indication letting the
3455 caller restore the previous state. Unfortunately the command
3456 ``target remote'' is directly wired to this function making that
3457 impossible. On a positive note, the CLI side of this problem has
3458 been fixed - the function set_cmd_context() makes it possible for
3459 all the ``target ....'' commands to share a common callback
3460 function. See cli-dump.c. */
3462 struct gdb_exception ex;
3463 struct start_remote_args args;
3465 args.from_tty = from_tty;
3466 args.target = target;
3467 args.extended_p = extended_p;
3469 ex = catch_exception (uiout, remote_start_remote, &args, RETURN_MASK_ALL);
3472 /* Pop the partially set up target - unless something else did
3473 already before throwing the exception. */
3474 if (remote_desc != NULL)
3476 if (target_async_permitted)
3477 wait_forever_enabled_p = 1;
3478 throw_exception (ex);
3482 if (target_async_permitted)
3483 wait_forever_enabled_p = 1;
3486 /* This takes a program previously attached to and detaches it. After
3487 this is done, GDB can be used to debug some other program. We
3488 better not have left any breakpoints in the target program or it'll
3489 die when it hits one. */
3492 remote_detach_1 (char *args, int from_tty, int extended)
3494 int pid = ptid_get_pid (inferior_ptid);
3495 struct remote_state *rs = get_remote_state ();
3498 error (_("Argument given to \"detach\" when remotely debugging."));
3500 if (!target_has_execution)
3501 error (_("No process to detach from."));
3503 /* Tell the remote target to detach. */
3504 if (remote_multi_process_p (rs))
3505 sprintf (rs->buf, "D;%x", pid);
3507 strcpy (rs->buf, "D");
3510 getpkt (&rs->buf, &rs->buf_size, 0);
3512 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
3514 else if (rs->buf[0] == '\0')
3515 error (_("Remote doesn't know how to detach"));
3517 error (_("Can't detach process."));
3521 if (remote_multi_process_p (rs))
3522 printf_filtered (_("Detached from remote %s.\n"),
3523 target_pid_to_str (pid_to_ptid (pid)));
3527 puts_filtered (_("Detached from remote process.\n"));
3529 puts_filtered (_("Ending remote debugging.\n"));
3533 discard_pending_stop_replies (pid);
3534 target_mourn_inferior ();
3538 remote_detach (struct target_ops *ops, char *args, int from_tty)
3540 remote_detach_1 (args, from_tty, 0);
3544 extended_remote_detach (struct target_ops *ops, char *args, int from_tty)
3546 remote_detach_1 (args, from_tty, 1);
3549 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
3552 remote_disconnect (struct target_ops *target, char *args, int from_tty)
3555 error (_("Argument given to \"disconnect\" when remotely debugging."));
3557 /* Make sure we unpush even the extended remote targets; mourn
3558 won't do it. So call remote_mourn_1 directly instead of
3559 target_mourn_inferior. */
3560 remote_mourn_1 (target);
3563 puts_filtered ("Ending remote debugging.\n");
3566 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
3567 be chatty about it. */
3570 extended_remote_attach_1 (struct target_ops *target, char *args, int from_tty)
3572 struct remote_state *rs = get_remote_state ();
3575 char *wait_status = NULL;
3578 error_no_arg (_("process-id to attach"));
3581 pid = strtol (args, &dummy, 0);
3582 /* Some targets don't set errno on errors, grrr! */
3583 if (pid == 0 && args == dummy)
3584 error (_("Illegal process-id: %s."), args);
3586 if (remote_protocol_packets[PACKET_vAttach].support == PACKET_DISABLE)
3587 error (_("This target does not support attaching to a process"));
3589 sprintf (rs->buf, "vAttach;%x", pid);
3591 getpkt (&rs->buf, &rs->buf_size, 0);
3593 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vAttach]) == PACKET_OK)
3596 printf_unfiltered (_("Attached to %s\n"),
3597 target_pid_to_str (pid_to_ptid (pid)));
3601 /* Save the reply for later. */
3602 wait_status = alloca (strlen (rs->buf) + 1);
3603 strcpy (wait_status, rs->buf);
3605 else if (strcmp (rs->buf, "OK") != 0)
3606 error (_("Attaching to %s failed with: %s"),
3607 target_pid_to_str (pid_to_ptid (pid)),
3610 else if (remote_protocol_packets[PACKET_vAttach].support == PACKET_DISABLE)
3611 error (_("This target does not support attaching to a process"));
3613 error (_("Attaching to %s failed"),
3614 target_pid_to_str (pid_to_ptid (pid)));
3616 set_current_inferior (remote_add_inferior (pid, 1));
3618 inferior_ptid = pid_to_ptid (pid);
3622 struct thread_info *thread;
3624 /* Get list of threads. */
3625 remote_threads_info (target);
3627 thread = first_thread_of_process (pid);
3629 inferior_ptid = thread->ptid;
3631 inferior_ptid = pid_to_ptid (pid);
3633 /* Invalidate our notion of the remote current thread. */
3634 record_currthread (minus_one_ptid);
3638 /* Now, if we have thread information, update inferior_ptid. */
3639 inferior_ptid = remote_current_thread (inferior_ptid);
3641 /* Add the main thread to the thread list. */
3642 add_thread_silent (inferior_ptid);
3645 /* Next, if the target can specify a description, read it. We do
3646 this before anything involving memory or registers. */
3647 target_find_description ();
3651 /* Use the previously fetched status. */
3652 gdb_assert (wait_status != NULL);
3654 if (target_can_async_p ())
3656 struct stop_reply *stop_reply;
3657 struct cleanup *old_chain;
3659 stop_reply = stop_reply_xmalloc ();
3660 old_chain = make_cleanup (do_stop_reply_xfree, stop_reply);
3661 remote_parse_stop_reply (wait_status, stop_reply);
3662 discard_cleanups (old_chain);
3663 push_stop_reply (stop_reply);
3665 target_async (inferior_event_handler, 0);
3669 gdb_assert (wait_status != NULL);
3670 strcpy (rs->buf, wait_status);
3671 rs->cached_wait_status = 1;
3675 gdb_assert (wait_status == NULL);
3679 extended_remote_attach (struct target_ops *ops, char *args, int from_tty)
3681 extended_remote_attach_1 (ops, args, from_tty);
3684 /* Convert hex digit A to a number. */
3689 if (a >= '0' && a <= '9')
3691 else if (a >= 'a' && a <= 'f')
3692 return a - 'a' + 10;
3693 else if (a >= 'A' && a <= 'F')
3694 return a - 'A' + 10;
3696 error (_("Reply contains invalid hex digit %d"), a);
3700 hex2bin (const char *hex, gdb_byte *bin, int count)
3704 for (i = 0; i < count; i++)
3706 if (hex[0] == 0 || hex[1] == 0)
3708 /* Hex string is short, or of uneven length.
3709 Return the count that has been converted so far. */
3712 *bin++ = fromhex (hex[0]) * 16 + fromhex (hex[1]);
3718 /* Convert number NIB to a hex digit. */
3726 return 'a' + nib - 10;
3730 bin2hex (const gdb_byte *bin, char *hex, int count)
3733 /* May use a length, or a nul-terminated string as input. */
3735 count = strlen ((char *) bin);
3737 for (i = 0; i < count; i++)
3739 *hex++ = tohex ((*bin >> 4) & 0xf);
3740 *hex++ = tohex (*bin++ & 0xf);
3746 /* Check for the availability of vCont. This function should also check
3750 remote_vcont_probe (struct remote_state *rs)
3754 strcpy (rs->buf, "vCont?");
3756 getpkt (&rs->buf, &rs->buf_size, 0);
3759 /* Make sure that the features we assume are supported. */
3760 if (strncmp (buf, "vCont", 5) == 0)
3763 int support_s, support_S, support_c, support_C;
3769 rs->support_vCont_t = 0;
3770 while (p && *p == ';')
3773 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
3775 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
3777 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
3779 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
3781 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
3782 rs->support_vCont_t = 1;
3784 p = strchr (p, ';');
3787 /* If s, S, c, and C are not all supported, we can't use vCont. Clearing
3788 BUF will make packet_ok disable the packet. */
3789 if (!support_s || !support_S || !support_c || !support_C)
3793 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
3796 /* Helper function for building "vCont" resumptions. Write a
3797 resumption to P. ENDP points to one-passed-the-end of the buffer
3798 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
3799 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
3800 resumed thread should be single-stepped and/or signalled. If PTID
3801 equals minus_one_ptid, then all threads are resumed; if PTID
3802 represents a process, then all threads of the process are resumed;
3803 the thread to be stepped and/or signalled is given in the global
3807 append_resumption (char *p, char *endp,
3808 ptid_t ptid, int step, enum target_signal siggnal)
3810 struct remote_state *rs = get_remote_state ();
3812 if (step && siggnal != TARGET_SIGNAL_0)
3813 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
3815 p += xsnprintf (p, endp - p, ";s");
3816 else if (siggnal != TARGET_SIGNAL_0)
3817 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
3819 p += xsnprintf (p, endp - p, ";c");
3821 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
3825 /* All (-1) threads of process. */
3826 nptid = ptid_build (ptid_get_pid (ptid), 0, -1);
3828 p += xsnprintf (p, endp - p, ":");
3829 p = write_ptid (p, endp, nptid);
3831 else if (!ptid_equal (ptid, minus_one_ptid))
3833 p += xsnprintf (p, endp - p, ":");
3834 p = write_ptid (p, endp, ptid);
3840 /* Resume the remote inferior by using a "vCont" packet. The thread
3841 to be resumed is PTID; STEP and SIGGNAL indicate whether the
3842 resumed thread should be single-stepped and/or signalled. If PTID
3843 equals minus_one_ptid, then all threads are resumed; the thread to
3844 be stepped and/or signalled is given in the global INFERIOR_PTID.
3845 This function returns non-zero iff it resumes the inferior.
3847 This function issues a strict subset of all possible vCont commands at the
3851 remote_vcont_resume (ptid_t ptid, int step, enum target_signal siggnal)
3853 struct remote_state *rs = get_remote_state ();
3857 if (remote_protocol_packets[PACKET_vCont].support == PACKET_SUPPORT_UNKNOWN)
3858 remote_vcont_probe (rs);
3860 if (remote_protocol_packets[PACKET_vCont].support == PACKET_DISABLE)
3864 endp = rs->buf + get_remote_packet_size ();
3866 /* If we could generate a wider range of packets, we'd have to worry
3867 about overflowing BUF. Should there be a generic
3868 "multi-part-packet" packet? */
3870 p += xsnprintf (p, endp - p, "vCont");
3872 if (ptid_equal (ptid, magic_null_ptid))
3874 /* MAGIC_NULL_PTID means that we don't have any active threads,
3875 so we don't have any TID numbers the inferior will
3876 understand. Make sure to only send forms that do not specify
3878 p = append_resumption (p, endp, minus_one_ptid, step, siggnal);
3880 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
3882 /* Resume all threads (of all processes, or of a single
3883 process), with preference for INFERIOR_PTID. This assumes
3884 inferior_ptid belongs to the set of all threads we are about
3886 if (step || siggnal != TARGET_SIGNAL_0)
3888 /* Step inferior_ptid, with or without signal. */
3889 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
3892 /* And continue others without a signal. */
3893 p = append_resumption (p, endp, ptid, /*step=*/ 0, TARGET_SIGNAL_0);
3897 /* Scheduler locking; resume only PTID. */
3898 p = append_resumption (p, endp, ptid, step, siggnal);
3901 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
3906 /* In non-stop, the stub replies to vCont with "OK". The stop
3907 reply will be reported asynchronously by means of a `%Stop'
3909 getpkt (&rs->buf, &rs->buf_size, 0);
3910 if (strcmp (rs->buf, "OK") != 0)
3911 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
3917 /* Tell the remote machine to resume. */
3919 static enum target_signal last_sent_signal = TARGET_SIGNAL_0;
3921 static int last_sent_step;
3924 remote_resume (struct target_ops *ops,
3925 ptid_t ptid, int step, enum target_signal siggnal)
3927 struct remote_state *rs = get_remote_state ();
3930 last_sent_signal = siggnal;
3931 last_sent_step = step;
3933 /* Update the inferior on signals to silently pass, if they've changed. */
3934 remote_pass_signals ();
3936 /* The vCont packet doesn't need to specify threads via Hc. */
3937 /* No reverse support (yet) for vCont. */
3938 if (execution_direction != EXEC_REVERSE)
3939 if (remote_vcont_resume (ptid, step, siggnal))
3942 /* All other supported resume packets do use Hc, so set the continue
3944 if (ptid_equal (ptid, minus_one_ptid))
3945 set_continue_thread (any_thread_ptid);
3947 set_continue_thread (ptid);
3950 if (execution_direction == EXEC_REVERSE)
3952 /* We don't pass signals to the target in reverse exec mode. */
3953 if (info_verbose && siggnal != TARGET_SIGNAL_0)
3954 warning (" - Can't pass signal %d to target in reverse: ignored.\n",
3958 && remote_protocol_packets[PACKET_bs].support == PACKET_DISABLE)
3959 error (_("Remote reverse-step not supported."));
3961 && remote_protocol_packets[PACKET_bc].support == PACKET_DISABLE)
3962 error (_("Remote reverse-continue not supported."));
3964 strcpy (buf, step ? "bs" : "bc");
3966 else if (siggnal != TARGET_SIGNAL_0)
3968 buf[0] = step ? 'S' : 'C';
3969 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
3970 buf[2] = tohex (((int) siggnal) & 0xf);
3974 strcpy (buf, step ? "s" : "c");
3979 /* We are about to start executing the inferior, let's register it
3980 with the event loop. NOTE: this is the one place where all the
3981 execution commands end up. We could alternatively do this in each
3982 of the execution commands in infcmd.c. */
3983 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
3984 into infcmd.c in order to allow inferior function calls to work
3985 NOT asynchronously. */
3986 if (target_can_async_p ())
3987 target_async (inferior_event_handler, 0);
3989 /* We've just told the target to resume. The remote server will
3990 wait for the inferior to stop, and then send a stop reply. In
3991 the mean time, we can't start another command/query ourselves
3992 because the stub wouldn't be ready to process it. This applies
3993 only to the base all-stop protocol, however. In non-stop (which
3994 only supports vCont), the stub replies with an "OK", and is
3995 immediate able to process further serial input. */
3997 rs->waiting_for_stop_reply = 1;
4001 /* Set up the signal handler for SIGINT, while the target is
4002 executing, ovewriting the 'regular' SIGINT signal handler. */
4004 initialize_sigint_signal_handler (void)
4006 signal (SIGINT, handle_remote_sigint);
4009 /* Signal handler for SIGINT, while the target is executing. */
4011 handle_remote_sigint (int sig)
4013 signal (sig, handle_remote_sigint_twice);
4014 mark_async_signal_handler_wrapper (sigint_remote_token);
4017 /* Signal handler for SIGINT, installed after SIGINT has already been
4018 sent once. It will take effect the second time that the user sends
4021 handle_remote_sigint_twice (int sig)
4023 signal (sig, handle_remote_sigint);
4024 mark_async_signal_handler_wrapper (sigint_remote_twice_token);
4027 /* Perform the real interruption of the target execution, in response
4030 async_remote_interrupt (gdb_client_data arg)
4033 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
4035 target_stop (inferior_ptid);
4038 /* Perform interrupt, if the first attempt did not succeed. Just give
4039 up on the target alltogether. */
4041 async_remote_interrupt_twice (gdb_client_data arg)
4044 fprintf_unfiltered (gdb_stdlog, "remote_interrupt_twice called\n");
4049 /* Reinstall the usual SIGINT handlers, after the target has
4052 cleanup_sigint_signal_handler (void *dummy)
4054 signal (SIGINT, handle_sigint);
4057 /* Send ^C to target to halt it. Target will respond, and send us a
4059 static void (*ofunc) (int);
4061 /* The command line interface's stop routine. This function is installed
4062 as a signal handler for SIGINT. The first time a user requests a
4063 stop, we call remote_stop to send a break or ^C. If there is no
4064 response from the target (it didn't stop when the user requested it),
4065 we ask the user if he'd like to detach from the target. */
4067 remote_interrupt (int signo)
4069 /* If this doesn't work, try more severe steps. */
4070 signal (signo, remote_interrupt_twice);
4072 gdb_call_async_signal_handler (sigint_remote_token, 1);
4075 /* The user typed ^C twice. */
4078 remote_interrupt_twice (int signo)
4080 signal (signo, ofunc);
4081 gdb_call_async_signal_handler (sigint_remote_twice_token, 1);
4082 signal (signo, remote_interrupt);
4085 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
4086 thread, all threads of a remote process, or all threads of all
4090 remote_stop_ns (ptid_t ptid)
4092 struct remote_state *rs = get_remote_state ();
4094 char *endp = rs->buf + get_remote_packet_size ();
4096 if (remote_protocol_packets[PACKET_vCont].support == PACKET_SUPPORT_UNKNOWN)
4097 remote_vcont_probe (rs);
4099 if (!rs->support_vCont_t)
4100 error (_("Remote server does not support stopping threads"));
4102 if (ptid_equal (ptid, minus_one_ptid)
4103 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
4104 p += xsnprintf (p, endp - p, "vCont;t");
4109 p += xsnprintf (p, endp - p, "vCont;t:");
4111 if (ptid_is_pid (ptid))
4112 /* All (-1) threads of process. */
4113 nptid = ptid_build (ptid_get_pid (ptid), 0, -1);
4116 /* Small optimization: if we already have a stop reply for
4117 this thread, no use in telling the stub we want this
4119 if (peek_stop_reply (ptid))
4125 p = write_ptid (p, endp, nptid);
4128 /* In non-stop, we get an immediate OK reply. The stop reply will
4129 come in asynchronously by notification. */
4131 getpkt (&rs->buf, &rs->buf_size, 0);
4132 if (strcmp (rs->buf, "OK") != 0)
4133 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
4136 /* All-stop version of target_stop. Sends a break or a ^C to stop the
4137 remote target. It is undefined which thread of which process
4138 reports the stop. */
4141 remote_stop_as (ptid_t ptid)
4143 struct remote_state *rs = get_remote_state ();
4145 rs->ctrlc_pending_p = 1;
4147 /* If the inferior is stopped already, but the core didn't know
4148 about it yet, just ignore the request. The cached wait status
4149 will be collected in remote_wait. */
4150 if (rs->cached_wait_status)
4153 /* Send interrupt_sequence to remote target. */
4154 send_interrupt_sequence ();
4157 /* This is the generic stop called via the target vector. When a target
4158 interrupt is requested, either by the command line or the GUI, we
4159 will eventually end up here. */
4162 remote_stop (ptid_t ptid)
4165 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
4168 remote_stop_ns (ptid);
4170 remote_stop_as (ptid);
4173 /* Ask the user what to do when an interrupt is received. */
4176 interrupt_query (void)
4178 target_terminal_ours ();
4180 if (target_can_async_p ())
4182 signal (SIGINT, handle_sigint);
4183 deprecated_throw_reason (RETURN_QUIT);
4187 if (query (_("Interrupted while waiting for the program.\n\
4188 Give up (and stop debugging it)? ")))
4191 deprecated_throw_reason (RETURN_QUIT);
4195 target_terminal_inferior ();
4198 /* Enable/disable target terminal ownership. Most targets can use
4199 terminal groups to control terminal ownership. Remote targets are
4200 different in that explicit transfer of ownership to/from GDB/target
4204 remote_terminal_inferior (void)
4206 if (!target_async_permitted)
4207 /* Nothing to do. */
4210 /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
4211 idempotent. The event-loop GDB talking to an asynchronous target
4212 with a synchronous command calls this function from both
4213 event-top.c and infrun.c/infcmd.c. Once GDB stops trying to
4214 transfer the terminal to the target when it shouldn't this guard
4216 if (!remote_async_terminal_ours_p)
4218 delete_file_handler (input_fd);
4219 remote_async_terminal_ours_p = 0;
4220 initialize_sigint_signal_handler ();
4221 /* NOTE: At this point we could also register our selves as the
4222 recipient of all input. Any characters typed could then be
4223 passed on down to the target. */
4227 remote_terminal_ours (void)
4229 if (!target_async_permitted)
4230 /* Nothing to do. */
4233 /* See FIXME in remote_terminal_inferior. */
4234 if (remote_async_terminal_ours_p)
4236 cleanup_sigint_signal_handler (NULL);
4237 add_file_handler (input_fd, stdin_event_handler, 0);
4238 remote_async_terminal_ours_p = 1;
4242 remote_console_output (char *msg)
4246 for (p = msg; p[0] && p[1]; p += 2)
4249 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
4252 fputs_unfiltered (tb, gdb_stdtarg);
4254 gdb_flush (gdb_stdtarg);
4257 typedef struct cached_reg
4260 gdb_byte data[MAX_REGISTER_SIZE];
4263 DEF_VEC_O(cached_reg_t);
4267 struct stop_reply *next;
4271 struct target_waitstatus ws;
4273 VEC(cached_reg_t) *regcache;
4275 int stopped_by_watchpoint_p;
4276 CORE_ADDR watch_data_address;
4282 /* The list of already fetched and acknowledged stop events. */
4283 static struct stop_reply *stop_reply_queue;
4285 static struct stop_reply *
4286 stop_reply_xmalloc (void)
4288 struct stop_reply *r = XMALLOC (struct stop_reply);
4294 stop_reply_xfree (struct stop_reply *r)
4298 VEC_free (cached_reg_t, r->regcache);
4303 /* Discard all pending stop replies of inferior PID. If PID is -1,
4304 discard everything. */
4307 discard_pending_stop_replies (int pid)
4309 struct stop_reply *prev = NULL, *reply, *next;
4311 /* Discard the in-flight notification. */
4312 if (pending_stop_reply != NULL
4314 || ptid_get_pid (pending_stop_reply->ptid) == pid))
4316 stop_reply_xfree (pending_stop_reply);
4317 pending_stop_reply = NULL;
4320 /* Discard the stop replies we have already pulled with
4322 for (reply = stop_reply_queue; reply; reply = next)
4326 || ptid_get_pid (reply->ptid) == pid)
4328 if (reply == stop_reply_queue)
4329 stop_reply_queue = reply->next;
4331 prev->next = reply->next;
4333 stop_reply_xfree (reply);
4340 /* Cleanup wrapper. */
4343 do_stop_reply_xfree (void *arg)
4345 struct stop_reply *r = arg;
4346 stop_reply_xfree (r);
4349 /* Look for a queued stop reply belonging to PTID. If one is found,
4350 remove it from the queue, and return it. Returns NULL if none is
4351 found. If there are still queued events left to process, tell the
4352 event loop to get back to target_wait soon. */
4354 static struct stop_reply *
4355 queued_stop_reply (ptid_t ptid)
4357 struct stop_reply *it, *prev;
4358 struct stop_reply head;
4360 head.next = stop_reply_queue;
4365 if (!ptid_equal (ptid, minus_one_ptid))
4366 for (; it; prev = it, it = it->next)
4367 if (ptid_equal (ptid, it->ptid))
4372 prev->next = it->next;
4376 stop_reply_queue = head.next;
4378 if (stop_reply_queue)
4379 /* There's still at least an event left. */
4380 mark_async_event_handler (remote_async_inferior_event_token);
4385 /* Push a fully parsed stop reply in the stop reply queue. Since we
4386 know that we now have at least one queued event left to pass to the
4387 core side, tell the event loop to get back to target_wait soon. */
4390 push_stop_reply (struct stop_reply *new_event)
4392 struct stop_reply *event;
4394 if (stop_reply_queue)
4396 for (event = stop_reply_queue;
4397 event && event->next;
4398 event = event->next)
4401 event->next = new_event;
4404 stop_reply_queue = new_event;
4406 mark_async_event_handler (remote_async_inferior_event_token);
4409 /* Returns true if we have a stop reply for PTID. */
4412 peek_stop_reply (ptid_t ptid)
4414 struct stop_reply *it;
4416 for (it = stop_reply_queue; it; it = it->next)
4417 if (ptid_equal (ptid, it->ptid))
4419 if (it->ws.kind == TARGET_WAITKIND_STOPPED)
4426 /* Parse the stop reply in BUF. Either the function succeeds, and the
4427 result is stored in EVENT, or throws an error. */
4430 remote_parse_stop_reply (char *buf, struct stop_reply *event)
4432 struct remote_arch_state *rsa = get_remote_arch_state ();
4436 event->ptid = null_ptid;
4437 event->ws.kind = TARGET_WAITKIND_IGNORE;
4438 event->ws.value.integer = 0;
4439 event->solibs_changed = 0;
4440 event->replay_event = 0;
4441 event->stopped_by_watchpoint_p = 0;
4442 event->regcache = NULL;
4446 case 'T': /* Status with PC, SP, FP, ... */
4447 /* Expedited reply, containing Signal, {regno, reg} repeat. */
4448 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
4450 n... = register number
4451 r... = register contents
4454 p = &buf[3]; /* after Txx */
4462 /* If the packet contains a register number, save it in
4463 pnum and set p1 to point to the character following it.
4464 Otherwise p1 points to p. */
4466 /* If this packet is an awatch packet, don't parse the 'a'
4467 as a register number. */
4469 if (strncmp (p, "awatch", strlen("awatch")) != 0)
4471 /* Read the ``P'' register number. */
4472 pnum = strtol (p, &p_temp, 16);
4478 if (p1 == p) /* No register number present here. */
4480 p1 = strchr (p, ':');
4482 error (_("Malformed packet(a) (missing colon): %s\n\
4485 if (strncmp (p, "thread", p1 - p) == 0)
4486 event->ptid = read_ptid (++p1, &p);
4487 else if ((strncmp (p, "watch", p1 - p) == 0)
4488 || (strncmp (p, "rwatch", p1 - p) == 0)
4489 || (strncmp (p, "awatch", p1 - p) == 0))
4491 event->stopped_by_watchpoint_p = 1;
4492 p = unpack_varlen_hex (++p1, &addr);
4493 event->watch_data_address = (CORE_ADDR) addr;
4495 else if (strncmp (p, "library", p1 - p) == 0)
4499 while (*p_temp && *p_temp != ';')
4502 event->solibs_changed = 1;
4505 else if (strncmp (p, "replaylog", p1 - p) == 0)
4507 /* NO_HISTORY event.
4508 p1 will indicate "begin" or "end", but
4509 it makes no difference for now, so ignore it. */
4510 event->replay_event = 1;
4511 p_temp = strchr (p1 + 1, ';');
4517 /* Silently skip unknown optional info. */
4518 p_temp = strchr (p1 + 1, ';');
4525 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
4526 cached_reg_t cached_reg;
4531 error (_("Malformed packet(b) (missing colon): %s\n\
4537 error (_("Remote sent bad register number %s: %s\n\
4539 phex_nz (pnum, 0), p, buf);
4541 cached_reg.num = reg->regnum;
4543 fieldsize = hex2bin (p, cached_reg.data,
4544 register_size (target_gdbarch,
4547 if (fieldsize < register_size (target_gdbarch,
4549 warning (_("Remote reply is too short: %s"), buf);
4551 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
4555 error (_("Remote register badly formatted: %s\nhere: %s"),
4560 case 'S': /* Old style status, just signal only. */
4561 if (event->solibs_changed)
4562 event->ws.kind = TARGET_WAITKIND_LOADED;
4563 else if (event->replay_event)
4564 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
4567 event->ws.kind = TARGET_WAITKIND_STOPPED;
4568 event->ws.value.sig = (enum target_signal)
4569 (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
4572 case 'W': /* Target exited. */
4579 /* GDB used to accept only 2 hex chars here. Stubs should
4580 only send more if they detect GDB supports multi-process
4582 p = unpack_varlen_hex (&buf[1], &value);
4586 /* The remote process exited. */
4587 event->ws.kind = TARGET_WAITKIND_EXITED;
4588 event->ws.value.integer = value;
4592 /* The remote process exited with a signal. */
4593 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
4594 event->ws.value.sig = (enum target_signal) value;
4597 /* If no process is specified, assume inferior_ptid. */
4598 pid = ptid_get_pid (inferior_ptid);
4607 else if (strncmp (p,
4608 "process:", sizeof ("process:") - 1) == 0)
4611 p += sizeof ("process:") - 1;
4612 unpack_varlen_hex (p, &upid);
4616 error (_("unknown stop reply packet: %s"), buf);
4619 error (_("unknown stop reply packet: %s"), buf);
4620 event->ptid = pid_to_ptid (pid);
4625 if (non_stop && ptid_equal (event->ptid, null_ptid))
4626 error (_("No process or thread specified in stop reply: %s"), buf);
4629 /* When the stub wants to tell GDB about a new stop reply, it sends a
4630 stop notification (%Stop). Those can come it at any time, hence,
4631 we have to make sure that any pending putpkt/getpkt sequence we're
4632 making is finished, before querying the stub for more events with
4633 vStopped. E.g., if we started a vStopped sequence immediatelly
4634 upon receiving the %Stop notification, something like this could
4642 1.6) <-- (registers reply to step #1.3)
4644 Obviously, the reply in step #1.6 would be unexpected to a vStopped
4647 To solve this, whenever we parse a %Stop notification sucessfully,
4648 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
4649 doing whatever we were doing:
4655 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
4656 2.5) <-- (registers reply to step #2.3)
4658 Eventualy after step #2.5, we return to the event loop, which
4659 notices there's an event on the
4660 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
4661 associated callback --- the function below. At this point, we're
4662 always safe to start a vStopped sequence. :
4665 2.7) <-- T05 thread:2
4671 remote_get_pending_stop_replies (void)
4673 struct remote_state *rs = get_remote_state ();
4675 if (pending_stop_reply)
4678 putpkt ("vStopped");
4680 /* Now we can rely on it. */
4681 push_stop_reply (pending_stop_reply);
4682 pending_stop_reply = NULL;
4686 getpkt (&rs->buf, &rs->buf_size, 0);
4687 if (strcmp (rs->buf, "OK") == 0)
4691 struct cleanup *old_chain;
4692 struct stop_reply *stop_reply = stop_reply_xmalloc ();
4694 old_chain = make_cleanup (do_stop_reply_xfree, stop_reply);
4695 remote_parse_stop_reply (rs->buf, stop_reply);
4698 putpkt ("vStopped");
4700 if (stop_reply->ws.kind != TARGET_WAITKIND_IGNORE)
4702 /* Now we can rely on it. */
4703 discard_cleanups (old_chain);
4704 push_stop_reply (stop_reply);
4707 /* We got an unknown stop reply. */
4708 do_cleanups (old_chain);
4715 /* Called when it is decided that STOP_REPLY holds the info of the
4716 event that is to be returned to the core. This function always
4717 destroys STOP_REPLY. */
4720 process_stop_reply (struct stop_reply *stop_reply,
4721 struct target_waitstatus *status)
4725 *status = stop_reply->ws;
4726 ptid = stop_reply->ptid;
4728 /* If no thread/process was reported by the stub, assume the current
4730 if (ptid_equal (ptid, null_ptid))
4731 ptid = inferior_ptid;
4733 if (status->kind != TARGET_WAITKIND_EXITED
4734 && status->kind != TARGET_WAITKIND_SIGNALLED)
4736 /* Expedited registers. */
4737 if (stop_reply->regcache)
4739 struct regcache *regcache
4740 = get_thread_arch_regcache (ptid, target_gdbarch);
4745 VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
4747 regcache_raw_supply (regcache, reg->num, reg->data);
4748 VEC_free (cached_reg_t, stop_reply->regcache);
4751 remote_stopped_by_watchpoint_p = stop_reply->stopped_by_watchpoint_p;
4752 remote_watch_data_address = stop_reply->watch_data_address;
4754 remote_notice_new_inferior (ptid, 0);
4757 stop_reply_xfree (stop_reply);
4761 /* The non-stop mode version of target_wait. */
4764 remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
4766 struct remote_state *rs = get_remote_state ();
4767 struct stop_reply *stop_reply;
4770 /* If in non-stop mode, get out of getpkt even if a
4771 notification is received. */
4773 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
4780 case 'E': /* Error of some sort. */
4781 /* We're out of sync with the target now. Did it continue
4782 or not? We can't tell which thread it was in non-stop,
4783 so just ignore this. */
4784 warning (_("Remote failure reply: %s"), rs->buf);
4786 case 'O': /* Console output. */
4787 remote_console_output (rs->buf + 1);
4790 warning (_("Invalid remote reply: %s"), rs->buf);
4794 /* Acknowledge a pending stop reply that may have arrived in the
4796 if (pending_stop_reply != NULL)
4797 remote_get_pending_stop_replies ();
4799 /* If indeed we noticed a stop reply, we're done. */
4800 stop_reply = queued_stop_reply (ptid);
4801 if (stop_reply != NULL)
4802 return process_stop_reply (stop_reply, status);
4804 /* Still no event. If we're just polling for an event, then
4805 return to the event loop. */
4806 if (options & TARGET_WNOHANG)
4808 status->kind = TARGET_WAITKIND_IGNORE;
4809 return minus_one_ptid;
4812 /* Otherwise do a blocking wait. */
4813 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
4818 /* Wait until the remote machine stops, then return, storing status in
4819 STATUS just as `wait' would. */
4822 remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
4824 struct remote_state *rs = get_remote_state ();
4825 ptid_t event_ptid = null_ptid;
4827 struct stop_reply *stop_reply;
4831 status->kind = TARGET_WAITKIND_IGNORE;
4832 status->value.integer = 0;
4834 stop_reply = queued_stop_reply (ptid);
4835 if (stop_reply != NULL)
4836 return process_stop_reply (stop_reply, status);
4838 if (rs->cached_wait_status)
4839 /* Use the cached wait status, but only once. */
4840 rs->cached_wait_status = 0;
4845 if (!target_is_async_p ())
4847 ofunc = signal (SIGINT, remote_interrupt);
4848 /* If the user hit C-c before this packet, or between packets,
4849 pretend that it was hit right here. */
4853 remote_interrupt (SIGINT);
4857 /* FIXME: cagney/1999-09-27: If we're in async mode we should
4858 _never_ wait for ever -> test on target_is_async_p().
4859 However, before we do that we need to ensure that the caller
4860 knows how to take the target into/out of async mode. */
4861 ret = getpkt_sane (&rs->buf, &rs->buf_size, wait_forever_enabled_p);
4862 if (!target_is_async_p ())
4863 signal (SIGINT, ofunc);
4868 remote_stopped_by_watchpoint_p = 0;
4870 /* We got something. */
4871 rs->waiting_for_stop_reply = 0;
4873 /* Assume that the target has acknowledged Ctrl-C unless we receive
4874 an 'F' or 'O' packet. */
4875 if (buf[0] != 'F' && buf[0] != 'O')
4876 rs->ctrlc_pending_p = 0;
4880 case 'E': /* Error of some sort. */
4881 /* We're out of sync with the target now. Did it continue or
4882 not? Not is more likely, so report a stop. */
4883 warning (_("Remote failure reply: %s"), buf);
4884 status->kind = TARGET_WAITKIND_STOPPED;
4885 status->value.sig = TARGET_SIGNAL_0;
4887 case 'F': /* File-I/O request. */
4888 remote_fileio_request (buf, rs->ctrlc_pending_p);
4889 rs->ctrlc_pending_p = 0;
4891 case 'T': case 'S': case 'X': case 'W':
4893 struct stop_reply *stop_reply;
4894 struct cleanup *old_chain;
4896 stop_reply = stop_reply_xmalloc ();
4897 old_chain = make_cleanup (do_stop_reply_xfree, stop_reply);
4898 remote_parse_stop_reply (buf, stop_reply);
4899 discard_cleanups (old_chain);
4900 event_ptid = process_stop_reply (stop_reply, status);
4903 case 'O': /* Console output. */
4904 remote_console_output (buf + 1);
4906 /* The target didn't really stop; keep waiting. */
4907 rs->waiting_for_stop_reply = 1;
4911 if (last_sent_signal != TARGET_SIGNAL_0)
4913 /* Zero length reply means that we tried 'S' or 'C' and the
4914 remote system doesn't support it. */
4915 target_terminal_ours_for_output ();
4917 ("Can't send signals to this remote system. %s not sent.\n",
4918 target_signal_to_name (last_sent_signal));
4919 last_sent_signal = TARGET_SIGNAL_0;
4920 target_terminal_inferior ();
4922 strcpy ((char *) buf, last_sent_step ? "s" : "c");
4923 putpkt ((char *) buf);
4925 /* We just told the target to resume, so a stop reply is in
4927 rs->waiting_for_stop_reply = 1;
4930 /* else fallthrough */
4932 warning (_("Invalid remote reply: %s"), buf);
4934 rs->waiting_for_stop_reply = 1;
4938 if (status->kind == TARGET_WAITKIND_IGNORE)
4940 /* Nothing interesting happened. If we're doing a non-blocking
4941 poll, we're done. Otherwise, go back to waiting. */
4942 if (options & TARGET_WNOHANG)
4943 return minus_one_ptid;
4947 else if (status->kind != TARGET_WAITKIND_EXITED
4948 && status->kind != TARGET_WAITKIND_SIGNALLED)
4950 if (!ptid_equal (event_ptid, null_ptid))
4951 record_currthread (event_ptid);
4953 event_ptid = inferior_ptid;
4956 /* A process exit. Invalidate our notion of current thread. */
4957 record_currthread (minus_one_ptid);
4962 /* Wait until the remote machine stops, then return, storing status in
4963 STATUS just as `wait' would. */
4966 remote_wait (struct target_ops *ops,
4967 ptid_t ptid, struct target_waitstatus *status, int options)
4972 event_ptid = remote_wait_ns (ptid, status, options);
4974 event_ptid = remote_wait_as (ptid, status, options);
4976 if (target_can_async_p ())
4978 /* If there are are events left in the queue tell the event loop
4980 if (stop_reply_queue)
4981 mark_async_event_handler (remote_async_inferior_event_token);
4987 /* Fetch a single register using a 'p' packet. */
4990 fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
4992 struct remote_state *rs = get_remote_state ();
4994 char regp[MAX_REGISTER_SIZE];
4997 if (remote_protocol_packets[PACKET_p].support == PACKET_DISABLE)
5000 if (reg->pnum == -1)
5005 p += hexnumstr (p, reg->pnum);
5008 getpkt (&rs->buf, &rs->buf_size, 0);
5012 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
5016 case PACKET_UNKNOWN:
5019 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
5020 gdbarch_register_name (get_regcache_arch (regcache),
5025 /* If this register is unfetchable, tell the regcache. */
5028 regcache_raw_supply (regcache, reg->regnum, NULL);
5032 /* Otherwise, parse and supply the value. */
5038 error (_("fetch_register_using_p: early buf termination"));
5040 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
5043 regcache_raw_supply (regcache, reg->regnum, regp);
5047 /* Fetch the registers included in the target's 'g' packet. */
5050 send_g_packet (void)
5052 struct remote_state *rs = get_remote_state ();
5055 sprintf (rs->buf, "g");
5056 remote_send (&rs->buf, &rs->buf_size);
5058 /* We can get out of synch in various cases. If the first character
5059 in the buffer is not a hex character, assume that has happened
5060 and try to fetch another packet to read. */
5061 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
5062 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
5063 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
5064 && rs->buf[0] != 'x') /* New: unavailable register value. */
5067 fprintf_unfiltered (gdb_stdlog,
5068 "Bad register packet; fetching a new packet\n");
5069 getpkt (&rs->buf, &rs->buf_size, 0);
5072 buf_len = strlen (rs->buf);
5074 /* Sanity check the received packet. */
5075 if (buf_len % 2 != 0)
5076 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
5082 process_g_packet (struct regcache *regcache)
5084 struct gdbarch *gdbarch = get_regcache_arch (regcache);
5085 struct remote_state *rs = get_remote_state ();
5086 struct remote_arch_state *rsa = get_remote_arch_state ();
5091 buf_len = strlen (rs->buf);
5093 /* Further sanity checks, with knowledge of the architecture. */
5094 if (buf_len > 2 * rsa->sizeof_g_packet)
5095 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
5097 /* Save the size of the packet sent to us by the target. It is used
5098 as a heuristic when determining the max size of packets that the
5099 target can safely receive. */
5100 if (rsa->actual_register_packet_size == 0)
5101 rsa->actual_register_packet_size = buf_len;
5103 /* If this is smaller than we guessed the 'g' packet would be,
5104 update our records. A 'g' reply that doesn't include a register's
5105 value implies either that the register is not available, or that
5106 the 'p' packet must be used. */
5107 if (buf_len < 2 * rsa->sizeof_g_packet)
5109 rsa->sizeof_g_packet = buf_len / 2;
5111 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
5113 if (rsa->regs[i].pnum == -1)
5116 if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
5117 rsa->regs[i].in_g_packet = 0;
5119 rsa->regs[i].in_g_packet = 1;
5123 regs = alloca (rsa->sizeof_g_packet);
5125 /* Unimplemented registers read as all bits zero. */
5126 memset (regs, 0, rsa->sizeof_g_packet);
5128 /* Reply describes registers byte by byte, each byte encoded as two
5129 hex characters. Suck them all up, then supply them to the
5130 register cacheing/storage mechanism. */
5133 for (i = 0; i < rsa->sizeof_g_packet; i++)
5135 if (p[0] == 0 || p[1] == 0)
5136 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
5137 internal_error (__FILE__, __LINE__,
5138 "unexpected end of 'g' packet reply");
5140 if (p[0] == 'x' && p[1] == 'x')
5141 regs[i] = 0; /* 'x' */
5143 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
5149 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
5151 struct packet_reg *r = &rsa->regs[i];
5154 if (r->offset * 2 >= strlen (rs->buf))
5155 /* This shouldn't happen - we adjusted in_g_packet above. */
5156 internal_error (__FILE__, __LINE__,
5157 "unexpected end of 'g' packet reply");
5158 else if (rs->buf[r->offset * 2] == 'x')
5160 gdb_assert (r->offset * 2 < strlen (rs->buf));
5161 /* The register isn't available, mark it as such (at
5162 the same time setting the value to zero). */
5163 regcache_raw_supply (regcache, r->regnum, NULL);
5166 regcache_raw_supply (regcache, r->regnum,
5174 fetch_registers_using_g (struct regcache *regcache)
5177 process_g_packet (regcache);
5181 remote_fetch_registers (struct target_ops *ops,
5182 struct regcache *regcache, int regnum)
5184 struct remote_arch_state *rsa = get_remote_arch_state ();
5187 set_general_thread (inferior_ptid);
5191 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
5192 gdb_assert (reg != NULL);
5194 /* If this register might be in the 'g' packet, try that first -
5195 we are likely to read more than one register. If this is the
5196 first 'g' packet, we might be overly optimistic about its
5197 contents, so fall back to 'p'. */
5198 if (reg->in_g_packet)
5200 fetch_registers_using_g (regcache);
5201 if (reg->in_g_packet)
5205 if (fetch_register_using_p (regcache, reg))
5208 /* This register is not available. */
5209 regcache_raw_supply (regcache, reg->regnum, NULL);
5214 fetch_registers_using_g (regcache);
5216 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
5217 if (!rsa->regs[i].in_g_packet)
5218 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
5220 /* This register is not available. */
5221 regcache_raw_supply (regcache, i, NULL);
5225 /* Prepare to store registers. Since we may send them all (using a
5226 'G' request), we have to read out the ones we don't want to change
5230 remote_prepare_to_store (struct regcache *regcache)
5232 struct remote_arch_state *rsa = get_remote_arch_state ();
5234 gdb_byte buf[MAX_REGISTER_SIZE];
5236 /* Make sure the entire registers array is valid. */
5237 switch (remote_protocol_packets[PACKET_P].support)
5239 case PACKET_DISABLE:
5240 case PACKET_SUPPORT_UNKNOWN:
5241 /* Make sure all the necessary registers are cached. */
5242 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
5243 if (rsa->regs[i].in_g_packet)
5244 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
5251 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
5252 packet was not recognized. */
5255 store_register_using_P (const struct regcache *regcache,
5256 struct packet_reg *reg)
5258 struct gdbarch *gdbarch = get_regcache_arch (regcache);
5259 struct remote_state *rs = get_remote_state ();
5260 /* Try storing a single register. */
5261 char *buf = rs->buf;
5262 gdb_byte regp[MAX_REGISTER_SIZE];
5265 if (remote_protocol_packets[PACKET_P].support == PACKET_DISABLE)
5268 if (reg->pnum == -1)
5271 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
5272 p = buf + strlen (buf);
5273 regcache_raw_collect (regcache, reg->regnum, regp);
5274 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
5276 getpkt (&rs->buf, &rs->buf_size, 0);
5278 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
5283 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
5284 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
5285 case PACKET_UNKNOWN:
5288 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
5292 /* Store register REGNUM, or all registers if REGNUM == -1, from the
5293 contents of the register cache buffer. FIXME: ignores errors. */
5296 store_registers_using_G (const struct regcache *regcache)
5298 struct remote_state *rs = get_remote_state ();
5299 struct remote_arch_state *rsa = get_remote_arch_state ();
5303 /* Extract all the registers in the regcache copying them into a
5307 regs = alloca (rsa->sizeof_g_packet);
5308 memset (regs, 0, rsa->sizeof_g_packet);
5309 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
5311 struct packet_reg *r = &rsa->regs[i];
5313 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
5317 /* Command describes registers byte by byte,
5318 each byte encoded as two hex characters. */
5321 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
5323 bin2hex (regs, p, rsa->sizeof_g_packet);
5325 getpkt (&rs->buf, &rs->buf_size, 0);
5326 if (packet_check_result (rs->buf) == PACKET_ERROR)
5327 error (_("Could not write registers; remote failure reply '%s'"),
5331 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
5332 of the register cache buffer. FIXME: ignores errors. */
5335 remote_store_registers (struct target_ops *ops,
5336 struct regcache *regcache, int regnum)
5338 struct remote_arch_state *rsa = get_remote_arch_state ();
5341 set_general_thread (inferior_ptid);
5345 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
5346 gdb_assert (reg != NULL);
5348 /* Always prefer to store registers using the 'P' packet if
5349 possible; we often change only a small number of registers.
5350 Sometimes we change a larger number; we'd need help from a
5351 higher layer to know to use 'G'. */
5352 if (store_register_using_P (regcache, reg))
5355 /* For now, don't complain if we have no way to write the
5356 register. GDB loses track of unavailable registers too
5357 easily. Some day, this may be an error. We don't have
5358 any way to read the register, either... */
5359 if (!reg->in_g_packet)
5362 store_registers_using_G (regcache);
5366 store_registers_using_G (regcache);
5368 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
5369 if (!rsa->regs[i].in_g_packet)
5370 if (!store_register_using_P (regcache, &rsa->regs[i]))
5371 /* See above for why we do not issue an error here. */
5376 /* Return the number of hex digits in num. */
5379 hexnumlen (ULONGEST num)
5383 for (i = 0; num != 0; i++)
5389 /* Set BUF to the minimum number of hex digits representing NUM. */
5392 hexnumstr (char *buf, ULONGEST num)
5394 int len = hexnumlen (num);
5395 return hexnumnstr (buf, num, len);
5399 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
5402 hexnumnstr (char *buf, ULONGEST num, int width)
5408 for (i = width - 1; i >= 0; i--)
5410 buf[i] = "0123456789abcdef"[(num & 0xf)];
5417 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
5420 remote_address_masked (CORE_ADDR addr)
5422 int address_size = remote_address_size;
5423 /* If "remoteaddresssize" was not set, default to target address size. */
5425 address_size = gdbarch_addr_bit (target_gdbarch);
5427 if (address_size > 0
5428 && address_size < (sizeof (ULONGEST) * 8))
5430 /* Only create a mask when that mask can safely be constructed
5431 in a ULONGEST variable. */
5433 mask = (mask << address_size) - 1;
5439 /* Convert BUFFER, binary data at least LEN bytes long, into escaped
5440 binary data in OUT_BUF. Set *OUT_LEN to the length of the data
5441 encoded in OUT_BUF, and return the number of bytes in OUT_BUF
5442 (which may be more than *OUT_LEN due to escape characters). The
5443 total number of bytes in the output buffer will be at most
5447 remote_escape_output (const gdb_byte *buffer, int len,
5448 gdb_byte *out_buf, int *out_len,
5451 int input_index, output_index;
5454 for (input_index = 0; input_index < len; input_index++)
5456 gdb_byte b = buffer[input_index];
5458 if (b == '$' || b == '#' || b == '}')
5460 /* These must be escaped. */
5461 if (output_index + 2 > out_maxlen)
5463 out_buf[output_index++] = '}';
5464 out_buf[output_index++] = b ^ 0x20;
5468 if (output_index + 1 > out_maxlen)
5470 out_buf[output_index++] = b;
5474 *out_len = input_index;
5475 return output_index;
5478 /* Convert BUFFER, escaped data LEN bytes long, into binary data
5479 in OUT_BUF. Return the number of bytes written to OUT_BUF.
5480 Raise an error if the total number of bytes exceeds OUT_MAXLEN.
5482 This function reverses remote_escape_output. It allows more
5483 escaped characters than that function does, in particular because
5484 '*' must be escaped to avoid the run-length encoding processing
5485 in reading packets. */
5488 remote_unescape_input (const gdb_byte *buffer, int len,
5489 gdb_byte *out_buf, int out_maxlen)
5491 int input_index, output_index;
5496 for (input_index = 0; input_index < len; input_index++)
5498 gdb_byte b = buffer[input_index];
5500 if (output_index + 1 > out_maxlen)
5502 warning (_("Received too much data from remote target;"
5503 " ignoring overflow."));
5504 return output_index;
5509 out_buf[output_index++] = b ^ 0x20;
5515 out_buf[output_index++] = b;
5519 error (_("Unmatched escape character in target response."));
5521 return output_index;
5524 /* Determine whether the remote target supports binary downloading.
5525 This is accomplished by sending a no-op memory write of zero length
5526 to the target at the specified address. It does not suffice to send
5527 the whole packet, since many stubs strip the eighth bit and
5528 subsequently compute a wrong checksum, which causes real havoc with
5531 NOTE: This can still lose if the serial line is not eight-bit
5532 clean. In cases like this, the user should clear "remote
5536 check_binary_download (CORE_ADDR addr)
5538 struct remote_state *rs = get_remote_state ();
5540 switch (remote_protocol_packets[PACKET_X].support)
5542 case PACKET_DISABLE:
5546 case PACKET_SUPPORT_UNKNOWN:
5552 p += hexnumstr (p, (ULONGEST) addr);
5554 p += hexnumstr (p, (ULONGEST) 0);
5558 putpkt_binary (rs->buf, (int) (p - rs->buf));
5559 getpkt (&rs->buf, &rs->buf_size, 0);
5561 if (rs->buf[0] == '\0')
5564 fprintf_unfiltered (gdb_stdlog,
5565 "binary downloading NOT suppported by target\n");
5566 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
5571 fprintf_unfiltered (gdb_stdlog,
5572 "binary downloading suppported by target\n");
5573 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
5580 /* Write memory data directly to the remote machine.
5581 This does not inform the data cache; the data cache uses this.
5582 HEADER is the starting part of the packet.
5583 MEMADDR is the address in the remote memory space.
5584 MYADDR is the address of the buffer in our space.
5585 LEN is the number of bytes.
5586 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
5587 should send data as binary ('X'), or hex-encoded ('M').
5589 The function creates packet of the form
5590 <HEADER><ADDRESS>,<LENGTH>:<DATA>
5592 where encoding of <DATA> is termined by PACKET_FORMAT.
5594 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
5597 Returns the number of bytes transferred, or 0 (setting errno) for
5598 error. Only transfer a single packet. */
5601 remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
5602 const gdb_byte *myaddr, int len,
5603 char packet_format, int use_length)
5605 struct remote_state *rs = get_remote_state ();
5615 if (packet_format != 'X' && packet_format != 'M')
5616 internal_error (__FILE__, __LINE__,
5617 "remote_write_bytes_aux: bad packet format");
5622 payload_size = get_memory_write_packet_size ();
5624 /* The packet buffer will be large enough for the payload;
5625 get_memory_packet_size ensures this. */
5628 /* Compute the size of the actual payload by subtracting out the
5629 packet header and footer overhead: "$M<memaddr>,<len>:...#nn".
5631 payload_size -= strlen ("$,:#NN");
5633 /* The comma won't be used. */
5635 header_length = strlen (header);
5636 payload_size -= header_length;
5637 payload_size -= hexnumlen (memaddr);
5639 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
5641 strcat (rs->buf, header);
5642 p = rs->buf + strlen (header);
5644 /* Compute a best guess of the number of bytes actually transfered. */
5645 if (packet_format == 'X')
5647 /* Best guess at number of bytes that will fit. */
5648 todo = min (len, payload_size);
5650 payload_size -= hexnumlen (todo);
5651 todo = min (todo, payload_size);
5655 /* Num bytes that will fit. */
5656 todo = min (len, payload_size / 2);
5658 payload_size -= hexnumlen (todo);
5659 todo = min (todo, payload_size / 2);
5663 internal_error (__FILE__, __LINE__,
5664 _("minumum packet size too small to write data"));
5666 /* If we already need another packet, then try to align the end
5667 of this packet to a useful boundary. */
5668 if (todo > 2 * REMOTE_ALIGN_WRITES && todo < len)
5669 todo = ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
5671 /* Append "<memaddr>". */
5672 memaddr = remote_address_masked (memaddr);
5673 p += hexnumstr (p, (ULONGEST) memaddr);
5680 /* Append <len>. Retain the location/size of <len>. It may need to
5681 be adjusted once the packet body has been created. */
5683 plenlen = hexnumstr (p, (ULONGEST) todo);
5691 /* Append the packet body. */
5692 if (packet_format == 'X')
5694 /* Binary mode. Send target system values byte by byte, in
5695 increasing byte addresses. Only escape certain critical
5697 payload_length = remote_escape_output (myaddr, todo, p, &nr_bytes,
5700 /* If not all TODO bytes fit, then we'll need another packet. Make
5701 a second try to keep the end of the packet aligned. Don't do
5702 this if the packet is tiny. */
5703 if (nr_bytes < todo && nr_bytes > 2 * REMOTE_ALIGN_WRITES)
5707 new_nr_bytes = (((memaddr + nr_bytes) & ~(REMOTE_ALIGN_WRITES - 1))
5709 if (new_nr_bytes != nr_bytes)
5710 payload_length = remote_escape_output (myaddr, new_nr_bytes,
5715 p += payload_length;
5716 if (use_length && nr_bytes < todo)
5718 /* Escape chars have filled up the buffer prematurely,
5719 and we have actually sent fewer bytes than planned.
5720 Fix-up the length field of the packet. Use the same
5721 number of characters as before. */
5722 plen += hexnumnstr (plen, (ULONGEST) nr_bytes, plenlen);
5723 *plen = ':'; /* overwrite \0 from hexnumnstr() */
5728 /* Normal mode: Send target system values byte by byte, in
5729 increasing byte addresses. Each byte is encoded as a two hex
5731 nr_bytes = bin2hex (myaddr, p, todo);
5735 putpkt_binary (rs->buf, (int) (p - rs->buf));
5736 getpkt (&rs->buf, &rs->buf_size, 0);
5738 if (rs->buf[0] == 'E')
5740 /* There is no correspondance between what the remote protocol
5741 uses for errors and errno codes. We would like a cleaner way
5742 of representing errors (big enough to include errno codes,
5743 bfd_error codes, and others). But for now just return EIO. */
5748 /* Return NR_BYTES, not TODO, in case escape chars caused us to send
5749 fewer bytes than we'd planned. */
5753 /* Write memory data directly to the remote machine.
5754 This does not inform the data cache; the data cache uses this.
5755 MEMADDR is the address in the remote memory space.
5756 MYADDR is the address of the buffer in our space.
5757 LEN is the number of bytes.
5759 Returns number of bytes transferred, or 0 (setting errno) for
5760 error. Only transfer a single packet. */
5763 remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, int len)
5765 char *packet_format = 0;
5767 /* Check whether the target supports binary download. */
5768 check_binary_download (memaddr);
5770 switch (remote_protocol_packets[PACKET_X].support)
5773 packet_format = "X";
5775 case PACKET_DISABLE:
5776 packet_format = "M";
5778 case PACKET_SUPPORT_UNKNOWN:
5779 internal_error (__FILE__, __LINE__,
5780 _("remote_write_bytes: bad internal state"));
5782 internal_error (__FILE__, __LINE__, _("bad switch"));
5785 return remote_write_bytes_aux (packet_format,
5786 memaddr, myaddr, len, packet_format[0], 1);
5789 /* Read memory data directly from the remote machine.
5790 This does not use the data cache; the data cache uses this.
5791 MEMADDR is the address in the remote memory space.
5792 MYADDR is the address of the buffer in our space.
5793 LEN is the number of bytes.
5795 Returns number of bytes transferred, or 0 for error. */
5797 /* NOTE: cagney/1999-10-18: This function (and its siblings in other
5798 remote targets) shouldn't attempt to read the entire buffer.
5799 Instead it should read a single packet worth of data and then
5800 return the byte size of that packet to the caller. The caller (its
5801 caller and its callers caller ;-) already contains code for
5802 handling partial reads. */
5805 remote_read_bytes (CORE_ADDR memaddr, gdb_byte *myaddr, int len)
5807 struct remote_state *rs = get_remote_state ();
5808 int max_buf_size; /* Max size of packet output buffer. */
5814 max_buf_size = get_memory_read_packet_size ();
5815 /* The packet buffer will be large enough for the payload;
5816 get_memory_packet_size ensures this. */
5825 todo = min (len, max_buf_size / 2); /* num bytes that will fit */
5827 /* construct "m"<memaddr>","<len>" */
5828 /* sprintf (rs->buf, "m%lx,%x", (unsigned long) memaddr, todo); */
5829 memaddr = remote_address_masked (memaddr);
5832 p += hexnumstr (p, (ULONGEST) memaddr);
5834 p += hexnumstr (p, (ULONGEST) todo);
5838 getpkt (&rs->buf, &rs->buf_size, 0);
5840 if (rs->buf[0] == 'E'
5841 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
5842 && rs->buf[3] == '\0')
5844 /* There is no correspondance between what the remote
5845 protocol uses for errors and errno codes. We would like
5846 a cleaner way of representing errors (big enough to
5847 include errno codes, bfd_error codes, and others). But
5848 for now just return EIO. */
5853 /* Reply describes memory byte by byte,
5854 each byte encoded as two hex characters. */
5857 if ((i = hex2bin (p, myaddr, todo)) < todo)
5859 /* Reply is short. This means that we were able to read
5860 only part of what we wanted to. */
5861 return i + (origlen - len);
5871 /* Remote notification handler. */
5874 handle_notification (char *buf, size_t length)
5876 if (strncmp (buf, "Stop:", 5) == 0)
5878 if (pending_stop_reply)
5879 /* We've already parsed the in-flight stop-reply, but the stub
5880 for some reason thought we didn't, possibly due to timeout
5881 on its side. Just ignore it. */
5885 struct cleanup *old_chain;
5886 struct stop_reply *reply = stop_reply_xmalloc ();
5887 old_chain = make_cleanup (do_stop_reply_xfree, reply);
5889 remote_parse_stop_reply (buf + 5, reply);
5891 discard_cleanups (old_chain);
5893 /* Be careful to only set it after parsing, since an error
5894 may be thrown then. */
5895 pending_stop_reply = reply;
5897 /* Notify the event loop there's a stop reply to acknowledge
5898 and that there may be more events to fetch. */
5899 mark_async_event_handler (remote_async_get_pending_events_token);
5903 /* We ignore notifications we don't recognize, for compatibility
5904 with newer stubs. */
5909 /* Read or write LEN bytes from inferior memory at MEMADDR,
5910 transferring to or from debugger address BUFFER. Write to inferior
5911 if SHOULD_WRITE is nonzero. Returns length of data written or
5912 read; 0 for error. TARGET is unused. */
5915 remote_xfer_memory (CORE_ADDR mem_addr, gdb_byte *buffer, int mem_len,
5916 int should_write, struct mem_attrib *attrib,
5917 struct target_ops *target)
5921 set_general_thread (inferior_ptid);
5924 res = remote_write_bytes (mem_addr, buffer, mem_len);
5926 res = remote_read_bytes (mem_addr, buffer, mem_len);
5931 /* Sends a packet with content determined by the printf format string
5932 FORMAT and the remaining arguments, then gets the reply. Returns
5933 whether the packet was a success, a failure, or unknown. */
5935 static enum packet_result
5936 remote_send_printf (const char *format, ...)
5938 struct remote_state *rs = get_remote_state ();
5939 int max_size = get_remote_packet_size ();
5942 va_start (ap, format);
5945 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
5946 internal_error (__FILE__, __LINE__, "Too long remote packet.");
5948 if (putpkt (rs->buf) < 0)
5949 error (_("Communication problem with target."));
5952 getpkt (&rs->buf, &rs->buf_size, 0);
5954 return packet_check_result (rs->buf);
5958 restore_remote_timeout (void *p)
5960 int value = *(int *)p;
5961 remote_timeout = value;
5964 /* Flash writing can take quite some time. We'll set
5965 effectively infinite timeout for flash operations.
5966 In future, we'll need to decide on a better approach. */
5967 static const int remote_flash_timeout = 1000;
5970 remote_flash_erase (struct target_ops *ops,
5971 ULONGEST address, LONGEST length)
5973 int addr_size = gdbarch_addr_bit (target_gdbarch) / 8;
5974 int saved_remote_timeout = remote_timeout;
5975 enum packet_result ret;
5977 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
5978 &saved_remote_timeout);
5979 remote_timeout = remote_flash_timeout;
5981 ret = remote_send_printf ("vFlashErase:%s,%s",
5982 phex (address, addr_size),
5986 case PACKET_UNKNOWN:
5987 error (_("Remote target does not support flash erase"));
5989 error (_("Error erasing flash with vFlashErase packet"));
5994 do_cleanups (back_to);
5998 remote_flash_write (struct target_ops *ops,
5999 ULONGEST address, LONGEST length,
6000 const gdb_byte *data)
6002 int saved_remote_timeout = remote_timeout;
6004 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
6005 &saved_remote_timeout);
6007 remote_timeout = remote_flash_timeout;
6008 ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length, 'X', 0);
6009 do_cleanups (back_to);
6015 remote_flash_done (struct target_ops *ops)
6017 int saved_remote_timeout = remote_timeout;
6019 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
6020 &saved_remote_timeout);
6022 remote_timeout = remote_flash_timeout;
6023 ret = remote_send_printf ("vFlashDone");
6024 do_cleanups (back_to);
6028 case PACKET_UNKNOWN:
6029 error (_("Remote target does not support vFlashDone"));
6031 error (_("Error finishing flash operation"));
6038 remote_files_info (struct target_ops *ignore)
6040 puts_filtered ("Debugging a target over a serial line.\n");
6043 /* Stuff for dealing with the packets which are part of this protocol.
6044 See comment at top of file for details. */
6046 /* Read a single character from the remote end. */
6049 readchar (int timeout)
6053 ch = serial_readchar (remote_desc, timeout);
6058 switch ((enum serial_rc) ch)
6062 error (_("Remote connection closed"));
6065 perror_with_name (_("Remote communication error"));
6067 case SERIAL_TIMEOUT:
6073 /* Send the command in *BUF to the remote machine, and read the reply
6074 into *BUF. Report an error if we get an error reply. Resize
6075 *BUF using xrealloc if necessary to hold the result, and update
6079 remote_send (char **buf,
6083 getpkt (buf, sizeof_buf, 0);
6085 if ((*buf)[0] == 'E')
6086 error (_("Remote failure reply: %s"), *buf);
6089 /* Return a pointer to an xmalloc'ed string representing an escaped
6090 version of BUF, of len N. E.g. \n is converted to \\n, \t to \\t,
6091 etc. The caller is responsible for releasing the returned
6095 escape_buffer (const char *buf, int n)
6097 struct cleanup *old_chain;
6098 struct ui_file *stb;
6101 stb = mem_fileopen ();
6102 old_chain = make_cleanup_ui_file_delete (stb);
6104 fputstrn_unfiltered (buf, n, 0, stb);
6105 str = ui_file_xstrdup (stb, NULL);
6106 do_cleanups (old_chain);
6110 /* Display a null-terminated packet on stdout, for debugging, using C
6114 print_packet (char *buf)
6116 puts_filtered ("\"");
6117 fputstr_filtered (buf, '"', gdb_stdout);
6118 puts_filtered ("\"");
6124 return putpkt_binary (buf, strlen (buf));
6127 /* Send a packet to the remote machine, with error checking. The data
6128 of the packet is in BUF. The string in BUF can be at most
6129 get_remote_packet_size () - 5 to account for the $, # and checksum,
6130 and for a possible /0 if we are debugging (remote_debug) and want
6131 to print the sent packet as a string. */
6134 putpkt_binary (char *buf, int cnt)
6136 struct remote_state *rs = get_remote_state ();
6138 unsigned char csum = 0;
6139 char *buf2 = alloca (cnt + 6);
6145 /* Catch cases like trying to read memory or listing threads while
6146 we're waiting for a stop reply. The remote server wouldn't be
6147 ready to handle this request, so we'd hang and timeout. We don't
6148 have to worry about this in synchronous mode, because in that
6149 case it's not possible to issue a command while the target is
6150 running. This is not a problem in non-stop mode, because in that
6151 case, the stub is always ready to process serial input. */
6152 if (!non_stop && target_can_async_p () && rs->waiting_for_stop_reply)
6153 error (_("Cannot execute this command while the target is running."));
6155 /* We're sending out a new packet. Make sure we don't look at a
6156 stale cached response. */
6157 rs->cached_wait_status = 0;
6159 /* Copy the packet into buffer BUF2, encapsulating it
6160 and giving it a checksum. */
6165 for (i = 0; i < cnt; i++)
6171 *p++ = tohex ((csum >> 4) & 0xf);
6172 *p++ = tohex (csum & 0xf);
6174 /* Send it over and over until we get a positive ack. */
6178 int started_error_output = 0;
6182 struct cleanup *old_chain;
6186 str = escape_buffer (buf2, p - buf2);
6187 old_chain = make_cleanup (xfree, str);
6188 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
6189 gdb_flush (gdb_stdlog);
6190 do_cleanups (old_chain);
6192 if (serial_write (remote_desc, buf2, p - buf2))
6193 perror_with_name (_("putpkt: write failed"));
6195 /* If this is a no acks version of the remote protocol, send the
6196 packet and move on. */
6200 /* Read until either a timeout occurs (-2) or '+' is read.
6201 Handle any notification that arrives in the mean time. */
6204 ch = readchar (remote_timeout);
6212 case SERIAL_TIMEOUT:
6215 if (started_error_output)
6217 putchar_unfiltered ('\n');
6218 started_error_output = 0;
6227 fprintf_unfiltered (gdb_stdlog, "Ack\n");
6231 fprintf_unfiltered (gdb_stdlog, "Nak\n");
6232 case SERIAL_TIMEOUT:
6236 break; /* Retransmit buffer. */
6240 fprintf_unfiltered (gdb_stdlog,
6241 "Packet instead of Ack, ignoring it\n");
6242 /* It's probably an old response sent because an ACK
6243 was lost. Gobble up the packet and ack it so it
6244 doesn't get retransmitted when we resend this
6247 serial_write (remote_desc, "+", 1);
6248 continue; /* Now, go look for +. */
6255 /* If we got a notification, handle it, and go back to looking
6257 /* We've found the start of a notification. Now
6258 collect the data. */
6259 val = read_frame (&rs->buf, &rs->buf_size);
6264 struct cleanup *old_chain;
6267 str = escape_buffer (rs->buf, val);
6268 old_chain = make_cleanup (xfree, str);
6269 fprintf_unfiltered (gdb_stdlog,
6270 " Notification received: %s\n",
6272 do_cleanups (old_chain);
6274 handle_notification (rs->buf, val);
6275 /* We're in sync now, rewait for the ack. */
6282 if (!started_error_output)
6284 started_error_output = 1;
6285 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
6287 fputc_unfiltered (ch & 0177, gdb_stdlog);
6288 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
6297 if (!started_error_output)
6299 started_error_output = 1;
6300 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
6302 fputc_unfiltered (ch & 0177, gdb_stdlog);
6306 break; /* Here to retransmit. */
6310 /* This is wrong. If doing a long backtrace, the user should be
6311 able to get out next time we call QUIT, without anything as
6312 violent as interrupt_query. If we want to provide a way out of
6313 here without getting to the next QUIT, it should be based on
6314 hitting ^C twice as in remote_wait. */
6325 /* Come here after finding the start of a frame when we expected an
6326 ack. Do our best to discard the rest of this packet. */
6335 c = readchar (remote_timeout);
6338 case SERIAL_TIMEOUT:
6339 /* Nothing we can do. */
6342 /* Discard the two bytes of checksum and stop. */
6343 c = readchar (remote_timeout);
6345 c = readchar (remote_timeout);
6348 case '*': /* Run length encoding. */
6349 /* Discard the repeat count. */
6350 c = readchar (remote_timeout);
6355 /* A regular character. */
6361 /* Come here after finding the start of the frame. Collect the rest
6362 into *BUF, verifying the checksum, length, and handling run-length
6363 compression. NUL terminate the buffer. If there is not enough room,
6364 expand *BUF using xrealloc.
6366 Returns -1 on error, number of characters in buffer (ignoring the
6367 trailing NULL) on success. (could be extended to return one of the
6368 SERIAL status indications). */
6371 read_frame (char **buf_p,
6378 struct remote_state *rs = get_remote_state ();
6385 c = readchar (remote_timeout);
6388 case SERIAL_TIMEOUT:
6390 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
6394 fputs_filtered ("Saw new packet start in middle of old one\n",
6396 return -1; /* Start a new packet, count retries. */
6399 unsigned char pktcsum;
6405 check_0 = readchar (remote_timeout);
6407 check_1 = readchar (remote_timeout);
6409 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
6412 fputs_filtered ("Timeout in checksum, retrying\n",
6416 else if (check_0 < 0 || check_1 < 0)
6419 fputs_filtered ("Communication error in checksum\n",
6424 /* Don't recompute the checksum; with no ack packets we
6425 don't have any way to indicate a packet retransmission
6430 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
6431 if (csum == pktcsum)
6436 struct cleanup *old_chain;
6439 str = escape_buffer (buf, bc);
6440 old_chain = make_cleanup (xfree, str);
6441 fprintf_unfiltered (gdb_stdlog,
6443 Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s\n",
6444 pktcsum, csum, str);
6445 do_cleanups (old_chain);
6447 /* Number of characters in buffer ignoring trailing
6451 case '*': /* Run length encoding. */
6456 c = readchar (remote_timeout);
6458 repeat = c - ' ' + 3; /* Compute repeat count. */
6460 /* The character before ``*'' is repeated. */
6462 if (repeat > 0 && repeat <= 255 && bc > 0)
6464 if (bc + repeat - 1 >= *sizeof_buf - 1)
6466 /* Make some more room in the buffer. */
6467 *sizeof_buf += repeat;
6468 *buf_p = xrealloc (*buf_p, *sizeof_buf);
6472 memset (&buf[bc], buf[bc - 1], repeat);
6478 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
6482 if (bc >= *sizeof_buf - 1)
6484 /* Make some more room in the buffer. */
6486 *buf_p = xrealloc (*buf_p, *sizeof_buf);
6497 /* Read a packet from the remote machine, with error checking, and
6498 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
6499 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
6500 rather than timing out; this is used (in synchronous mode) to wait
6501 for a target that is is executing user code to stop. */
6502 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
6503 don't have to change all the calls to getpkt to deal with the
6504 return value, because at the moment I don't know what the right
6505 thing to do it for those. */
6513 timed_out = getpkt_sane (buf, sizeof_buf, forever);
6517 /* Read a packet from the remote machine, with error checking, and
6518 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
6519 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
6520 rather than timing out; this is used (in synchronous mode) to wait
6521 for a target that is is executing user code to stop. If FOREVER ==
6522 0, this function is allowed to time out gracefully and return an
6523 indication of this to the caller. Otherwise return the number of
6524 bytes read. If EXPECTING_NOTIF, consider receiving a notification
6525 enough reason to return to the caller. */
6528 getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
6529 int expecting_notif)
6531 struct remote_state *rs = get_remote_state ();
6537 /* We're reading a new response. Make sure we don't look at a
6538 previously cached response. */
6539 rs->cached_wait_status = 0;
6541 strcpy (*buf, "timeout");
6544 timeout = watchdog > 0 ? watchdog : -1;
6545 else if (expecting_notif)
6546 timeout = 0; /* There should already be a char in the buffer. If
6549 timeout = remote_timeout;
6553 /* Process any number of notifications, and then return when
6557 /* If we get a timeout or bad checksm, retry up to MAX_TRIES
6559 for (tries = 1; tries <= MAX_TRIES; tries++)
6561 /* This can loop forever if the remote side sends us
6562 characters continuously, but if it pauses, we'll get
6563 SERIAL_TIMEOUT from readchar because of timeout. Then
6564 we'll count that as a retry.
6566 Note that even when forever is set, we will only wait
6567 forever prior to the start of a packet. After that, we
6568 expect characters to arrive at a brisk pace. They should
6569 show up within remote_timeout intervals. */
6571 c = readchar (timeout);
6572 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
6574 if (c == SERIAL_TIMEOUT)
6576 if (expecting_notif)
6577 return -1; /* Don't complain, it's normal to not get
6578 anything in this case. */
6580 if (forever) /* Watchdog went off? Kill the target. */
6584 error (_("Watchdog timeout has expired. Target detached."));
6587 fputs_filtered ("Timed out.\n", gdb_stdlog);
6591 /* We've found the start of a packet or notification.
6592 Now collect the data. */
6593 val = read_frame (buf, sizeof_buf);
6598 serial_write (remote_desc, "-", 1);
6601 if (tries > MAX_TRIES)
6603 /* We have tried hard enough, and just can't receive the
6604 packet/notification. Give up. */
6605 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
6607 /* Skip the ack char if we're in no-ack mode. */
6608 if (!rs->noack_mode)
6609 serial_write (remote_desc, "+", 1);
6613 /* If we got an ordinary packet, return that to our caller. */
6618 struct cleanup *old_chain;
6621 str = escape_buffer (*buf, val);
6622 old_chain = make_cleanup (xfree, str);
6623 fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
6624 do_cleanups (old_chain);
6627 /* Skip the ack char if we're in no-ack mode. */
6628 if (!rs->noack_mode)
6629 serial_write (remote_desc, "+", 1);
6633 /* If we got a notification, handle it, and go back to looking
6637 gdb_assert (c == '%');
6641 struct cleanup *old_chain;
6644 str = escape_buffer (*buf, val);
6645 old_chain = make_cleanup (xfree, str);
6646 fprintf_unfiltered (gdb_stdlog,
6647 " Notification received: %s\n",
6649 do_cleanups (old_chain);
6652 handle_notification (*buf, val);
6654 /* Notifications require no acknowledgement. */
6656 if (expecting_notif)
6663 getpkt_sane (char **buf, long *sizeof_buf, int forever)
6665 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0);
6669 getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever)
6671 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1);
6676 remote_kill (struct target_ops *ops)
6678 /* Use catch_errors so the user can quit from gdb even when we
6679 aren't on speaking terms with the remote system. */
6680 catch_errors ((catch_errors_ftype *) putpkt, "k", "", RETURN_MASK_ERROR);
6682 /* Don't wait for it to die. I'm not really sure it matters whether
6683 we do or not. For the existing stubs, kill is a noop. */
6684 target_mourn_inferior ();
6688 remote_vkill (int pid, struct remote_state *rs)
6690 if (remote_protocol_packets[PACKET_vKill].support == PACKET_DISABLE)
6693 /* Tell the remote target to detach. */
6694 sprintf (rs->buf, "vKill;%x", pid);
6696 getpkt (&rs->buf, &rs->buf_size, 0);
6698 if (packet_ok (rs->buf,
6699 &remote_protocol_packets[PACKET_vKill]) == PACKET_OK)
6701 else if (remote_protocol_packets[PACKET_vKill].support == PACKET_DISABLE)
6708 extended_remote_kill (struct target_ops *ops)
6711 int pid = ptid_get_pid (inferior_ptid);
6712 struct remote_state *rs = get_remote_state ();
6714 res = remote_vkill (pid, rs);
6715 if (res == -1 && !remote_multi_process_p (rs))
6717 /* Don't try 'k' on a multi-process aware stub -- it has no way
6718 to specify the pid. */
6722 getpkt (&rs->buf, &rs->buf_size, 0);
6723 if (rs->buf[0] != 'O' || rs->buf[0] != 'K')
6726 /* Don't wait for it to die. I'm not really sure it matters whether
6727 we do or not. For the existing stubs, kill is a noop. */
6733 error (_("Can't kill process"));
6735 target_mourn_inferior ();
6739 remote_mourn (struct target_ops *ops)
6741 remote_mourn_1 (ops);
6744 /* Worker function for remote_mourn. */
6746 remote_mourn_1 (struct target_ops *target)
6748 unpush_target (target);
6750 /* remote_close takes care of doing most of the clean up. */
6751 generic_mourn_inferior ();
6755 extended_remote_mourn_1 (struct target_ops *target)
6757 struct remote_state *rs = get_remote_state ();
6759 /* In case we got here due to an error, but we're going to stay
6761 rs->waiting_for_stop_reply = 0;
6763 /* We're no longer interested in these events. */
6764 discard_pending_stop_replies (ptid_get_pid (inferior_ptid));
6766 /* If the current general thread belonged to the process we just
6767 detached from or has exited, the remote side current general
6768 thread becomes undefined. Considering a case like this:
6770 - We just got here due to a detach.
6771 - The process that we're detaching from happens to immediately
6772 report a global breakpoint being hit in non-stop mode, in the
6773 same thread we had selected before.
6774 - GDB attaches to this process again.
6775 - This event happens to be the next event we handle.
6777 GDB would consider that the current general thread didn't need to
6778 be set on the stub side (with Hg), since for all it knew,
6779 GENERAL_THREAD hadn't changed.
6781 Notice that although in all-stop mode, the remote server always
6782 sets the current thread to the thread reporting the stop event,
6783 that doesn't happen in non-stop mode; in non-stop, the stub *must
6784 not* change the current thread when reporting a breakpoint hit,
6785 due to the decoupling of event reporting and event handling.
6787 To keep things simple, we always invalidate our notion of the
6789 record_currthread (minus_one_ptid);
6791 /* Unlike "target remote", we do not want to unpush the target; then
6792 the next time the user says "run", we won't be connected. */
6794 /* Call common code to mark the inferior as not running. */
6795 generic_mourn_inferior ();
6797 if (!have_inferiors ())
6799 if (!remote_multi_process_p (rs))
6801 /* Check whether the target is running now - some remote stubs
6802 automatically restart after kill. */
6804 getpkt (&rs->buf, &rs->buf_size, 0);
6806 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
6808 /* Assume that the target has been restarted. Set inferior_ptid
6809 so that bits of core GDB realizes there's something here, e.g.,
6810 so that the user can say "kill" again. */
6811 inferior_ptid = magic_null_ptid;
6818 extended_remote_mourn (struct target_ops *ops)
6820 extended_remote_mourn_1 (ops);
6824 extended_remote_run (char *args)
6826 struct remote_state *rs = get_remote_state ();
6829 /* If the user has disabled vRun support, or we have detected that
6830 support is not available, do not try it. */
6831 if (remote_protocol_packets[PACKET_vRun].support == PACKET_DISABLE)
6834 strcpy (rs->buf, "vRun;");
6835 len = strlen (rs->buf);
6837 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
6838 error (_("Remote file name too long for run packet"));
6839 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len, 0);
6841 gdb_assert (args != NULL);
6844 struct cleanup *back_to;
6848 argv = gdb_buildargv (args);
6849 back_to = make_cleanup ((void (*) (void *)) freeargv, argv);
6850 for (i = 0; argv[i] != NULL; i++)
6852 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
6853 error (_("Argument list too long for run packet"));
6854 rs->buf[len++] = ';';
6855 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len, 0);
6857 do_cleanups (back_to);
6860 rs->buf[len++] = '\0';
6863 getpkt (&rs->buf, &rs->buf_size, 0);
6865 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]) == PACKET_OK)
6867 /* We have a wait response; we don't need it, though. All is well. */
6870 else if (remote_protocol_packets[PACKET_vRun].support == PACKET_DISABLE)
6871 /* It wasn't disabled before, but it is now. */
6875 if (remote_exec_file[0] == '\0')
6876 error (_("Running the default executable on the remote target failed; "
6877 "try \"set remote exec-file\"?"));
6879 error (_("Running \"%s\" on the remote target failed"),
6884 /* In the extended protocol we want to be able to do things like
6885 "run" and have them basically work as expected. So we need
6886 a special create_inferior function. We support changing the
6887 executable file and the command line arguments, but not the
6891 extended_remote_create_inferior_1 (char *exec_file, char *args,
6892 char **env, int from_tty)
6894 /* If running asynchronously, register the target file descriptor
6895 with the event loop. */
6896 if (target_can_async_p ())
6897 target_async (inferior_event_handler, 0);
6899 /* Now restart the remote server. */
6900 if (extended_remote_run (args) == -1)
6902 /* vRun was not supported. Fail if we need it to do what the
6904 if (remote_exec_file[0])
6905 error (_("Remote target does not support \"set remote exec-file\""));
6907 error (_("Remote target does not support \"set args\" or run <ARGS>"));
6909 /* Fall back to "R". */
6910 extended_remote_restart ();
6913 if (!have_inferiors ())
6915 /* Clean up from the last time we ran, before we mark the target
6916 running again. This will mark breakpoints uninserted, and
6917 get_offsets may insert breakpoints. */
6918 init_thread_list ();
6919 init_wait_for_inferior ();
6922 /* Now mark the inferior as running before we do anything else. */
6923 inferior_ptid = magic_null_ptid;
6925 /* Now, if we have thread information, update inferior_ptid. */
6926 inferior_ptid = remote_current_thread (inferior_ptid);
6928 remote_add_inferior (ptid_get_pid (inferior_ptid), 0);
6929 add_thread_silent (inferior_ptid);
6931 /* Get updated offsets, if the stub uses qOffsets. */
6936 extended_remote_create_inferior (struct target_ops *ops,
6937 char *exec_file, char *args,
6938 char **env, int from_tty)
6940 extended_remote_create_inferior_1 (exec_file, args, env, from_tty);
6944 /* Insert a breakpoint. On targets that have software breakpoint
6945 support, we ask the remote target to do the work; on targets
6946 which don't, we insert a traditional memory breakpoint. */
6949 remote_insert_breakpoint (struct gdbarch *gdbarch,
6950 struct bp_target_info *bp_tgt)
6952 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
6953 If it succeeds, then set the support to PACKET_ENABLE. If it
6954 fails, and the user has explicitly requested the Z support then
6955 report an error, otherwise, mark it disabled and go on. */
6957 if (remote_protocol_packets[PACKET_Z0].support != PACKET_DISABLE)
6959 CORE_ADDR addr = bp_tgt->placed_address;
6960 struct remote_state *rs;
6964 gdbarch_breakpoint_from_pc (gdbarch, &addr, &bpsize);
6966 rs = get_remote_state ();
6972 addr = (ULONGEST) remote_address_masked (addr);
6973 p += hexnumstr (p, addr);
6974 sprintf (p, ",%d", bpsize);
6977 getpkt (&rs->buf, &rs->buf_size, 0);
6979 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
6984 bp_tgt->placed_address = addr;
6985 bp_tgt->placed_size = bpsize;
6987 case PACKET_UNKNOWN:
6992 return memory_insert_breakpoint (gdbarch, bp_tgt);
6996 remote_remove_breakpoint (struct gdbarch *gdbarch,
6997 struct bp_target_info *bp_tgt)
6999 CORE_ADDR addr = bp_tgt->placed_address;
7000 struct remote_state *rs = get_remote_state ();
7002 if (remote_protocol_packets[PACKET_Z0].support != PACKET_DISABLE)
7010 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
7011 p += hexnumstr (p, addr);
7012 sprintf (p, ",%d", bp_tgt->placed_size);
7015 getpkt (&rs->buf, &rs->buf_size, 0);
7017 return (rs->buf[0] == 'E');
7020 return memory_remove_breakpoint (gdbarch, bp_tgt);
7024 watchpoint_to_Z_packet (int type)
7029 return Z_PACKET_WRITE_WP;
7032 return Z_PACKET_READ_WP;
7035 return Z_PACKET_ACCESS_WP;
7038 internal_error (__FILE__, __LINE__,
7039 _("hw_bp_to_z: bad watchpoint type %d"), type);
7044 remote_insert_watchpoint (CORE_ADDR addr, int len, int type)
7046 struct remote_state *rs = get_remote_state ();
7048 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
7050 if (remote_protocol_packets[PACKET_Z0 + packet].support == PACKET_DISABLE)
7053 sprintf (rs->buf, "Z%x,", packet);
7054 p = strchr (rs->buf, '\0');
7055 addr = remote_address_masked (addr);
7056 p += hexnumstr (p, (ULONGEST) addr);
7057 sprintf (p, ",%x", len);
7060 getpkt (&rs->buf, &rs->buf_size, 0);
7062 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
7065 case PACKET_UNKNOWN:
7070 internal_error (__FILE__, __LINE__,
7071 _("remote_insert_watchpoint: reached end of function"));
7076 remote_remove_watchpoint (CORE_ADDR addr, int len, int type)
7078 struct remote_state *rs = get_remote_state ();
7080 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
7082 if (remote_protocol_packets[PACKET_Z0 + packet].support == PACKET_DISABLE)
7085 sprintf (rs->buf, "z%x,", packet);
7086 p = strchr (rs->buf, '\0');
7087 addr = remote_address_masked (addr);
7088 p += hexnumstr (p, (ULONGEST) addr);
7089 sprintf (p, ",%x", len);
7091 getpkt (&rs->buf, &rs->buf_size, 0);
7093 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
7096 case PACKET_UNKNOWN:
7101 internal_error (__FILE__, __LINE__,
7102 _("remote_remove_watchpoint: reached end of function"));
7106 int remote_hw_watchpoint_limit = -1;
7107 int remote_hw_breakpoint_limit = -1;
7110 remote_check_watch_resources (int type, int cnt, int ot)
7112 if (type == bp_hardware_breakpoint)
7114 if (remote_hw_breakpoint_limit == 0)
7116 else if (remote_hw_breakpoint_limit < 0)
7118 else if (cnt <= remote_hw_breakpoint_limit)
7123 if (remote_hw_watchpoint_limit == 0)
7125 else if (remote_hw_watchpoint_limit < 0)
7129 else if (cnt <= remote_hw_watchpoint_limit)
7136 remote_stopped_by_watchpoint (void)
7138 return remote_stopped_by_watchpoint_p;
7142 remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
7145 if (remote_stopped_by_watchpoint ())
7147 *addr_p = remote_watch_data_address;
7156 remote_insert_hw_breakpoint (struct gdbarch *gdbarch,
7157 struct bp_target_info *bp_tgt)
7160 struct remote_state *rs;
7163 /* The length field should be set to the size of a breakpoint
7164 instruction, even though we aren't inserting one ourselves. */
7166 gdbarch_breakpoint_from_pc
7167 (gdbarch, &bp_tgt->placed_address, &bp_tgt->placed_size);
7169 if (remote_protocol_packets[PACKET_Z1].support == PACKET_DISABLE)
7172 rs = get_remote_state ();
7179 addr = remote_address_masked (bp_tgt->placed_address);
7180 p += hexnumstr (p, (ULONGEST) addr);
7181 sprintf (p, ",%x", bp_tgt->placed_size);
7184 getpkt (&rs->buf, &rs->buf_size, 0);
7186 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
7189 case PACKET_UNKNOWN:
7194 internal_error (__FILE__, __LINE__,
7195 _("remote_insert_hw_breakpoint: reached end of function"));
7200 remote_remove_hw_breakpoint (struct gdbarch *gdbarch,
7201 struct bp_target_info *bp_tgt)
7204 struct remote_state *rs = get_remote_state ();
7207 if (remote_protocol_packets[PACKET_Z1].support == PACKET_DISABLE)
7214 addr = remote_address_masked (bp_tgt->placed_address);
7215 p += hexnumstr (p, (ULONGEST) addr);
7216 sprintf (p, ",%x", bp_tgt->placed_size);
7219 getpkt (&rs->buf, &rs->buf_size, 0);
7221 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
7224 case PACKET_UNKNOWN:
7229 internal_error (__FILE__, __LINE__,
7230 _("remote_remove_hw_breakpoint: reached end of function"));
7233 /* Table used by the crc32 function to calcuate the checksum. */
7235 static unsigned long crc32_table[256] =
7238 static unsigned long
7239 crc32 (unsigned char *buf, int len, unsigned int crc)
7241 if (!crc32_table[1])
7243 /* Initialize the CRC table and the decoding table. */
7247 for (i = 0; i < 256; i++)
7249 for (c = i << 24, j = 8; j > 0; --j)
7250 c = c & 0x80000000 ? (c << 1) ^ 0x04c11db7 : (c << 1);
7257 crc = (crc << 8) ^ crc32_table[((crc >> 24) ^ *buf) & 255];
7263 /* compare-sections command
7265 With no arguments, compares each loadable section in the exec bfd
7266 with the same memory range on the target, and reports mismatches.
7267 Useful for verifying the image on the target against the exec file.
7268 Depends on the target understanding the new "qCRC:" request. */
7270 /* FIXME: cagney/1999-10-26: This command should be broken down into a
7271 target method (target verify memory) and generic version of the
7272 actual command. This will allow other high-level code (especially
7273 generic_load()) to make use of this target functionality. */
7276 compare_sections_command (char *args, int from_tty)
7278 struct remote_state *rs = get_remote_state ();
7280 unsigned long host_crc, target_crc;
7281 struct cleanup *old_chain;
7284 const char *sectname;
7291 error (_("command cannot be used without an exec file"));
7292 if (!current_target.to_shortname ||
7293 strcmp (current_target.to_shortname, "remote") != 0)
7294 error (_("command can only be used with remote target"));
7296 for (s = exec_bfd->sections; s; s = s->next)
7298 if (!(s->flags & SEC_LOAD))
7299 continue; /* skip non-loadable section */
7301 size = bfd_get_section_size (s);
7303 continue; /* skip zero-length section */
7305 sectname = bfd_get_section_name (exec_bfd, s);
7306 if (args && strcmp (args, sectname) != 0)
7307 continue; /* not the section selected by user */
7309 matched = 1; /* do this section */
7311 /* FIXME: assumes lma can fit into long. */
7312 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
7313 (long) lma, (long) size);
7316 /* Be clever; compute the host_crc before waiting for target
7318 sectdata = xmalloc (size);
7319 old_chain = make_cleanup (xfree, sectdata);
7320 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
7321 host_crc = crc32 ((unsigned char *) sectdata, size, 0xffffffff);
7323 getpkt (&rs->buf, &rs->buf_size, 0);
7324 if (rs->buf[0] == 'E')
7325 error (_("target memory fault, section %s, range %s -- %s"), sectname,
7326 paddress (target_gdbarch, lma),
7327 paddress (target_gdbarch, lma + size));
7328 if (rs->buf[0] != 'C')
7329 error (_("remote target does not support this operation"));
7331 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
7332 target_crc = target_crc * 16 + fromhex (*tmp);
7334 printf_filtered ("Section %s, range %s -- %s: ", sectname,
7335 paddress (target_gdbarch, lma),
7336 paddress (target_gdbarch, lma + size));
7337 if (host_crc == target_crc)
7338 printf_filtered ("matched.\n");
7341 printf_filtered ("MIS-MATCHED!\n");
7345 do_cleanups (old_chain);
7348 warning (_("One or more sections of the remote executable does not match\n\
7349 the loaded file\n"));
7350 if (args && !matched)
7351 printf_filtered (_("No loaded section named '%s'.\n"), args);
7354 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
7355 into remote target. The number of bytes written to the remote
7356 target is returned, or -1 for error. */
7359 remote_write_qxfer (struct target_ops *ops, const char *object_name,
7360 const char *annex, const gdb_byte *writebuf,
7361 ULONGEST offset, LONGEST len,
7362 struct packet_config *packet)
7366 struct remote_state *rs = get_remote_state ();
7367 int max_size = get_memory_write_packet_size ();
7369 if (packet->support == PACKET_DISABLE)
7372 /* Insert header. */
7373 i = snprintf (rs->buf, max_size,
7374 "qXfer:%s:write:%s:%s:",
7375 object_name, annex ? annex : "",
7376 phex_nz (offset, sizeof offset));
7377 max_size -= (i + 1);
7379 /* Escape as much data as fits into rs->buf. */
7380 buf_len = remote_escape_output
7381 (writebuf, len, (rs->buf + i), &max_size, max_size);
7383 if (putpkt_binary (rs->buf, i + buf_len) < 0
7384 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
7385 || packet_ok (rs->buf, packet) != PACKET_OK)
7388 unpack_varlen_hex (rs->buf, &n);
7392 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
7393 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
7394 number of bytes read is returned, or 0 for EOF, or -1 for error.
7395 The number of bytes read may be less than LEN without indicating an
7396 EOF. PACKET is checked and updated to indicate whether the remote
7397 target supports this object. */
7400 remote_read_qxfer (struct target_ops *ops, const char *object_name,
7402 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
7403 struct packet_config *packet)
7405 static char *finished_object;
7406 static char *finished_annex;
7407 static ULONGEST finished_offset;
7409 struct remote_state *rs = get_remote_state ();
7410 LONGEST i, n, packet_len;
7412 if (packet->support == PACKET_DISABLE)
7415 /* Check whether we've cached an end-of-object packet that matches
7417 if (finished_object)
7419 if (strcmp (object_name, finished_object) == 0
7420 && strcmp (annex ? annex : "", finished_annex) == 0
7421 && offset == finished_offset)
7424 /* Otherwise, we're now reading something different. Discard
7426 xfree (finished_object);
7427 xfree (finished_annex);
7428 finished_object = NULL;
7429 finished_annex = NULL;
7432 /* Request only enough to fit in a single packet. The actual data
7433 may not, since we don't know how much of it will need to be escaped;
7434 the target is free to respond with slightly less data. We subtract
7435 five to account for the response type and the protocol frame. */
7436 n = min (get_remote_packet_size () - 5, len);
7437 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
7438 object_name, annex ? annex : "",
7439 phex_nz (offset, sizeof offset),
7440 phex_nz (n, sizeof n));
7441 i = putpkt (rs->buf);
7446 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
7447 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
7450 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
7451 error (_("Unknown remote qXfer reply: %s"), rs->buf);
7453 /* 'm' means there is (or at least might be) more data after this
7454 batch. That does not make sense unless there's at least one byte
7455 of data in this reply. */
7456 if (rs->buf[0] == 'm' && packet_len == 1)
7457 error (_("Remote qXfer reply contained no data."));
7459 /* Got some data. */
7460 i = remote_unescape_input (rs->buf + 1, packet_len - 1, readbuf, n);
7462 /* 'l' is an EOF marker, possibly including a final block of data,
7463 or possibly empty. If we have the final block of a non-empty
7464 object, record this fact to bypass a subsequent partial read. */
7465 if (rs->buf[0] == 'l' && offset + i > 0)
7467 finished_object = xstrdup (object_name);
7468 finished_annex = xstrdup (annex ? annex : "");
7469 finished_offset = offset + i;
7476 remote_xfer_partial (struct target_ops *ops, enum target_object object,
7477 const char *annex, gdb_byte *readbuf,
7478 const gdb_byte *writebuf, ULONGEST offset, LONGEST len)
7480 struct remote_state *rs;
7485 set_general_thread (inferior_ptid);
7487 rs = get_remote_state ();
7489 /* Handle memory using the standard memory routines. */
7490 if (object == TARGET_OBJECT_MEMORY)
7495 /* If the remote target is connected but not running, we should
7496 pass this request down to a lower stratum (e.g. the executable
7498 if (!target_has_execution)
7501 if (writebuf != NULL)
7502 xfered = remote_write_bytes (offset, writebuf, len);
7504 xfered = remote_read_bytes (offset, readbuf, len);
7508 else if (xfered == 0 && errno == 0)
7514 /* Handle SPU memory using qxfer packets. */
7515 if (object == TARGET_OBJECT_SPU)
7518 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
7519 &remote_protocol_packets
7520 [PACKET_qXfer_spu_read]);
7522 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
7523 &remote_protocol_packets
7524 [PACKET_qXfer_spu_write]);
7527 /* Handle extra signal info using qxfer packets. */
7528 if (object == TARGET_OBJECT_SIGNAL_INFO)
7531 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
7532 &remote_protocol_packets
7533 [PACKET_qXfer_siginfo_read]);
7535 return remote_write_qxfer (ops, "siginfo", annex, writebuf, offset, len,
7536 &remote_protocol_packets
7537 [PACKET_qXfer_siginfo_write]);
7540 /* Only handle flash writes. */
7541 if (writebuf != NULL)
7547 case TARGET_OBJECT_FLASH:
7548 xfered = remote_flash_write (ops, offset, len, writebuf);
7552 else if (xfered == 0 && errno == 0)
7562 /* Map pre-existing objects onto letters. DO NOT do this for new
7563 objects!!! Instead specify new query packets. */
7566 case TARGET_OBJECT_AVR:
7570 case TARGET_OBJECT_AUXV:
7571 gdb_assert (annex == NULL);
7572 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
7573 &remote_protocol_packets[PACKET_qXfer_auxv]);
7575 case TARGET_OBJECT_AVAILABLE_FEATURES:
7576 return remote_read_qxfer
7577 (ops, "features", annex, readbuf, offset, len,
7578 &remote_protocol_packets[PACKET_qXfer_features]);
7580 case TARGET_OBJECT_LIBRARIES:
7581 return remote_read_qxfer
7582 (ops, "libraries", annex, readbuf, offset, len,
7583 &remote_protocol_packets[PACKET_qXfer_libraries]);
7585 case TARGET_OBJECT_MEMORY_MAP:
7586 gdb_assert (annex == NULL);
7587 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
7588 &remote_protocol_packets[PACKET_qXfer_memory_map]);
7590 case TARGET_OBJECT_OSDATA:
7591 /* Should only get here if we're connected. */
7592 gdb_assert (remote_desc);
7593 return remote_read_qxfer
7594 (ops, "osdata", annex, readbuf, offset, len,
7595 &remote_protocol_packets[PACKET_qXfer_osdata]);
7601 /* Note: a zero OFFSET and LEN can be used to query the minimum
7603 if (offset == 0 && len == 0)
7604 return (get_remote_packet_size ());
7605 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
7606 large enough let the caller deal with it. */
7607 if (len < get_remote_packet_size ())
7609 len = get_remote_packet_size ();
7611 /* Except for querying the minimum buffer size, target must be open. */
7613 error (_("remote query is only available after target open"));
7615 gdb_assert (annex != NULL);
7616 gdb_assert (readbuf != NULL);
7622 /* We used one buffer char for the remote protocol q command and
7623 another for the query type. As the remote protocol encapsulation
7624 uses 4 chars plus one extra in case we are debugging
7625 (remote_debug), we have PBUFZIZ - 7 left to pack the query
7628 while (annex[i] && (i < (get_remote_packet_size () - 8)))
7630 /* Bad caller may have sent forbidden characters. */
7631 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
7636 gdb_assert (annex[i] == '\0');
7638 i = putpkt (rs->buf);
7642 getpkt (&rs->buf, &rs->buf_size, 0);
7643 strcpy ((char *) readbuf, rs->buf);
7645 return strlen ((char *) readbuf);
7649 remote_search_memory (struct target_ops* ops,
7650 CORE_ADDR start_addr, ULONGEST search_space_len,
7651 const gdb_byte *pattern, ULONGEST pattern_len,
7652 CORE_ADDR *found_addrp)
7654 int addr_size = gdbarch_addr_bit (target_gdbarch) / 8;
7655 struct remote_state *rs = get_remote_state ();
7656 int max_size = get_memory_write_packet_size ();
7657 struct packet_config *packet =
7658 &remote_protocol_packets[PACKET_qSearch_memory];
7659 /* number of packet bytes used to encode the pattern,
7660 this could be more than PATTERN_LEN due to escape characters */
7661 int escaped_pattern_len;
7662 /* amount of pattern that was encodable in the packet */
7663 int used_pattern_len;
7666 ULONGEST found_addr;
7668 /* Don't go to the target if we don't have to.
7669 This is done before checking packet->support to avoid the possibility that
7670 a success for this edge case means the facility works in general. */
7671 if (pattern_len > search_space_len)
7673 if (pattern_len == 0)
7675 *found_addrp = start_addr;
7679 /* If we already know the packet isn't supported, fall back to the simple
7680 way of searching memory. */
7682 if (packet->support == PACKET_DISABLE)
7684 /* Target doesn't provided special support, fall back and use the
7685 standard support (copy memory and do the search here). */
7686 return simple_search_memory (ops, start_addr, search_space_len,
7687 pattern, pattern_len, found_addrp);
7690 /* Insert header. */
7691 i = snprintf (rs->buf, max_size,
7692 "qSearch:memory:%s;%s;",
7693 phex_nz (start_addr, addr_size),
7694 phex_nz (search_space_len, sizeof (search_space_len)));
7695 max_size -= (i + 1);
7697 /* Escape as much data as fits into rs->buf. */
7698 escaped_pattern_len =
7699 remote_escape_output (pattern, pattern_len, (rs->buf + i),
7700 &used_pattern_len, max_size);
7702 /* Bail if the pattern is too large. */
7703 if (used_pattern_len != pattern_len)
7704 error ("Pattern is too large to transmit to remote target.");
7706 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
7707 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
7708 || packet_ok (rs->buf, packet) != PACKET_OK)
7710 /* The request may not have worked because the command is not
7711 supported. If so, fall back to the simple way. */
7712 if (packet->support == PACKET_DISABLE)
7714 return simple_search_memory (ops, start_addr, search_space_len,
7715 pattern, pattern_len, found_addrp);
7720 if (rs->buf[0] == '0')
7722 else if (rs->buf[0] == '1')
7725 if (rs->buf[1] != ',')
7726 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
7727 unpack_varlen_hex (rs->buf + 2, &found_addr);
7728 *found_addrp = found_addr;
7731 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
7737 remote_rcmd (char *command,
7738 struct ui_file *outbuf)
7740 struct remote_state *rs = get_remote_state ();
7744 error (_("remote rcmd is only available after target open"));
7746 /* Send a NULL command across as an empty command. */
7747 if (command == NULL)
7750 /* The query prefix. */
7751 strcpy (rs->buf, "qRcmd,");
7752 p = strchr (rs->buf, '\0');
7754 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/) > get_remote_packet_size ())
7755 error (_("\"monitor\" command ``%s'' is too long."), command);
7757 /* Encode the actual command. */
7758 bin2hex ((gdb_byte *) command, p, 0);
7760 if (putpkt (rs->buf) < 0)
7761 error (_("Communication problem with target."));
7763 /* get/display the response */
7768 /* XXX - see also tracepoint.c:remote_get_noisy_reply(). */
7770 getpkt (&rs->buf, &rs->buf_size, 0);
7773 error (_("Target does not support this command."));
7774 if (buf[0] == 'O' && buf[1] != 'K')
7776 remote_console_output (buf + 1); /* 'O' message from stub. */
7779 if (strcmp (buf, "OK") == 0)
7781 if (strlen (buf) == 3 && buf[0] == 'E'
7782 && isdigit (buf[1]) && isdigit (buf[2]))
7784 error (_("Protocol error with Rcmd"));
7786 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
7788 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
7789 fputc_unfiltered (c, outbuf);
7795 static VEC(mem_region_s) *
7796 remote_memory_map (struct target_ops *ops)
7798 VEC(mem_region_s) *result = NULL;
7799 char *text = target_read_stralloc (¤t_target,
7800 TARGET_OBJECT_MEMORY_MAP, NULL);
7804 struct cleanup *back_to = make_cleanup (xfree, text);
7805 result = parse_memory_map (text);
7806 do_cleanups (back_to);
7813 packet_command (char *args, int from_tty)
7815 struct remote_state *rs = get_remote_state ();
7818 error (_("command can only be used with remote target"));
7821 error (_("remote-packet command requires packet text as argument"));
7823 puts_filtered ("sending: ");
7824 print_packet (args);
7825 puts_filtered ("\n");
7828 getpkt (&rs->buf, &rs->buf_size, 0);
7829 puts_filtered ("received: ");
7830 print_packet (rs->buf);
7831 puts_filtered ("\n");
7835 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
7837 static void display_thread_info (struct gdb_ext_thread_info *info);
7839 static void threadset_test_cmd (char *cmd, int tty);
7841 static void threadalive_test (char *cmd, int tty);
7843 static void threadlist_test_cmd (char *cmd, int tty);
7845 int get_and_display_threadinfo (threadref *ref);
7847 static void threadinfo_test_cmd (char *cmd, int tty);
7849 static int thread_display_step (threadref *ref, void *context);
7851 static void threadlist_update_test_cmd (char *cmd, int tty);
7853 static void init_remote_threadtests (void);
7855 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
7858 threadset_test_cmd (char *cmd, int tty)
7860 int sample_thread = SAMPLE_THREAD;
7862 printf_filtered (_("Remote threadset test\n"));
7863 set_general_thread (sample_thread);
7868 threadalive_test (char *cmd, int tty)
7870 int sample_thread = SAMPLE_THREAD;
7871 int pid = ptid_get_pid (inferior_ptid);
7872 ptid_t ptid = ptid_build (pid, 0, sample_thread);
7874 if (remote_thread_alive (ptid))
7875 printf_filtered ("PASS: Thread alive test\n");
7877 printf_filtered ("FAIL: Thread alive test\n");
7880 void output_threadid (char *title, threadref *ref);
7883 output_threadid (char *title, threadref *ref)
7887 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
7889 printf_filtered ("%s %s\n", title, (&hexid[0]));
7893 threadlist_test_cmd (char *cmd, int tty)
7896 threadref nextthread;
7897 int done, result_count;
7898 threadref threadlist[3];
7900 printf_filtered ("Remote Threadlist test\n");
7901 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
7902 &result_count, &threadlist[0]))
7903 printf_filtered ("FAIL: threadlist test\n");
7906 threadref *scan = threadlist;
7907 threadref *limit = scan + result_count;
7909 while (scan < limit)
7910 output_threadid (" thread ", scan++);
7915 display_thread_info (struct gdb_ext_thread_info *info)
7917 output_threadid ("Threadid: ", &info->threadid);
7918 printf_filtered ("Name: %s\n ", info->shortname);
7919 printf_filtered ("State: %s\n", info->display);
7920 printf_filtered ("other: %s\n\n", info->more_display);
7924 get_and_display_threadinfo (threadref *ref)
7928 struct gdb_ext_thread_info threadinfo;
7930 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
7931 | TAG_MOREDISPLAY | TAG_DISPLAY;
7932 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
7933 display_thread_info (&threadinfo);
7938 threadinfo_test_cmd (char *cmd, int tty)
7940 int athread = SAMPLE_THREAD;
7944 int_to_threadref (&thread, athread);
7945 printf_filtered ("Remote Threadinfo test\n");
7946 if (!get_and_display_threadinfo (&thread))
7947 printf_filtered ("FAIL cannot get thread info\n");
7951 thread_display_step (threadref *ref, void *context)
7953 /* output_threadid(" threadstep ",ref); *//* simple test */
7954 return get_and_display_threadinfo (ref);
7958 threadlist_update_test_cmd (char *cmd, int tty)
7960 printf_filtered ("Remote Threadlist update test\n");
7961 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
7965 init_remote_threadtests (void)
7967 add_com ("tlist", class_obscure, threadlist_test_cmd, _("\
7968 Fetch and print the remote list of thread identifiers, one pkt only"));
7969 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
7970 _("Fetch and display info about one thread"));
7971 add_com ("tset", class_obscure, threadset_test_cmd,
7972 _("Test setting to a different thread"));
7973 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
7974 _("Iterate through updating all remote thread info"));
7975 add_com ("talive", class_obscure, threadalive_test,
7976 _(" Remote thread alive test "));
7981 /* Convert a thread ID to a string. Returns the string in a static
7985 remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
7987 static char buf[64];
7988 struct remote_state *rs = get_remote_state ();
7990 if (ptid_is_pid (ptid))
7992 /* Printing an inferior target id. */
7994 /* When multi-process extensions are off, there's no way in the
7995 remote protocol to know the remote process id, if there's any
7996 at all. There's one exception --- when we're connected with
7997 target extended-remote, and we manually attached to a process
7998 with "attach PID". We don't record anywhere a flag that
7999 allows us to distinguish that case from the case of
8000 connecting with extended-remote and the stub already being
8001 attached to a process, and reporting yes to qAttached, hence
8002 no smart special casing here. */
8003 if (!remote_multi_process_p (rs))
8005 xsnprintf (buf, sizeof buf, "Remote target");
8009 return normal_pid_to_str (ptid);
8013 if (ptid_equal (magic_null_ptid, ptid))
8014 xsnprintf (buf, sizeof buf, "Thread <main>");
8015 else if (remote_multi_process_p (rs))
8016 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
8017 ptid_get_pid (ptid), ptid_get_tid (ptid));
8019 xsnprintf (buf, sizeof buf, "Thread %ld",
8020 ptid_get_tid (ptid));
8025 /* Get the address of the thread local variable in OBJFILE which is
8026 stored at OFFSET within the thread local storage for thread PTID. */
8029 remote_get_thread_local_address (struct target_ops *ops,
8030 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
8032 if (remote_protocol_packets[PACKET_qGetTLSAddr].support != PACKET_DISABLE)
8034 struct remote_state *rs = get_remote_state ();
8036 char *endp = rs->buf + get_remote_packet_size ();
8037 enum packet_result result;
8039 strcpy (p, "qGetTLSAddr:");
8041 p = write_ptid (p, endp, ptid);
8043 p += hexnumstr (p, offset);
8045 p += hexnumstr (p, lm);
8049 getpkt (&rs->buf, &rs->buf_size, 0);
8050 result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_qGetTLSAddr]);
8051 if (result == PACKET_OK)
8055 unpack_varlen_hex (rs->buf, &result);
8058 else if (result == PACKET_UNKNOWN)
8059 throw_error (TLS_GENERIC_ERROR,
8060 _("Remote target doesn't support qGetTLSAddr packet"));
8062 throw_error (TLS_GENERIC_ERROR,
8063 _("Remote target failed to process qGetTLSAddr request"));
8066 throw_error (TLS_GENERIC_ERROR,
8067 _("TLS not supported or disabled on this target"));
8072 /* Support for inferring a target description based on the current
8073 architecture and the size of a 'g' packet. While the 'g' packet
8074 can have any size (since optional registers can be left off the
8075 end), some sizes are easily recognizable given knowledge of the
8076 approximate architecture. */
8078 struct remote_g_packet_guess
8081 const struct target_desc *tdesc;
8083 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
8084 DEF_VEC_O(remote_g_packet_guess_s);
8086 struct remote_g_packet_data
8088 VEC(remote_g_packet_guess_s) *guesses;
8091 static struct gdbarch_data *remote_g_packet_data_handle;
8094 remote_g_packet_data_init (struct obstack *obstack)
8096 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
8100 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
8101 const struct target_desc *tdesc)
8103 struct remote_g_packet_data *data
8104 = gdbarch_data (gdbarch, remote_g_packet_data_handle);
8105 struct remote_g_packet_guess new_guess, *guess;
8108 gdb_assert (tdesc != NULL);
8111 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
8113 if (guess->bytes == bytes)
8114 internal_error (__FILE__, __LINE__,
8115 "Duplicate g packet description added for size %d",
8118 new_guess.bytes = bytes;
8119 new_guess.tdesc = tdesc;
8120 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
8123 /* Return 1 if remote_read_description would do anything on this target
8124 and architecture, 0 otherwise. */
8127 remote_read_description_p (struct target_ops *target)
8129 struct remote_g_packet_data *data
8130 = gdbarch_data (target_gdbarch, remote_g_packet_data_handle);
8132 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
8138 static const struct target_desc *
8139 remote_read_description (struct target_ops *target)
8141 struct remote_g_packet_data *data
8142 = gdbarch_data (target_gdbarch, remote_g_packet_data_handle);
8144 /* Do not try this during initial connection, when we do not know
8145 whether there is a running but stopped thread. */
8146 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
8149 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
8151 struct remote_g_packet_guess *guess;
8153 int bytes = send_g_packet ();
8156 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
8158 if (guess->bytes == bytes)
8159 return guess->tdesc;
8161 /* We discard the g packet. A minor optimization would be to
8162 hold on to it, and fill the register cache once we have selected
8163 an architecture, but it's too tricky to do safely. */
8169 /* Remote file transfer support. This is host-initiated I/O, not
8170 target-initiated; for target-initiated, see remote-fileio.c. */
8172 /* If *LEFT is at least the length of STRING, copy STRING to
8173 *BUFFER, update *BUFFER to point to the new end of the buffer, and
8174 decrease *LEFT. Otherwise raise an error. */
8177 remote_buffer_add_string (char **buffer, int *left, char *string)
8179 int len = strlen (string);
8182 error (_("Packet too long for target."));
8184 memcpy (*buffer, string, len);
8188 /* NUL-terminate the buffer as a convenience, if there is
8194 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
8195 *BUFFER, update *BUFFER to point to the new end of the buffer, and
8196 decrease *LEFT. Otherwise raise an error. */
8199 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
8202 if (2 * len > *left)
8203 error (_("Packet too long for target."));
8205 bin2hex (bytes, *buffer, len);
8209 /* NUL-terminate the buffer as a convenience, if there is
8215 /* If *LEFT is large enough, convert VALUE to hex and add it to
8216 *BUFFER, update *BUFFER to point to the new end of the buffer, and
8217 decrease *LEFT. Otherwise raise an error. */
8220 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
8222 int len = hexnumlen (value);
8225 error (_("Packet too long for target."));
8227 hexnumstr (*buffer, value);
8231 /* NUL-terminate the buffer as a convenience, if there is
8237 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
8238 value, *REMOTE_ERRNO to the remote error number or zero if none
8239 was included, and *ATTACHMENT to point to the start of the annex
8240 if any. The length of the packet isn't needed here; there may
8241 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
8243 Return 0 if the packet could be parsed, -1 if it could not. If
8244 -1 is returned, the other variables may not be initialized. */
8247 remote_hostio_parse_result (char *buffer, int *retcode,
8248 int *remote_errno, char **attachment)
8255 if (buffer[0] != 'F')
8259 *retcode = strtol (&buffer[1], &p, 16);
8260 if (errno != 0 || p == &buffer[1])
8263 /* Check for ",errno". */
8267 *remote_errno = strtol (p + 1, &p2, 16);
8268 if (errno != 0 || p + 1 == p2)
8273 /* Check for ";attachment". If there is no attachment, the
8274 packet should end here. */
8277 *attachment = p + 1;
8280 else if (*p == '\0')
8286 /* Send a prepared I/O packet to the target and read its response.
8287 The prepared packet is in the global RS->BUF before this function
8288 is called, and the answer is there when we return.
8290 COMMAND_BYTES is the length of the request to send, which may include
8291 binary data. WHICH_PACKET is the packet configuration to check
8292 before attempting a packet. If an error occurs, *REMOTE_ERRNO
8293 is set to the error number and -1 is returned. Otherwise the value
8294 returned by the function is returned.
8296 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
8297 attachment is expected; an error will be reported if there's a
8298 mismatch. If one is found, *ATTACHMENT will be set to point into
8299 the packet buffer and *ATTACHMENT_LEN will be set to the
8300 attachment's length. */
8303 remote_hostio_send_command (int command_bytes, int which_packet,
8304 int *remote_errno, char **attachment,
8305 int *attachment_len)
8307 struct remote_state *rs = get_remote_state ();
8308 int ret, bytes_read;
8309 char *attachment_tmp;
8312 || remote_protocol_packets[which_packet].support == PACKET_DISABLE)
8314 *remote_errno = FILEIO_ENOSYS;
8318 putpkt_binary (rs->buf, command_bytes);
8319 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
8321 /* If it timed out, something is wrong. Don't try to parse the
8325 *remote_errno = FILEIO_EINVAL;
8329 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
8332 *remote_errno = FILEIO_EINVAL;
8334 case PACKET_UNKNOWN:
8335 *remote_errno = FILEIO_ENOSYS;
8341 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
8344 *remote_errno = FILEIO_EINVAL;
8348 /* Make sure we saw an attachment if and only if we expected one. */
8349 if ((attachment_tmp == NULL && attachment != NULL)
8350 || (attachment_tmp != NULL && attachment == NULL))
8352 *remote_errno = FILEIO_EINVAL;
8356 /* If an attachment was found, it must point into the packet buffer;
8357 work out how many bytes there were. */
8358 if (attachment_tmp != NULL)
8360 *attachment = attachment_tmp;
8361 *attachment_len = bytes_read - (*attachment - rs->buf);
8367 /* Open FILENAME on the remote target, using FLAGS and MODE. Return a
8368 remote file descriptor, or -1 if an error occurs (and set
8372 remote_hostio_open (const char *filename, int flags, int mode,
8375 struct remote_state *rs = get_remote_state ();
8377 int left = get_remote_packet_size () - 1;
8379 remote_buffer_add_string (&p, &left, "vFile:open:");
8381 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
8383 remote_buffer_add_string (&p, &left, ",");
8385 remote_buffer_add_int (&p, &left, flags);
8386 remote_buffer_add_string (&p, &left, ",");
8388 remote_buffer_add_int (&p, &left, mode);
8390 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
8391 remote_errno, NULL, NULL);
8394 /* Write up to LEN bytes from WRITE_BUF to FD on the remote target.
8395 Return the number of bytes written, or -1 if an error occurs (and
8396 set *REMOTE_ERRNO). */
8399 remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
8400 ULONGEST offset, int *remote_errno)
8402 struct remote_state *rs = get_remote_state ();
8404 int left = get_remote_packet_size ();
8407 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
8409 remote_buffer_add_int (&p, &left, fd);
8410 remote_buffer_add_string (&p, &left, ",");
8412 remote_buffer_add_int (&p, &left, offset);
8413 remote_buffer_add_string (&p, &left, ",");
8415 p += remote_escape_output (write_buf, len, p, &out_len,
8416 get_remote_packet_size () - (p - rs->buf));
8418 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
8419 remote_errno, NULL, NULL);
8422 /* Read up to LEN bytes FD on the remote target into READ_BUF
8423 Return the number of bytes read, or -1 if an error occurs (and
8424 set *REMOTE_ERRNO). */
8427 remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
8428 ULONGEST offset, int *remote_errno)
8430 struct remote_state *rs = get_remote_state ();
8433 int left = get_remote_packet_size ();
8434 int ret, attachment_len;
8437 remote_buffer_add_string (&p, &left, "vFile:pread:");
8439 remote_buffer_add_int (&p, &left, fd);
8440 remote_buffer_add_string (&p, &left, ",");
8442 remote_buffer_add_int (&p, &left, len);
8443 remote_buffer_add_string (&p, &left, ",");
8445 remote_buffer_add_int (&p, &left, offset);
8447 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
8448 remote_errno, &attachment,
8454 read_len = remote_unescape_input (attachment, attachment_len,
8456 if (read_len != ret)
8457 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
8462 /* Close FD on the remote target. Return 0, or -1 if an error occurs
8463 (and set *REMOTE_ERRNO). */
8466 remote_hostio_close (int fd, int *remote_errno)
8468 struct remote_state *rs = get_remote_state ();
8470 int left = get_remote_packet_size () - 1;
8472 remote_buffer_add_string (&p, &left, "vFile:close:");
8474 remote_buffer_add_int (&p, &left, fd);
8476 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
8477 remote_errno, NULL, NULL);
8480 /* Unlink FILENAME on the remote target. Return 0, or -1 if an error
8481 occurs (and set *REMOTE_ERRNO). */
8484 remote_hostio_unlink (const char *filename, int *remote_errno)
8486 struct remote_state *rs = get_remote_state ();
8488 int left = get_remote_packet_size () - 1;
8490 remote_buffer_add_string (&p, &left, "vFile:unlink:");
8492 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
8495 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
8496 remote_errno, NULL, NULL);
8500 remote_fileio_errno_to_host (int errnum)
8524 case FILEIO_ENOTDIR:
8544 case FILEIO_ENAMETOOLONG:
8545 return ENAMETOOLONG;
8551 remote_hostio_error (int errnum)
8553 int host_error = remote_fileio_errno_to_host (errnum);
8555 if (host_error == -1)
8556 error (_("Unknown remote I/O error %d"), errnum);
8558 error (_("Remote I/O error: %s"), safe_strerror (host_error));
8562 remote_hostio_close_cleanup (void *opaque)
8564 int fd = *(int *) opaque;
8567 remote_hostio_close (fd, &remote_errno);
8572 remote_bfd_iovec_open (struct bfd *abfd, void *open_closure)
8574 const char *filename = bfd_get_filename (abfd);
8575 int fd, remote_errno;
8578 gdb_assert (remote_filename_p (filename));
8580 fd = remote_hostio_open (filename + 7, FILEIO_O_RDONLY, 0, &remote_errno);
8583 errno = remote_fileio_errno_to_host (remote_errno);
8584 bfd_set_error (bfd_error_system_call);
8588 stream = xmalloc (sizeof (int));
8594 remote_bfd_iovec_close (struct bfd *abfd, void *stream)
8596 int fd = *(int *)stream;
8601 /* Ignore errors on close; these may happen if the remote
8602 connection was already torn down. */
8603 remote_hostio_close (fd, &remote_errno);
8609 remote_bfd_iovec_pread (struct bfd *abfd, void *stream, void *buf,
8610 file_ptr nbytes, file_ptr offset)
8612 int fd = *(int *)stream;
8614 file_ptr pos, bytes;
8617 while (nbytes > pos)
8619 bytes = remote_hostio_pread (fd, (char *)buf + pos, nbytes - pos,
8620 offset + pos, &remote_errno);
8622 /* Success, but no bytes, means end-of-file. */
8626 errno = remote_fileio_errno_to_host (remote_errno);
8627 bfd_set_error (bfd_error_system_call);
8638 remote_bfd_iovec_stat (struct bfd *abfd, void *stream, struct stat *sb)
8640 /* FIXME: We should probably implement remote_hostio_stat. */
8641 sb->st_size = INT_MAX;
8646 remote_filename_p (const char *filename)
8648 return strncmp (filename, "remote:", 7) == 0;
8652 remote_bfd_open (const char *remote_file, const char *target)
8654 return bfd_openr_iovec (remote_file, target,
8655 remote_bfd_iovec_open, NULL,
8656 remote_bfd_iovec_pread,
8657 remote_bfd_iovec_close,
8658 remote_bfd_iovec_stat);
8662 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
8664 struct cleanup *back_to, *close_cleanup;
8665 int retcode, fd, remote_errno, bytes, io_size;
8668 int bytes_in_buffer;
8673 error (_("command can only be used with remote target"));
8675 file = fopen (local_file, "rb");
8677 perror_with_name (local_file);
8678 back_to = make_cleanup_fclose (file);
8680 fd = remote_hostio_open (remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
8682 0700, &remote_errno);
8684 remote_hostio_error (remote_errno);
8686 /* Send up to this many bytes at once. They won't all fit in the
8687 remote packet limit, so we'll transfer slightly fewer. */
8688 io_size = get_remote_packet_size ();
8689 buffer = xmalloc (io_size);
8690 make_cleanup (xfree, buffer);
8692 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
8694 bytes_in_buffer = 0;
8697 while (bytes_in_buffer || !saw_eof)
8701 bytes = fread (buffer + bytes_in_buffer, 1, io_size - bytes_in_buffer,
8706 error (_("Error reading %s."), local_file);
8709 /* EOF. Unless there is something still in the
8710 buffer from the last iteration, we are done. */
8712 if (bytes_in_buffer == 0)
8720 bytes += bytes_in_buffer;
8721 bytes_in_buffer = 0;
8723 retcode = remote_hostio_pwrite (fd, buffer, bytes, offset, &remote_errno);
8726 remote_hostio_error (remote_errno);
8727 else if (retcode == 0)
8728 error (_("Remote write of %d bytes returned 0!"), bytes);
8729 else if (retcode < bytes)
8731 /* Short write. Save the rest of the read data for the next
8733 bytes_in_buffer = bytes - retcode;
8734 memmove (buffer, buffer + retcode, bytes_in_buffer);
8740 discard_cleanups (close_cleanup);
8741 if (remote_hostio_close (fd, &remote_errno))
8742 remote_hostio_error (remote_errno);
8745 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
8746 do_cleanups (back_to);
8750 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
8752 struct cleanup *back_to, *close_cleanup;
8753 int fd, remote_errno, bytes, io_size;
8759 error (_("command can only be used with remote target"));
8761 fd = remote_hostio_open (remote_file, FILEIO_O_RDONLY, 0, &remote_errno);
8763 remote_hostio_error (remote_errno);
8765 file = fopen (local_file, "wb");
8767 perror_with_name (local_file);
8768 back_to = make_cleanup_fclose (file);
8770 /* Send up to this many bytes at once. They won't all fit in the
8771 remote packet limit, so we'll transfer slightly fewer. */
8772 io_size = get_remote_packet_size ();
8773 buffer = xmalloc (io_size);
8774 make_cleanup (xfree, buffer);
8776 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
8781 bytes = remote_hostio_pread (fd, buffer, io_size, offset, &remote_errno);
8783 /* Success, but no bytes, means end-of-file. */
8786 remote_hostio_error (remote_errno);
8790 bytes = fwrite (buffer, 1, bytes, file);
8792 perror_with_name (local_file);
8795 discard_cleanups (close_cleanup);
8796 if (remote_hostio_close (fd, &remote_errno))
8797 remote_hostio_error (remote_errno);
8800 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
8801 do_cleanups (back_to);
8805 remote_file_delete (const char *remote_file, int from_tty)
8807 int retcode, remote_errno;
8810 error (_("command can only be used with remote target"));
8812 retcode = remote_hostio_unlink (remote_file, &remote_errno);
8814 remote_hostio_error (remote_errno);
8817 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
8821 remote_put_command (char *args, int from_tty)
8823 struct cleanup *back_to;
8827 error_no_arg (_("file to put"));
8829 argv = gdb_buildargv (args);
8830 back_to = make_cleanup_freeargv (argv);
8831 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
8832 error (_("Invalid parameters to remote put"));
8834 remote_file_put (argv[0], argv[1], from_tty);
8836 do_cleanups (back_to);
8840 remote_get_command (char *args, int from_tty)
8842 struct cleanup *back_to;
8846 error_no_arg (_("file to get"));
8848 argv = gdb_buildargv (args);
8849 back_to = make_cleanup_freeargv (argv);
8850 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
8851 error (_("Invalid parameters to remote get"));
8853 remote_file_get (argv[0], argv[1], from_tty);
8855 do_cleanups (back_to);
8859 remote_delete_command (char *args, int from_tty)
8861 struct cleanup *back_to;
8865 error_no_arg (_("file to delete"));
8867 argv = gdb_buildargv (args);
8868 back_to = make_cleanup_freeargv (argv);
8869 if (argv[0] == NULL || argv[1] != NULL)
8870 error (_("Invalid parameters to remote delete"));
8872 remote_file_delete (argv[0], from_tty);
8874 do_cleanups (back_to);
8878 remote_command (char *args, int from_tty)
8880 help_list (remote_cmdlist, "remote ", -1, gdb_stdout);
8884 remote_can_execute_reverse (void)
8886 if (remote_protocol_packets[PACKET_bs].support == PACKET_ENABLE
8887 || remote_protocol_packets[PACKET_bc].support == PACKET_ENABLE)
8894 remote_supports_non_stop (void)
8900 remote_supports_multi_process (void)
8902 struct remote_state *rs = get_remote_state ();
8903 return remote_multi_process_p (rs);
8907 remote_supports_cond_tracepoints (void)
8909 struct remote_state *rs = get_remote_state ();
8910 return rs->cond_tracepoints;
8914 remote_supports_fast_tracepoints (void)
8916 struct remote_state *rs = get_remote_state ();
8917 return rs->fast_tracepoints;
8921 init_remote_ops (void)
8923 remote_ops.to_shortname = "remote";
8924 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
8926 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
8927 Specify the serial device it is connected to\n\
8928 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
8929 remote_ops.to_open = remote_open;
8930 remote_ops.to_close = remote_close;
8931 remote_ops.to_detach = remote_detach;
8932 remote_ops.to_disconnect = remote_disconnect;
8933 remote_ops.to_resume = remote_resume;
8934 remote_ops.to_wait = remote_wait;
8935 remote_ops.to_fetch_registers = remote_fetch_registers;
8936 remote_ops.to_store_registers = remote_store_registers;
8937 remote_ops.to_prepare_to_store = remote_prepare_to_store;
8938 remote_ops.deprecated_xfer_memory = remote_xfer_memory;
8939 remote_ops.to_files_info = remote_files_info;
8940 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
8941 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
8942 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
8943 remote_ops.to_stopped_data_address = remote_stopped_data_address;
8944 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
8945 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
8946 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
8947 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
8948 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
8949 remote_ops.to_kill = remote_kill;
8950 remote_ops.to_load = generic_load;
8951 remote_ops.to_mourn_inferior = remote_mourn;
8952 remote_ops.to_thread_alive = remote_thread_alive;
8953 remote_ops.to_find_new_threads = remote_threads_info;
8954 remote_ops.to_pid_to_str = remote_pid_to_str;
8955 remote_ops.to_extra_thread_info = remote_threads_extra_info;
8956 remote_ops.to_stop = remote_stop;
8957 remote_ops.to_xfer_partial = remote_xfer_partial;
8958 remote_ops.to_rcmd = remote_rcmd;
8959 remote_ops.to_log_command = serial_log_command;
8960 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
8961 remote_ops.to_stratum = process_stratum;
8962 remote_ops.to_has_all_memory = default_child_has_all_memory;
8963 remote_ops.to_has_memory = default_child_has_memory;
8964 remote_ops.to_has_stack = default_child_has_stack;
8965 remote_ops.to_has_registers = default_child_has_registers;
8966 remote_ops.to_has_execution = default_child_has_execution;
8967 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
8968 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
8969 remote_ops.to_magic = OPS_MAGIC;
8970 remote_ops.to_memory_map = remote_memory_map;
8971 remote_ops.to_flash_erase = remote_flash_erase;
8972 remote_ops.to_flash_done = remote_flash_done;
8973 remote_ops.to_read_description = remote_read_description;
8974 remote_ops.to_search_memory = remote_search_memory;
8975 remote_ops.to_can_async_p = remote_can_async_p;
8976 remote_ops.to_is_async_p = remote_is_async_p;
8977 remote_ops.to_async = remote_async;
8978 remote_ops.to_async_mask = remote_async_mask;
8979 remote_ops.to_terminal_inferior = remote_terminal_inferior;
8980 remote_ops.to_terminal_ours = remote_terminal_ours;
8981 remote_ops.to_supports_non_stop = remote_supports_non_stop;
8982 remote_ops.to_supports_multi_process = remote_supports_multi_process;
8985 /* Set up the extended remote vector by making a copy of the standard
8986 remote vector and adding to it. */
8989 init_extended_remote_ops (void)
8991 extended_remote_ops = remote_ops;
8993 extended_remote_ops.to_shortname = "extended-remote";
8994 extended_remote_ops.to_longname =
8995 "Extended remote serial target in gdb-specific protocol";
8996 extended_remote_ops.to_doc =
8997 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
8998 Specify the serial device it is connected to (e.g. /dev/ttya).";
8999 extended_remote_ops.to_open = extended_remote_open;
9000 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
9001 extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
9002 extended_remote_ops.to_detach = extended_remote_detach;
9003 extended_remote_ops.to_attach = extended_remote_attach;
9004 extended_remote_ops.to_kill = extended_remote_kill;
9008 remote_can_async_p (void)
9010 if (!target_async_permitted)
9011 /* We only enable async when the user specifically asks for it. */
9014 /* We're async whenever the serial device is. */
9015 return remote_async_mask_value && serial_can_async_p (remote_desc);
9019 remote_is_async_p (void)
9021 if (!target_async_permitted)
9022 /* We only enable async when the user specifically asks for it. */
9025 /* We're async whenever the serial device is. */
9026 return remote_async_mask_value && serial_is_async_p (remote_desc);
9029 /* Pass the SERIAL event on and up to the client. One day this code
9030 will be able to delay notifying the client of an event until the
9031 point where an entire packet has been received. */
9033 static void (*async_client_callback) (enum inferior_event_type event_type,
9035 static void *async_client_context;
9036 static serial_event_ftype remote_async_serial_handler;
9039 remote_async_serial_handler (struct serial *scb, void *context)
9041 /* Don't propogate error information up to the client. Instead let
9042 the client find out about the error by querying the target. */
9043 async_client_callback (INF_REG_EVENT, async_client_context);
9047 remote_async_inferior_event_handler (gdb_client_data data)
9049 inferior_event_handler (INF_REG_EVENT, NULL);
9053 remote_async_get_pending_events_handler (gdb_client_data data)
9055 remote_get_pending_stop_replies ();
9059 remote_async (void (*callback) (enum inferior_event_type event_type,
9060 void *context), void *context)
9062 if (remote_async_mask_value == 0)
9063 internal_error (__FILE__, __LINE__,
9064 _("Calling remote_async when async is masked"));
9066 if (callback != NULL)
9068 serial_async (remote_desc, remote_async_serial_handler, NULL);
9069 async_client_callback = callback;
9070 async_client_context = context;
9073 serial_async (remote_desc, NULL, NULL);
9077 remote_async_mask (int new_mask)
9079 int curr_mask = remote_async_mask_value;
9080 remote_async_mask_value = new_mask;
9085 set_remote_cmd (char *args, int from_tty)
9087 help_list (remote_set_cmdlist, "set remote ", -1, gdb_stdout);
9091 show_remote_cmd (char *args, int from_tty)
9093 /* We can't just use cmd_show_list here, because we want to skip
9094 the redundant "show remote Z-packet" and the legacy aliases. */
9095 struct cleanup *showlist_chain;
9096 struct cmd_list_element *list = remote_show_cmdlist;
9098 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
9099 for (; list != NULL; list = list->next)
9100 if (strcmp (list->name, "Z-packet") == 0)
9102 else if (list->type == not_set_cmd)
9103 /* Alias commands are exactly like the original, except they
9104 don't have the normal type. */
9108 struct cleanup *option_chain
9109 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
9110 ui_out_field_string (uiout, "name", list->name);
9111 ui_out_text (uiout, ": ");
9112 if (list->type == show_cmd)
9113 do_setshow_command ((char *) NULL, from_tty, list);
9115 cmd_func (list, NULL, from_tty);
9116 /* Close the tuple. */
9117 do_cleanups (option_chain);
9120 /* Close the tuple. */
9121 do_cleanups (showlist_chain);
9125 /* Function to be called whenever a new objfile (shlib) is detected. */
9127 remote_new_objfile (struct objfile *objfile)
9129 if (remote_desc != 0) /* Have a remote connection. */
9130 remote_check_symbols (objfile);
9134 _initialize_remote (void)
9136 struct remote_state *rs;
9137 struct cmd_list_element *cmd;
9140 /* architecture specific data */
9141 remote_gdbarch_data_handle =
9142 gdbarch_data_register_post_init (init_remote_state);
9143 remote_g_packet_data_handle =
9144 gdbarch_data_register_pre_init (remote_g_packet_data_init);
9146 /* Initialize the per-target state. At the moment there is only one
9147 of these, not one per target. Only one target is active at a
9148 time. The default buffer size is unimportant; it will be expanded
9149 whenever a larger buffer is needed. */
9150 rs = get_remote_state_raw ();
9152 rs->buf = xmalloc (rs->buf_size);
9155 add_target (&remote_ops);
9157 init_extended_remote_ops ();
9158 add_target (&extended_remote_ops);
9160 /* Hook into new objfile notification. */
9161 observer_attach_new_objfile (remote_new_objfile);
9163 /* Set up signal handlers. */
9164 sigint_remote_token =
9165 create_async_signal_handler (async_remote_interrupt, NULL);
9166 sigint_remote_twice_token =
9167 create_async_signal_handler (inferior_event_handler_wrapper, NULL);
9170 init_remote_threadtests ();
9173 /* set/show remote ... */
9175 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
9176 Remote protocol specific variables\n\
9177 Configure various remote-protocol specific variables such as\n\
9178 the packets being used"),
9179 &remote_set_cmdlist, "set remote ",
9180 0 /* allow-unknown */, &setlist);
9181 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
9182 Remote protocol specific variables\n\
9183 Configure various remote-protocol specific variables such as\n\
9184 the packets being used"),
9185 &remote_show_cmdlist, "show remote ",
9186 0 /* allow-unknown */, &showlist);
9188 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
9189 Compare section data on target to the exec file.\n\
9190 Argument is a single section name (default: all loaded sections)."),
9193 add_cmd ("packet", class_maintenance, packet_command, _("\
9194 Send an arbitrary packet to a remote target.\n\
9195 maintenance packet TEXT\n\
9196 If GDB is talking to an inferior via the GDB serial protocol, then\n\
9197 this command sends the string TEXT to the inferior, and displays the\n\
9198 response packet. GDB supplies the initial `$' character, and the\n\
9199 terminating `#' character and checksum."),
9202 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
9203 Set whether to send break if interrupted."), _("\
9204 Show whether to send break if interrupted."), _("\
9205 If set, a break, instead of a cntrl-c, is sent to the remote target."),
9206 set_remotebreak, show_remotebreak,
9207 &setlist, &showlist);
9208 cmd_name = "remotebreak";
9209 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
9210 deprecate_cmd (cmd, "set remote interrupt-sequence");
9211 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
9212 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
9213 deprecate_cmd (cmd, "show remote interrupt-sequence");
9215 add_setshow_enum_cmd ("interrupt-sequence", class_support,
9216 interrupt_sequence_modes, &interrupt_sequence_mode, _("\
9217 Set interrupt sequence to remote target."), _("\
9218 Show interrupt sequence to remote target."), _("\
9219 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
9220 NULL, show_interrupt_sequence,
9221 &remote_set_cmdlist,
9222 &remote_show_cmdlist);
9224 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
9225 &interrupt_on_connect, _("\
9226 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
9227 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
9228 If set, interrupt sequence is sent to remote target."),
9230 &remote_set_cmdlist, &remote_show_cmdlist);
9232 /* Install commands for configuring memory read/write packets. */
9234 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
9235 Set the maximum number of bytes per memory write packet (deprecated)."),
9237 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
9238 Show the maximum number of bytes per memory write packet (deprecated)."),
9240 add_cmd ("memory-write-packet-size", no_class,
9241 set_memory_write_packet_size, _("\
9242 Set the maximum number of bytes per memory-write packet.\n\
9243 Specify the number of bytes in a packet or 0 (zero) for the\n\
9244 default packet size. The actual limit is further reduced\n\
9245 dependent on the target. Specify ``fixed'' to disable the\n\
9246 further restriction and ``limit'' to enable that restriction."),
9247 &remote_set_cmdlist);
9248 add_cmd ("memory-read-packet-size", no_class,
9249 set_memory_read_packet_size, _("\
9250 Set the maximum number of bytes per memory-read packet.\n\
9251 Specify the number of bytes in a packet or 0 (zero) for the\n\
9252 default packet size. The actual limit is further reduced\n\
9253 dependent on the target. Specify ``fixed'' to disable the\n\
9254 further restriction and ``limit'' to enable that restriction."),
9255 &remote_set_cmdlist);
9256 add_cmd ("memory-write-packet-size", no_class,
9257 show_memory_write_packet_size,
9258 _("Show the maximum number of bytes per memory-write packet."),
9259 &remote_show_cmdlist);
9260 add_cmd ("memory-read-packet-size", no_class,
9261 show_memory_read_packet_size,
9262 _("Show the maximum number of bytes per memory-read packet."),
9263 &remote_show_cmdlist);
9265 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
9266 &remote_hw_watchpoint_limit, _("\
9267 Set the maximum number of target hardware watchpoints."), _("\
9268 Show the maximum number of target hardware watchpoints."), _("\
9269 Specify a negative limit for unlimited."),
9270 NULL, NULL, /* FIXME: i18n: The maximum number of target hardware watchpoints is %s. */
9271 &remote_set_cmdlist, &remote_show_cmdlist);
9272 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
9273 &remote_hw_breakpoint_limit, _("\
9274 Set the maximum number of target hardware breakpoints."), _("\
9275 Show the maximum number of target hardware breakpoints."), _("\
9276 Specify a negative limit for unlimited."),
9277 NULL, NULL, /* FIXME: i18n: The maximum number of target hardware breakpoints is %s. */
9278 &remote_set_cmdlist, &remote_show_cmdlist);
9280 add_setshow_integer_cmd ("remoteaddresssize", class_obscure,
9281 &remote_address_size, _("\
9282 Set the maximum size of the address (in bits) in a memory packet."), _("\
9283 Show the maximum size of the address (in bits) in a memory packet."), NULL,
9285 NULL, /* FIXME: i18n: */
9286 &setlist, &showlist);
9288 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
9289 "X", "binary-download", 1);
9291 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
9292 "vCont", "verbose-resume", 0);
9294 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
9295 "QPassSignals", "pass-signals", 0);
9297 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
9298 "qSymbol", "symbol-lookup", 0);
9300 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
9301 "P", "set-register", 1);
9303 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
9304 "p", "fetch-register", 1);
9306 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
9307 "Z0", "software-breakpoint", 0);
9309 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
9310 "Z1", "hardware-breakpoint", 0);
9312 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
9313 "Z2", "write-watchpoint", 0);
9315 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
9316 "Z3", "read-watchpoint", 0);
9318 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
9319 "Z4", "access-watchpoint", 0);
9321 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
9322 "qXfer:auxv:read", "read-aux-vector", 0);
9324 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
9325 "qXfer:features:read", "target-features", 0);
9327 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
9328 "qXfer:libraries:read", "library-info", 0);
9330 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
9331 "qXfer:memory-map:read", "memory-map", 0);
9333 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
9334 "qXfer:spu:read", "read-spu-object", 0);
9336 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
9337 "qXfer:spu:write", "write-spu-object", 0);
9339 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
9340 "qXfer:osdata:read", "osdata", 0);
9342 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
9343 "qXfer:siginfo:read", "read-siginfo-object", 0);
9345 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
9346 "qXfer:siginfo:write", "write-siginfo-object", 0);
9348 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
9349 "qGetTLSAddr", "get-thread-local-storage-address",
9352 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
9353 "bc", "reverse-continue", 0);
9355 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
9356 "bs", "reverse-step", 0);
9358 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
9359 "qSupported", "supported-packets", 0);
9361 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
9362 "qSearch:memory", "search-memory", 0);
9364 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
9365 "vFile:open", "hostio-open", 0);
9367 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
9368 "vFile:pread", "hostio-pread", 0);
9370 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
9371 "vFile:pwrite", "hostio-pwrite", 0);
9373 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
9374 "vFile:close", "hostio-close", 0);
9376 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
9377 "vFile:unlink", "hostio-unlink", 0);
9379 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
9380 "vAttach", "attach", 0);
9382 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
9385 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
9386 "QStartNoAckMode", "noack", 0);
9388 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
9389 "vKill", "kill", 0);
9391 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
9392 "qAttached", "query-attached", 0);
9394 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
9395 "ConditionalTracepoints", "conditional-tracepoints", 0);
9396 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
9397 "FastTracepoints", "fast-tracepoints", 0);
9399 /* Keep the old ``set remote Z-packet ...'' working. Each individual
9400 Z sub-packet has its own set and show commands, but users may
9401 have sets to this variable in their .gdbinit files (or in their
9403 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
9404 &remote_Z_packet_detect, _("\
9405 Set use of remote protocol `Z' packets"), _("\
9406 Show use of remote protocol `Z' packets "), _("\
9407 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
9409 set_remote_protocol_Z_packet_cmd,
9410 show_remote_protocol_Z_packet_cmd, /* FIXME: i18n: Use of remote protocol `Z' packets is %s. */
9411 &remote_set_cmdlist, &remote_show_cmdlist);
9413 add_prefix_cmd ("remote", class_files, remote_command, _("\
9414 Manipulate files on the remote system\n\
9415 Transfer files to and from the remote target system."),
9416 &remote_cmdlist, "remote ",
9417 0 /* allow-unknown */, &cmdlist);
9419 add_cmd ("put", class_files, remote_put_command,
9420 _("Copy a local file to the remote system."),
9423 add_cmd ("get", class_files, remote_get_command,
9424 _("Copy a remote file to the local system."),
9427 add_cmd ("delete", class_files, remote_delete_command,
9428 _("Delete a remote file."),
9431 remote_exec_file = xstrdup ("");
9432 add_setshow_string_noescape_cmd ("exec-file", class_files,
9433 &remote_exec_file, _("\
9434 Set the remote pathname for \"run\""), _("\
9435 Show the remote pathname for \"run\""), NULL, NULL, NULL,
9436 &remote_set_cmdlist, &remote_show_cmdlist);
9438 /* Eventually initialize fileio. See fileio.c */
9439 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
9441 /* Take advantage of the fact that the LWP field is not used, to tag
9442 special ptids with it set to != 0. */
9443 magic_null_ptid = ptid_build (42000, 1, -1);
9444 not_sent_ptid = ptid_build (42000, 1, -2);
9445 any_thread_ptid = ptid_build (42000, 1, 0);