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
5 Free Software Foundation, Inc.
7 This file is part of GDB.
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 3 of the License, or
12 (at your option) any later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with this program. If not, see <http://www.gnu.org/licenses/>. */
22 /* See the GDB User Guide for details of the GDB remote protocol. */
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"
63 #include "memory-map.h"
65 /* The size to align memory write packets, when practical. The protocol
66 does not guarantee any alignment, and gdb will generate short
67 writes and unaligned writes, but even as a best-effort attempt this
68 can improve bulk transfers. For instance, if a write is misaligned
69 relative to the target's data bus, the stub may need to make an extra
70 round trip fetching data from the target. This doesn't make a
71 huge difference, but it's easy to do, so we try to be helpful.
73 The alignment chosen is arbitrary; usually data bus width is
74 important here, not the possibly larger cache line size. */
75 enum { REMOTE_ALIGN_WRITES = 16 };
77 /* Prototypes for local functions. */
78 static void cleanup_sigint_signal_handler (void *dummy);
79 static void initialize_sigint_signal_handler (void);
80 static int getpkt_sane (char **buf, long *sizeof_buf, int forever);
82 static void handle_remote_sigint (int);
83 static void handle_remote_sigint_twice (int);
84 static void async_remote_interrupt (gdb_client_data);
85 void async_remote_interrupt_twice (gdb_client_data);
87 static void remote_files_info (struct target_ops *ignore);
89 static void remote_prepare_to_store (struct regcache *regcache);
91 static void remote_fetch_registers (struct regcache *regcache, int regno);
93 static void remote_resume (ptid_t ptid, int step,
94 enum target_signal siggnal);
95 static void remote_async_resume (ptid_t ptid, int step,
96 enum target_signal siggnal);
97 static void remote_open (char *name, int from_tty);
98 static void remote_async_open (char *name, int from_tty);
100 static void extended_remote_open (char *name, int from_tty);
101 static void extended_remote_async_open (char *name, int from_tty);
103 static void remote_open_1 (char *, int, struct target_ops *, int extended_p,
106 static void remote_close (int quitting);
108 static void remote_store_registers (struct regcache *regcache, int regno);
110 static void remote_mourn (void);
111 static void remote_async_mourn (void);
113 static void extended_remote_restart (void);
115 static void extended_remote_mourn (void);
117 static void remote_mourn_1 (struct target_ops *);
119 static void remote_send (char **buf, long *sizeof_buf_p);
121 static int readchar (int timeout);
123 static ptid_t remote_wait (ptid_t ptid,
124 struct target_waitstatus *status);
125 static ptid_t remote_async_wait (ptid_t ptid,
126 struct target_waitstatus *status);
128 static void remote_kill (void);
129 static void remote_async_kill (void);
131 static int tohex (int nib);
133 static void remote_detach (char *args, int from_tty);
135 static void remote_interrupt (int signo);
137 static void remote_interrupt_twice (int signo);
139 static void interrupt_query (void);
141 static void set_thread (int, int);
143 static int remote_thread_alive (ptid_t);
145 static void get_offsets (void);
147 static void skip_frame (void);
149 static long read_frame (char **buf_p, long *sizeof_buf);
151 static int hexnumlen (ULONGEST num);
153 static void init_remote_ops (void);
155 static void init_extended_remote_ops (void);
157 static void remote_stop (void);
159 static int ishex (int ch, int *val);
161 static int stubhex (int ch);
163 static int hexnumstr (char *, ULONGEST);
165 static int hexnumnstr (char *, ULONGEST, int);
167 static CORE_ADDR remote_address_masked (CORE_ADDR);
169 static void print_packet (char *);
171 static unsigned long crc32 (unsigned char *, int, unsigned int);
173 static void compare_sections_command (char *, int);
175 static void packet_command (char *, int);
177 static int stub_unpack_int (char *buff, int fieldlength);
179 static ptid_t remote_current_thread (ptid_t oldptid);
181 static void remote_find_new_threads (void);
183 static void record_currthread (int currthread);
185 static int fromhex (int a);
187 static int hex2bin (const char *hex, gdb_byte *bin, int count);
189 static int bin2hex (const gdb_byte *bin, char *hex, int count);
191 static int putpkt_binary (char *buf, int cnt);
193 static void check_binary_download (CORE_ADDR addr);
195 struct packet_config;
197 static void show_packet_config_cmd (struct packet_config *config);
199 static void update_packet_config (struct packet_config *config);
201 static void set_remote_protocol_packet_cmd (char *args, int from_tty,
202 struct cmd_list_element *c);
204 static void show_remote_protocol_packet_cmd (struct ui_file *file,
206 struct cmd_list_element *c,
209 void _initialize_remote (void);
213 static struct cmd_list_element *remote_cmdlist;
215 /* For "set remote" and "show remote". */
217 static struct cmd_list_element *remote_set_cmdlist;
218 static struct cmd_list_element *remote_show_cmdlist;
220 /* Description of the remote protocol state for the currently
221 connected target. This is per-target state, and independent of the
222 selected architecture. */
226 /* A buffer to use for incoming packets, and its current size. The
227 buffer is grown dynamically for larger incoming packets.
228 Outgoing packets may also be constructed in this buffer.
229 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
230 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
235 /* If we negotiated packet size explicitly (and thus can bypass
236 heuristics for the largest packet size that will not overflow
237 a buffer in the stub), this will be set to that packet size.
238 Otherwise zero, meaning to use the guessed size. */
239 long explicit_packet_size;
241 /* remote_wait is normally called when the target is running and
242 waits for a stop reply packet. But sometimes we need to call it
243 when the target is already stopped. We can send a "?" packet
244 and have remote_wait read the response. Or, if we already have
245 the response, we can stash it in BUF and tell remote_wait to
246 skip calling getpkt. This flag is set when BUF contains a
247 stop reply packet and the target is not waiting. */
248 int cached_wait_status;
251 /* This data could be associated with a target, but we do not always
252 have access to the current target when we need it, so for now it is
253 static. This will be fine for as long as only one target is in use
255 static struct remote_state remote_state;
257 static struct remote_state *
258 get_remote_state_raw (void)
260 return &remote_state;
263 /* Description of the remote protocol for a given architecture. */
267 long offset; /* Offset into G packet. */
268 long regnum; /* GDB's internal register number. */
269 LONGEST pnum; /* Remote protocol register number. */
270 int in_g_packet; /* Always part of G packet. */
271 /* long size in bytes; == register_size (current_gdbarch, regnum);
273 /* char *name; == gdbarch_register_name (current_gdbarch, regnum);
277 struct remote_arch_state
279 /* Description of the remote protocol registers. */
280 long sizeof_g_packet;
282 /* Description of the remote protocol registers indexed by REGNUM
283 (making an array gdbarch_num_regs in size). */
284 struct packet_reg *regs;
286 /* This is the size (in chars) of the first response to the ``g''
287 packet. It is used as a heuristic when determining the maximum
288 size of memory-read and memory-write packets. A target will
289 typically only reserve a buffer large enough to hold the ``g''
290 packet. The size does not include packet overhead (headers and
292 long actual_register_packet_size;
294 /* This is the maximum size (in chars) of a non read/write packet.
295 It is also used as a cap on the size of read/write packets. */
296 long remote_packet_size;
300 /* Handle for retreving the remote protocol data from gdbarch. */
301 static struct gdbarch_data *remote_gdbarch_data_handle;
303 static struct remote_arch_state *
304 get_remote_arch_state (void)
306 return gdbarch_data (current_gdbarch, remote_gdbarch_data_handle);
309 /* Fetch the global remote target state. */
311 static struct remote_state *
312 get_remote_state (void)
314 /* Make sure that the remote architecture state has been
315 initialized, because doing so might reallocate rs->buf. Any
316 function which calls getpkt also needs to be mindful of changes
317 to rs->buf, but this call limits the number of places which run
319 get_remote_arch_state ();
321 return get_remote_state_raw ();
325 compare_pnums (const void *lhs_, const void *rhs_)
327 const struct packet_reg * const *lhs = lhs_;
328 const struct packet_reg * const *rhs = rhs_;
330 if ((*lhs)->pnum < (*rhs)->pnum)
332 else if ((*lhs)->pnum == (*rhs)->pnum)
339 init_remote_state (struct gdbarch *gdbarch)
341 int regnum, num_remote_regs, offset;
342 struct remote_state *rs = get_remote_state_raw ();
343 struct remote_arch_state *rsa;
344 struct packet_reg **remote_regs;
346 rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
348 /* Use the architecture to build a regnum<->pnum table, which will be
349 1:1 unless a feature set specifies otherwise. */
350 rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
351 gdbarch_num_regs (gdbarch),
353 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
355 struct packet_reg *r = &rsa->regs[regnum];
357 if (register_size (gdbarch, regnum) == 0)
358 /* Do not try to fetch zero-sized (placeholder) registers. */
361 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
366 /* Define the g/G packet format as the contents of each register
367 with a remote protocol number, in order of ascending protocol
370 remote_regs = alloca (gdbarch_num_regs (gdbarch)
371 * sizeof (struct packet_reg *));
372 for (num_remote_regs = 0, regnum = 0;
373 regnum < gdbarch_num_regs (gdbarch);
375 if (rsa->regs[regnum].pnum != -1)
376 remote_regs[num_remote_regs++] = &rsa->regs[regnum];
378 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
381 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
383 remote_regs[regnum]->in_g_packet = 1;
384 remote_regs[regnum]->offset = offset;
385 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
388 /* Record the maximum possible size of the g packet - it may turn out
390 rsa->sizeof_g_packet = offset;
392 /* Default maximum number of characters in a packet body. Many
393 remote stubs have a hardwired buffer size of 400 bytes
394 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
395 as the maximum packet-size to ensure that the packet and an extra
396 NUL character can always fit in the buffer. This stops GDB
397 trashing stubs that try to squeeze an extra NUL into what is
398 already a full buffer (As of 1999-12-04 that was most stubs). */
399 rsa->remote_packet_size = 400 - 1;
401 /* This one is filled in when a ``g'' packet is received. */
402 rsa->actual_register_packet_size = 0;
404 /* Should rsa->sizeof_g_packet needs more space than the
405 default, adjust the size accordingly. Remember that each byte is
406 encoded as two characters. 32 is the overhead for the packet
407 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
408 (``$NN:G...#NN'') is a better guess, the below has been padded a
410 if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
411 rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
413 /* Make sure that the packet buffer is plenty big enough for
414 this architecture. */
415 if (rs->buf_size < rsa->remote_packet_size)
417 rs->buf_size = 2 * rsa->remote_packet_size;
418 rs->buf = xrealloc (rs->buf, rs->buf_size);
424 /* Return the current allowed size of a remote packet. This is
425 inferred from the current architecture, and should be used to
426 limit the length of outgoing packets. */
428 get_remote_packet_size (void)
430 struct remote_state *rs = get_remote_state ();
431 struct remote_arch_state *rsa = get_remote_arch_state ();
433 if (rs->explicit_packet_size)
434 return rs->explicit_packet_size;
436 return rsa->remote_packet_size;
439 static struct packet_reg *
440 packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
442 if (regnum < 0 && regnum >= gdbarch_num_regs (current_gdbarch))
446 struct packet_reg *r = &rsa->regs[regnum];
447 gdb_assert (r->regnum == regnum);
452 static struct packet_reg *
453 packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
456 for (i = 0; i < gdbarch_num_regs (current_gdbarch); i++)
458 struct packet_reg *r = &rsa->regs[i];
465 /* FIXME: graces/2002-08-08: These variables should eventually be
466 bound to an instance of the target object (as in gdbarch-tdep()),
467 when such a thing exists. */
469 /* This is set to the data address of the access causing the target
470 to stop for a watchpoint. */
471 static CORE_ADDR remote_watch_data_address;
473 /* This is non-zero if target stopped for a watchpoint. */
474 static int remote_stopped_by_watchpoint_p;
476 static struct target_ops remote_ops;
478 static struct target_ops extended_remote_ops;
480 /* Temporary target ops. Just like the remote_ops and
481 extended_remote_ops, but with asynchronous support. */
482 static struct target_ops remote_async_ops;
484 static int remote_async_mask_value = 1;
486 static struct target_ops extended_async_remote_ops;
488 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
489 ``forever'' still use the normal timeout mechanism. This is
490 currently used by the ASYNC code to guarentee that target reads
491 during the initial connect always time-out. Once getpkt has been
492 modified to return a timeout indication and, in turn
493 remote_wait()/wait_for_inferior() have gained a timeout parameter
495 static int wait_forever_enabled_p = 1;
498 /* This variable chooses whether to send a ^C or a break when the user
499 requests program interruption. Although ^C is usually what remote
500 systems expect, and that is the default here, sometimes a break is
501 preferable instead. */
503 static int remote_break;
505 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
506 remote_open knows that we don't have a file open when the program
508 static struct serial *remote_desc = NULL;
510 /* This variable sets the number of bits in an address that are to be
511 sent in a memory ("M" or "m") packet. Normally, after stripping
512 leading zeros, the entire address would be sent. This variable
513 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
514 initial implementation of remote.c restricted the address sent in
515 memory packets to ``host::sizeof long'' bytes - (typically 32
516 bits). Consequently, for 64 bit targets, the upper 32 bits of an
517 address was never sent. Since fixing this bug may cause a break in
518 some remote targets this variable is principly provided to
519 facilitate backward compatibility. */
521 static int remote_address_size;
523 /* Tempoary to track who currently owns the terminal. See
524 target_async_terminal_* for more details. */
526 static int remote_async_terminal_ours_p;
528 /* The executable file to use for "run" on the remote side. */
530 static char *remote_exec_file = "";
533 /* User configurable variables for the number of characters in a
534 memory read/write packet. MIN (rsa->remote_packet_size,
535 rsa->sizeof_g_packet) is the default. Some targets need smaller
536 values (fifo overruns, et.al.) and some users need larger values
537 (speed up transfers). The variables ``preferred_*'' (the user
538 request), ``current_*'' (what was actually set) and ``forced_*''
539 (Positive - a soft limit, negative - a hard limit). */
541 struct memory_packet_config
548 /* Compute the current size of a read/write packet. Since this makes
549 use of ``actual_register_packet_size'' the computation is dynamic. */
552 get_memory_packet_size (struct memory_packet_config *config)
554 struct remote_state *rs = get_remote_state ();
555 struct remote_arch_state *rsa = get_remote_arch_state ();
557 /* NOTE: The somewhat arbitrary 16k comes from the knowledge (folk
558 law?) that some hosts don't cope very well with large alloca()
559 calls. Eventually the alloca() code will be replaced by calls to
560 xmalloc() and make_cleanups() allowing this restriction to either
561 be lifted or removed. */
562 #ifndef MAX_REMOTE_PACKET_SIZE
563 #define MAX_REMOTE_PACKET_SIZE 16384
565 /* NOTE: 20 ensures we can write at least one byte. */
566 #ifndef MIN_REMOTE_PACKET_SIZE
567 #define MIN_REMOTE_PACKET_SIZE 20
572 if (config->size <= 0)
573 what_they_get = MAX_REMOTE_PACKET_SIZE;
575 what_they_get = config->size;
579 what_they_get = get_remote_packet_size ();
580 /* Limit the packet to the size specified by the user. */
582 && what_they_get > config->size)
583 what_they_get = config->size;
585 /* Limit it to the size of the targets ``g'' response unless we have
586 permission from the stub to use a larger packet size. */
587 if (rs->explicit_packet_size == 0
588 && rsa->actual_register_packet_size > 0
589 && what_they_get > rsa->actual_register_packet_size)
590 what_they_get = rsa->actual_register_packet_size;
592 if (what_they_get > MAX_REMOTE_PACKET_SIZE)
593 what_they_get = MAX_REMOTE_PACKET_SIZE;
594 if (what_they_get < MIN_REMOTE_PACKET_SIZE)
595 what_they_get = MIN_REMOTE_PACKET_SIZE;
597 /* Make sure there is room in the global buffer for this packet
598 (including its trailing NUL byte). */
599 if (rs->buf_size < what_they_get + 1)
601 rs->buf_size = 2 * what_they_get;
602 rs->buf = xrealloc (rs->buf, 2 * what_they_get);
605 return what_they_get;
608 /* Update the size of a read/write packet. If they user wants
609 something really big then do a sanity check. */
612 set_memory_packet_size (char *args, struct memory_packet_config *config)
614 int fixed_p = config->fixed_p;
615 long size = config->size;
617 error (_("Argument required (integer, `fixed' or `limited')."));
618 else if (strcmp (args, "hard") == 0
619 || strcmp (args, "fixed") == 0)
621 else if (strcmp (args, "soft") == 0
622 || strcmp (args, "limit") == 0)
627 size = strtoul (args, &end, 0);
629 error (_("Invalid %s (bad syntax)."), config->name);
631 /* Instead of explicitly capping the size of a packet to
632 MAX_REMOTE_PACKET_SIZE or dissallowing it, the user is
633 instead allowed to set the size to something arbitrarily
635 if (size > MAX_REMOTE_PACKET_SIZE)
636 error (_("Invalid %s (too large)."), config->name);
640 if (fixed_p && !config->fixed_p)
642 if (! query (_("The target may not be able to correctly handle a %s\n"
643 "of %ld bytes. Change the packet size? "),
645 error (_("Packet size not changed."));
647 /* Update the config. */
648 config->fixed_p = fixed_p;
653 show_memory_packet_size (struct memory_packet_config *config)
655 printf_filtered (_("The %s is %ld. "), config->name, config->size);
657 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
658 get_memory_packet_size (config));
660 printf_filtered (_("Packets are limited to %ld bytes.\n"),
661 get_memory_packet_size (config));
664 static struct memory_packet_config memory_write_packet_config =
666 "memory-write-packet-size",
670 set_memory_write_packet_size (char *args, int from_tty)
672 set_memory_packet_size (args, &memory_write_packet_config);
676 show_memory_write_packet_size (char *args, int from_tty)
678 show_memory_packet_size (&memory_write_packet_config);
682 get_memory_write_packet_size (void)
684 return get_memory_packet_size (&memory_write_packet_config);
687 static struct memory_packet_config memory_read_packet_config =
689 "memory-read-packet-size",
693 set_memory_read_packet_size (char *args, int from_tty)
695 set_memory_packet_size (args, &memory_read_packet_config);
699 show_memory_read_packet_size (char *args, int from_tty)
701 show_memory_packet_size (&memory_read_packet_config);
705 get_memory_read_packet_size (void)
707 long size = get_memory_packet_size (&memory_read_packet_config);
708 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
709 extra buffer size argument before the memory read size can be
710 increased beyond this. */
711 if (size > get_remote_packet_size ())
712 size = get_remote_packet_size ();
717 /* Generic configuration support for packets the stub optionally
718 supports. Allows the user to specify the use of the packet as well
719 as allowing GDB to auto-detect support in the remote stub. */
723 PACKET_SUPPORT_UNKNOWN = 0,
732 enum auto_boolean detect;
733 enum packet_support support;
736 /* Analyze a packet's return value and update the packet config
747 update_packet_config (struct packet_config *config)
749 switch (config->detect)
751 case AUTO_BOOLEAN_TRUE:
752 config->support = PACKET_ENABLE;
754 case AUTO_BOOLEAN_FALSE:
755 config->support = PACKET_DISABLE;
757 case AUTO_BOOLEAN_AUTO:
758 config->support = PACKET_SUPPORT_UNKNOWN;
764 show_packet_config_cmd (struct packet_config *config)
766 char *support = "internal-error";
767 switch (config->support)
773 support = "disabled";
775 case PACKET_SUPPORT_UNKNOWN:
779 switch (config->detect)
781 case AUTO_BOOLEAN_AUTO:
782 printf_filtered (_("Support for the `%s' packet is auto-detected, currently %s.\n"),
783 config->name, support);
785 case AUTO_BOOLEAN_TRUE:
786 case AUTO_BOOLEAN_FALSE:
787 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
788 config->name, support);
794 add_packet_config_cmd (struct packet_config *config, const char *name,
795 const char *title, int legacy)
802 config->title = title;
803 config->detect = AUTO_BOOLEAN_AUTO;
804 config->support = PACKET_SUPPORT_UNKNOWN;
805 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
807 show_doc = xstrprintf ("Show current use of remote protocol `%s' (%s) packet",
809 /* set/show TITLE-packet {auto,on,off} */
810 cmd_name = xstrprintf ("%s-packet", title);
811 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
812 &config->detect, set_doc, show_doc, NULL, /* help_doc */
813 set_remote_protocol_packet_cmd,
814 show_remote_protocol_packet_cmd,
815 &remote_set_cmdlist, &remote_show_cmdlist);
816 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
820 legacy_name = xstrprintf ("%s-packet", name);
821 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
822 &remote_set_cmdlist);
823 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
824 &remote_show_cmdlist);
828 static enum packet_result
829 packet_check_result (const char *buf)
833 /* The stub recognized the packet request. Check that the
834 operation succeeded. */
836 && isxdigit (buf[1]) && isxdigit (buf[2])
838 /* "Enn" - definitly an error. */
841 /* Always treat "E." as an error. This will be used for
842 more verbose error messages, such as E.memtypes. */
843 if (buf[0] == 'E' && buf[1] == '.')
846 /* The packet may or may not be OK. Just assume it is. */
850 /* The stub does not support the packet. */
851 return PACKET_UNKNOWN;
854 static enum packet_result
855 packet_ok (const char *buf, struct packet_config *config)
857 enum packet_result result;
859 result = packet_check_result (buf);
864 /* The stub recognized the packet request. */
865 switch (config->support)
867 case PACKET_SUPPORT_UNKNOWN:
869 fprintf_unfiltered (gdb_stdlog,
870 "Packet %s (%s) is supported\n",
871 config->name, config->title);
872 config->support = PACKET_ENABLE;
875 internal_error (__FILE__, __LINE__,
876 _("packet_ok: attempt to use a disabled packet"));
883 /* The stub does not support the packet. */
884 switch (config->support)
887 if (config->detect == AUTO_BOOLEAN_AUTO)
888 /* If the stub previously indicated that the packet was
889 supported then there is a protocol error.. */
890 error (_("Protocol error: %s (%s) conflicting enabled responses."),
891 config->name, config->title);
893 /* The user set it wrong. */
894 error (_("Enabled packet %s (%s) not recognized by stub"),
895 config->name, config->title);
897 case PACKET_SUPPORT_UNKNOWN:
899 fprintf_unfiltered (gdb_stdlog,
900 "Packet %s (%s) is NOT supported\n",
901 config->name, config->title);
902 config->support = PACKET_DISABLE;
930 PACKET_qXfer_features,
931 PACKET_qXfer_libraries,
932 PACKET_qXfer_memory_map,
933 PACKET_qXfer_spu_read,
934 PACKET_qXfer_spu_write,
938 PACKET_qSearch_memory,
944 static struct packet_config remote_protocol_packets[PACKET_MAX];
947 set_remote_protocol_packet_cmd (char *args, int from_tty,
948 struct cmd_list_element *c)
950 struct packet_config *packet;
952 for (packet = remote_protocol_packets;
953 packet < &remote_protocol_packets[PACKET_MAX];
956 if (&packet->detect == c->var)
958 update_packet_config (packet);
962 internal_error (__FILE__, __LINE__, "Could not find config for %s",
967 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
968 struct cmd_list_element *c,
971 struct packet_config *packet;
973 for (packet = remote_protocol_packets;
974 packet < &remote_protocol_packets[PACKET_MAX];
977 if (&packet->detect == c->var)
979 show_packet_config_cmd (packet);
983 internal_error (__FILE__, __LINE__, "Could not find config for %s",
987 /* Should we try one of the 'Z' requests? */
991 Z_PACKET_SOFTWARE_BP,
992 Z_PACKET_HARDWARE_BP,
999 /* For compatibility with older distributions. Provide a ``set remote
1000 Z-packet ...'' command that updates all the Z packet types. */
1002 static enum auto_boolean remote_Z_packet_detect;
1005 set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1006 struct cmd_list_element *c)
1009 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1011 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
1012 update_packet_config (&remote_protocol_packets[PACKET_Z0 + i]);
1017 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1018 struct cmd_list_element *c,
1022 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1024 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
1028 /* Should we try the 'ThreadInfo' query packet?
1030 This variable (NOT available to the user: auto-detect only!)
1031 determines whether GDB will use the new, simpler "ThreadInfo"
1032 query or the older, more complex syntax for thread queries.
1033 This is an auto-detect variable (set to true at each connect,
1034 and set to false when the target fails to recognize it). */
1036 static int use_threadinfo_query;
1037 static int use_threadextra_query;
1039 /* Tokens for use by the asynchronous signal handlers for SIGINT. */
1040 static struct async_signal_handler *sigint_remote_twice_token;
1041 static struct async_signal_handler *sigint_remote_token;
1046 /* These are the threads which we last sent to the remote system.
1047 -1 for all or -2 for not sent yet. */
1048 static int general_thread;
1049 static int continue_thread;
1051 /* Call this function as a result of
1052 1) A halt indication (T packet) containing a thread id
1053 2) A direct query of currthread
1054 3) Successful execution of set thread
1058 record_currthread (int currthread)
1060 general_thread = currthread;
1062 /* If this is a new thread, add it to GDB's thread list.
1063 If we leave it up to WFI to do this, bad things will happen. */
1064 if (!in_thread_list (pid_to_ptid (currthread)))
1065 add_thread (pid_to_ptid (currthread));
1068 static char *last_pass_packet;
1070 /* If 'QPassSignals' is supported, tell the remote stub what signals
1071 it can simply pass through to the inferior without reporting. */
1074 remote_pass_signals (void)
1076 if (remote_protocol_packets[PACKET_QPassSignals].support != PACKET_DISABLE)
1078 char *pass_packet, *p;
1079 int numsigs = (int) TARGET_SIGNAL_LAST;
1082 gdb_assert (numsigs < 256);
1083 for (i = 0; i < numsigs; i++)
1085 if (signal_stop_state (i) == 0
1086 && signal_print_state (i) == 0
1087 && signal_pass_state (i) == 1)
1090 pass_packet = xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
1091 strcpy (pass_packet, "QPassSignals:");
1092 p = pass_packet + strlen (pass_packet);
1093 for (i = 0; i < numsigs; i++)
1095 if (signal_stop_state (i) == 0
1096 && signal_print_state (i) == 0
1097 && signal_pass_state (i) == 1)
1100 *p++ = tohex (i >> 4);
1101 *p++ = tohex (i & 15);
1110 if (!last_pass_packet || strcmp (last_pass_packet, pass_packet))
1112 struct remote_state *rs = get_remote_state ();
1113 char *buf = rs->buf;
1115 putpkt (pass_packet);
1116 getpkt (&rs->buf, &rs->buf_size, 0);
1117 packet_ok (buf, &remote_protocol_packets[PACKET_QPassSignals]);
1118 if (last_pass_packet)
1119 xfree (last_pass_packet);
1120 last_pass_packet = pass_packet;
1123 xfree (pass_packet);
1127 #define MAGIC_NULL_PID 42000
1130 set_thread (int th, int gen)
1132 struct remote_state *rs = get_remote_state ();
1133 char *buf = rs->buf;
1134 int state = gen ? general_thread : continue_thread;
1140 buf[1] = gen ? 'g' : 'c';
1141 if (th == MAGIC_NULL_PID)
1147 xsnprintf (&buf[2], get_remote_packet_size () - 2, "-%x", -th);
1149 xsnprintf (&buf[2], get_remote_packet_size () - 2, "%x", th);
1151 getpkt (&rs->buf, &rs->buf_size, 0);
1153 general_thread = th;
1155 continue_thread = th;
1158 /* Return nonzero if the thread TH is still alive on the remote system. */
1161 remote_thread_alive (ptid_t ptid)
1163 struct remote_state *rs = get_remote_state ();
1164 int tid = PIDGET (ptid);
1167 xsnprintf (rs->buf, get_remote_packet_size (), "T-%08x", -tid);
1169 xsnprintf (rs->buf, get_remote_packet_size (), "T%08x", tid);
1171 getpkt (&rs->buf, &rs->buf_size, 0);
1172 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
1175 /* About these extended threadlist and threadinfo packets. They are
1176 variable length packets but, the fields within them are often fixed
1177 length. They are redundent enough to send over UDP as is the
1178 remote protocol in general. There is a matching unit test module
1181 #define OPAQUETHREADBYTES 8
1183 /* a 64 bit opaque identifier */
1184 typedef unsigned char threadref[OPAQUETHREADBYTES];
1186 /* WARNING: This threadref data structure comes from the remote O.S.,
1187 libstub protocol encoding, and remote.c. it is not particularly
1190 /* Right now, the internal structure is int. We want it to be bigger.
1194 typedef int gdb_threadref; /* Internal GDB thread reference. */
1196 /* gdb_ext_thread_info is an internal GDB data structure which is
1197 equivalent to the reply of the remote threadinfo packet. */
1199 struct gdb_ext_thread_info
1201 threadref threadid; /* External form of thread reference. */
1202 int active; /* Has state interesting to GDB?
1204 char display[256]; /* Brief state display, name,
1205 blocked/suspended. */
1206 char shortname[32]; /* To be used to name threads. */
1207 char more_display[256]; /* Long info, statistics, queue depth,
1211 /* The volume of remote transfers can be limited by submitting
1212 a mask containing bits specifying the desired information.
1213 Use a union of these values as the 'selection' parameter to
1214 get_thread_info. FIXME: Make these TAG names more thread specific.
1217 #define TAG_THREADID 1
1218 #define TAG_EXISTS 2
1219 #define TAG_DISPLAY 4
1220 #define TAG_THREADNAME 8
1221 #define TAG_MOREDISPLAY 16
1223 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
1225 char *unpack_varlen_hex (char *buff, ULONGEST *result);
1227 static char *unpack_nibble (char *buf, int *val);
1229 static char *pack_nibble (char *buf, int nibble);
1231 static char *pack_hex_byte (char *pkt, int /* unsigned char */ byte);
1233 static char *unpack_byte (char *buf, int *value);
1235 static char *pack_int (char *buf, int value);
1237 static char *unpack_int (char *buf, int *value);
1239 static char *unpack_string (char *src, char *dest, int length);
1241 static char *pack_threadid (char *pkt, threadref *id);
1243 static char *unpack_threadid (char *inbuf, threadref *id);
1245 void int_to_threadref (threadref *id, int value);
1247 static int threadref_to_int (threadref *ref);
1249 static void copy_threadref (threadref *dest, threadref *src);
1251 static int threadmatch (threadref *dest, threadref *src);
1253 static char *pack_threadinfo_request (char *pkt, int mode,
1256 static int remote_unpack_thread_info_response (char *pkt,
1257 threadref *expectedref,
1258 struct gdb_ext_thread_info
1262 static int remote_get_threadinfo (threadref *threadid,
1263 int fieldset, /*TAG mask */
1264 struct gdb_ext_thread_info *info);
1266 static char *pack_threadlist_request (char *pkt, int startflag,
1268 threadref *nextthread);
1270 static int parse_threadlist_response (char *pkt,
1272 threadref *original_echo,
1273 threadref *resultlist,
1276 static int remote_get_threadlist (int startflag,
1277 threadref *nextthread,
1281 threadref *threadlist);
1283 typedef int (*rmt_thread_action) (threadref *ref, void *context);
1285 static int remote_threadlist_iterator (rmt_thread_action stepfunction,
1286 void *context, int looplimit);
1288 static int remote_newthread_step (threadref *ref, void *context);
1290 /* Encode 64 bits in 16 chars of hex. */
1292 static const char hexchars[] = "0123456789abcdef";
1295 ishex (int ch, int *val)
1297 if ((ch >= 'a') && (ch <= 'f'))
1299 *val = ch - 'a' + 10;
1302 if ((ch >= 'A') && (ch <= 'F'))
1304 *val = ch - 'A' + 10;
1307 if ((ch >= '0') && (ch <= '9'))
1318 if (ch >= 'a' && ch <= 'f')
1319 return ch - 'a' + 10;
1320 if (ch >= '0' && ch <= '9')
1322 if (ch >= 'A' && ch <= 'F')
1323 return ch - 'A' + 10;
1328 stub_unpack_int (char *buff, int fieldlength)
1335 nibble = stubhex (*buff++);
1339 retval = retval << 4;
1345 unpack_varlen_hex (char *buff, /* packet to parse */
1349 ULONGEST retval = 0;
1351 while (ishex (*buff, &nibble))
1354 retval = retval << 4;
1355 retval |= nibble & 0x0f;
1362 unpack_nibble (char *buf, int *val)
1364 *val = fromhex (*buf++);
1369 pack_nibble (char *buf, int nibble)
1371 *buf++ = hexchars[(nibble & 0x0f)];
1376 pack_hex_byte (char *pkt, int byte)
1378 *pkt++ = hexchars[(byte >> 4) & 0xf];
1379 *pkt++ = hexchars[(byte & 0xf)];
1384 unpack_byte (char *buf, int *value)
1386 *value = stub_unpack_int (buf, 2);
1391 pack_int (char *buf, int value)
1393 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
1394 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
1395 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
1396 buf = pack_hex_byte (buf, (value & 0xff));
1401 unpack_int (char *buf, int *value)
1403 *value = stub_unpack_int (buf, 8);
1407 #if 0 /* Currently unused, uncomment when needed. */
1408 static char *pack_string (char *pkt, char *string);
1411 pack_string (char *pkt, char *string)
1416 len = strlen (string);
1418 len = 200; /* Bigger than most GDB packets, junk??? */
1419 pkt = pack_hex_byte (pkt, len);
1423 if ((ch == '\0') || (ch == '#'))
1424 ch = '*'; /* Protect encapsulation. */
1429 #endif /* 0 (unused) */
1432 unpack_string (char *src, char *dest, int length)
1441 pack_threadid (char *pkt, threadref *id)
1444 unsigned char *altid;
1446 altid = (unsigned char *) id;
1447 limit = pkt + BUF_THREAD_ID_SIZE;
1449 pkt = pack_hex_byte (pkt, *altid++);
1455 unpack_threadid (char *inbuf, threadref *id)
1458 char *limit = inbuf + BUF_THREAD_ID_SIZE;
1461 altref = (char *) id;
1463 while (inbuf < limit)
1465 x = stubhex (*inbuf++);
1466 y = stubhex (*inbuf++);
1467 *altref++ = (x << 4) | y;
1472 /* Externally, threadrefs are 64 bits but internally, they are still
1473 ints. This is due to a mismatch of specifications. We would like
1474 to use 64bit thread references internally. This is an adapter
1478 int_to_threadref (threadref *id, int value)
1480 unsigned char *scan;
1482 scan = (unsigned char *) id;
1488 *scan++ = (value >> 24) & 0xff;
1489 *scan++ = (value >> 16) & 0xff;
1490 *scan++ = (value >> 8) & 0xff;
1491 *scan++ = (value & 0xff);
1495 threadref_to_int (threadref *ref)
1498 unsigned char *scan;
1504 value = (value << 8) | ((*scan++) & 0xff);
1509 copy_threadref (threadref *dest, threadref *src)
1512 unsigned char *csrc, *cdest;
1514 csrc = (unsigned char *) src;
1515 cdest = (unsigned char *) dest;
1522 threadmatch (threadref *dest, threadref *src)
1524 /* Things are broken right now, so just assume we got a match. */
1526 unsigned char *srcp, *destp;
1528 srcp = (char *) src;
1529 destp = (char *) dest;
1533 result &= (*srcp++ == *destp++) ? 1 : 0;
1540 threadid:1, # always request threadid
1547 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
1550 pack_threadinfo_request (char *pkt, int mode, threadref *id)
1552 *pkt++ = 'q'; /* Info Query */
1553 *pkt++ = 'P'; /* process or thread info */
1554 pkt = pack_int (pkt, mode); /* mode */
1555 pkt = pack_threadid (pkt, id); /* threadid */
1556 *pkt = '\0'; /* terminate */
1560 /* These values tag the fields in a thread info response packet. */
1561 /* Tagging the fields allows us to request specific fields and to
1562 add more fields as time goes by. */
1564 #define TAG_THREADID 1 /* Echo the thread identifier. */
1565 #define TAG_EXISTS 2 /* Is this process defined enough to
1566 fetch registers and its stack? */
1567 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
1568 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
1569 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
1573 remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
1574 struct gdb_ext_thread_info *info)
1576 struct remote_state *rs = get_remote_state ();
1580 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
1583 /* info->threadid = 0; FIXME: implement zero_threadref. */
1585 info->display[0] = '\0';
1586 info->shortname[0] = '\0';
1587 info->more_display[0] = '\0';
1589 /* Assume the characters indicating the packet type have been
1591 pkt = unpack_int (pkt, &mask); /* arg mask */
1592 pkt = unpack_threadid (pkt, &ref);
1595 warning (_("Incomplete response to threadinfo request."));
1596 if (!threadmatch (&ref, expectedref))
1597 { /* This is an answer to a different request. */
1598 warning (_("ERROR RMT Thread info mismatch."));
1601 copy_threadref (&info->threadid, &ref);
1603 /* Loop on tagged fields , try to bail if somthing goes wrong. */
1605 /* Packets are terminated with nulls. */
1606 while ((pkt < limit) && mask && *pkt)
1608 pkt = unpack_int (pkt, &tag); /* tag */
1609 pkt = unpack_byte (pkt, &length); /* length */
1610 if (!(tag & mask)) /* Tags out of synch with mask. */
1612 warning (_("ERROR RMT: threadinfo tag mismatch."));
1616 if (tag == TAG_THREADID)
1620 warning (_("ERROR RMT: length of threadid is not 16."));
1624 pkt = unpack_threadid (pkt, &ref);
1625 mask = mask & ~TAG_THREADID;
1628 if (tag == TAG_EXISTS)
1630 info->active = stub_unpack_int (pkt, length);
1632 mask = mask & ~(TAG_EXISTS);
1635 warning (_("ERROR RMT: 'exists' length too long."));
1641 if (tag == TAG_THREADNAME)
1643 pkt = unpack_string (pkt, &info->shortname[0], length);
1644 mask = mask & ~TAG_THREADNAME;
1647 if (tag == TAG_DISPLAY)
1649 pkt = unpack_string (pkt, &info->display[0], length);
1650 mask = mask & ~TAG_DISPLAY;
1653 if (tag == TAG_MOREDISPLAY)
1655 pkt = unpack_string (pkt, &info->more_display[0], length);
1656 mask = mask & ~TAG_MOREDISPLAY;
1659 warning (_("ERROR RMT: unknown thread info tag."));
1660 break; /* Not a tag we know about. */
1666 remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
1667 struct gdb_ext_thread_info *info)
1669 struct remote_state *rs = get_remote_state ();
1672 pack_threadinfo_request (rs->buf, fieldset, threadid);
1674 getpkt (&rs->buf, &rs->buf_size, 0);
1675 result = remote_unpack_thread_info_response (rs->buf + 2,
1680 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
1683 pack_threadlist_request (char *pkt, int startflag, int threadcount,
1684 threadref *nextthread)
1686 *pkt++ = 'q'; /* info query packet */
1687 *pkt++ = 'L'; /* Process LIST or threadLIST request */
1688 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
1689 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
1690 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
1695 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
1698 parse_threadlist_response (char *pkt, int result_limit,
1699 threadref *original_echo, threadref *resultlist,
1702 struct remote_state *rs = get_remote_state ();
1704 int count, resultcount, done;
1707 /* Assume the 'q' and 'M chars have been stripped. */
1708 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
1709 /* done parse past here */
1710 pkt = unpack_byte (pkt, &count); /* count field */
1711 pkt = unpack_nibble (pkt, &done);
1712 /* The first threadid is the argument threadid. */
1713 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
1714 while ((count-- > 0) && (pkt < limit))
1716 pkt = unpack_threadid (pkt, resultlist++);
1717 if (resultcount++ >= result_limit)
1726 remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
1727 int *done, int *result_count, threadref *threadlist)
1729 struct remote_state *rs = get_remote_state ();
1730 static threadref echo_nextthread;
1733 /* Trancate result limit to be smaller than the packet size. */
1734 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10) >= get_remote_packet_size ())
1735 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
1737 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
1739 getpkt (&rs->buf, &rs->buf_size, 0);
1741 if (*rs->buf == '\0')
1745 parse_threadlist_response (rs->buf + 2, result_limit, &echo_nextthread,
1748 if (!threadmatch (&echo_nextthread, nextthread))
1750 /* FIXME: This is a good reason to drop the packet. */
1751 /* Possably, there is a duplicate response. */
1753 retransmit immediatly - race conditions
1754 retransmit after timeout - yes
1756 wait for packet, then exit
1758 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
1759 return 0; /* I choose simply exiting. */
1761 if (*result_count <= 0)
1765 warning (_("RMT ERROR : failed to get remote thread list."));
1768 return result; /* break; */
1770 if (*result_count > result_limit)
1773 warning (_("RMT ERROR: threadlist response longer than requested."));
1779 /* This is the interface between remote and threads, remotes upper
1782 /* remote_find_new_threads retrieves the thread list and for each
1783 thread in the list, looks up the thread in GDB's internal list,
1784 ading the thread if it does not already exist. This involves
1785 getting partial thread lists from the remote target so, polling the
1786 quit_flag is required. */
1789 /* About this many threadisds fit in a packet. */
1791 #define MAXTHREADLISTRESULTS 32
1794 remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
1797 int done, i, result_count;
1801 static threadref nextthread;
1802 static threadref resultthreadlist[MAXTHREADLISTRESULTS];
1807 if (loopcount++ > looplimit)
1810 warning (_("Remote fetch threadlist -infinite loop-."));
1813 if (!remote_get_threadlist (startflag, &nextthread, MAXTHREADLISTRESULTS,
1814 &done, &result_count, resultthreadlist))
1819 /* Clear for later iterations. */
1821 /* Setup to resume next batch of thread references, set nextthread. */
1822 if (result_count >= 1)
1823 copy_threadref (&nextthread, &resultthreadlist[result_count - 1]);
1825 while (result_count--)
1826 if (!(result = (*stepfunction) (&resultthreadlist[i++], context)))
1833 remote_newthread_step (threadref *ref, void *context)
1837 ptid = pid_to_ptid (threadref_to_int (ref));
1839 if (!in_thread_list (ptid))
1841 return 1; /* continue iterator */
1844 #define CRAZY_MAX_THREADS 1000
1847 remote_current_thread (ptid_t oldpid)
1849 struct remote_state *rs = get_remote_state ();
1852 getpkt (&rs->buf, &rs->buf_size, 0);
1853 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
1854 /* Use strtoul here, so we'll correctly parse values whose highest
1855 bit is set. The protocol carries them as a simple series of
1856 hex digits; in the absence of a sign, strtol will see such
1857 values as positive numbers out of range for signed 'long', and
1858 return LONG_MAX to indicate an overflow. */
1859 return pid_to_ptid (strtoul (&rs->buf[2], NULL, 16));
1864 /* Find new threads for info threads command.
1865 * Original version, using John Metzler's thread protocol.
1869 remote_find_new_threads (void)
1871 remote_threadlist_iterator (remote_newthread_step, 0,
1873 if (PIDGET (inferior_ptid) == MAGIC_NULL_PID) /* ack ack ack */
1874 inferior_ptid = remote_current_thread (inferior_ptid);
1878 * Find all threads for info threads command.
1879 * Uses new thread protocol contributed by Cisco.
1880 * Falls back and attempts to use the older method (above)
1881 * if the target doesn't respond to the new method.
1885 remote_threads_info (void)
1887 struct remote_state *rs = get_remote_state ();
1891 if (remote_desc == 0) /* paranoia */
1892 error (_("Command can only be used when connected to the remote target."));
1894 if (use_threadinfo_query)
1896 putpkt ("qfThreadInfo");
1897 getpkt (&rs->buf, &rs->buf_size, 0);
1899 if (bufp[0] != '\0') /* q packet recognized */
1901 while (*bufp++ == 'm') /* reply contains one or more TID */
1905 /* Use strtoul here, so we'll correctly parse values
1906 whose highest bit is set. The protocol carries
1907 them as a simple series of hex digits; in the
1908 absence of a sign, strtol will see such values as
1909 positive numbers out of range for signed 'long',
1910 and return LONG_MAX to indicate an overflow. */
1911 tid = strtoul (bufp, &bufp, 16);
1912 if (tid != 0 && !in_thread_list (pid_to_ptid (tid)))
1913 add_thread (pid_to_ptid (tid));
1915 while (*bufp++ == ','); /* comma-separated list */
1916 putpkt ("qsThreadInfo");
1917 getpkt (&rs->buf, &rs->buf_size, 0);
1924 /* Else fall back to old method based on jmetzler protocol. */
1925 use_threadinfo_query = 0;
1926 remote_find_new_threads ();
1931 * Collect a descriptive string about the given thread.
1932 * The target may say anything it wants to about the thread
1933 * (typically info about its blocked / runnable state, name, etc.).
1934 * This string will appear in the info threads display.
1936 * Optional: targets are not required to implement this function.
1940 remote_threads_extra_info (struct thread_info *tp)
1942 struct remote_state *rs = get_remote_state ();
1946 struct gdb_ext_thread_info threadinfo;
1947 static char display_buf[100]; /* arbitrary... */
1948 int n = 0; /* position in display_buf */
1950 if (remote_desc == 0) /* paranoia */
1951 internal_error (__FILE__, __LINE__,
1952 _("remote_threads_extra_info"));
1954 if (use_threadextra_query)
1956 xsnprintf (rs->buf, get_remote_packet_size (), "qThreadExtraInfo,%x",
1959 getpkt (&rs->buf, &rs->buf_size, 0);
1960 if (rs->buf[0] != 0)
1962 n = min (strlen (rs->buf) / 2, sizeof (display_buf));
1963 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
1964 display_buf [result] = '\0';
1969 /* If the above query fails, fall back to the old method. */
1970 use_threadextra_query = 0;
1971 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
1972 | TAG_MOREDISPLAY | TAG_DISPLAY;
1973 int_to_threadref (&id, PIDGET (tp->ptid));
1974 if (remote_get_threadinfo (&id, set, &threadinfo))
1975 if (threadinfo.active)
1977 if (*threadinfo.shortname)
1978 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
1979 " Name: %s,", threadinfo.shortname);
1980 if (*threadinfo.display)
1981 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
1982 " State: %s,", threadinfo.display);
1983 if (*threadinfo.more_display)
1984 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
1985 " Priority: %s", threadinfo.more_display);
1989 /* For purely cosmetic reasons, clear up trailing commas. */
1990 if (',' == display_buf[n-1])
1991 display_buf[n-1] = ' ';
1999 /* Restart the remote side; this is an extended protocol operation. */
2002 extended_remote_restart (void)
2004 struct remote_state *rs = get_remote_state ();
2006 /* Send the restart command; for reasons I don't understand the
2007 remote side really expects a number after the "R". */
2008 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
2011 remote_fileio_reset ();
2014 /* Clean up connection to a remote debugger. */
2017 remote_close (int quitting)
2020 serial_close (remote_desc);
2024 /* Query the remote side for the text, data and bss offsets. */
2029 struct remote_state *rs = get_remote_state ();
2032 int lose, num_segments = 0, do_sections, do_segments;
2033 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
2034 struct section_offsets *offs;
2035 struct symfile_segment_data *data;
2037 if (symfile_objfile == NULL)
2040 putpkt ("qOffsets");
2041 getpkt (&rs->buf, &rs->buf_size, 0);
2044 if (buf[0] == '\000')
2045 return; /* Return silently. Stub doesn't support
2049 warning (_("Remote failure reply: %s"), buf);
2053 /* Pick up each field in turn. This used to be done with scanf, but
2054 scanf will make trouble if CORE_ADDR size doesn't match
2055 conversion directives correctly. The following code will work
2056 with any size of CORE_ADDR. */
2057 text_addr = data_addr = bss_addr = 0;
2061 if (strncmp (ptr, "Text=", 5) == 0)
2064 /* Don't use strtol, could lose on big values. */
2065 while (*ptr && *ptr != ';')
2066 text_addr = (text_addr << 4) + fromhex (*ptr++);
2068 if (strncmp (ptr, ";Data=", 6) == 0)
2071 while (*ptr && *ptr != ';')
2072 data_addr = (data_addr << 4) + fromhex (*ptr++);
2077 if (!lose && strncmp (ptr, ";Bss=", 5) == 0)
2080 while (*ptr && *ptr != ';')
2081 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
2083 if (bss_addr != data_addr)
2084 warning (_("Target reported unsupported offsets: %s"), buf);
2089 else if (strncmp (ptr, "TextSeg=", 8) == 0)
2092 /* Don't use strtol, could lose on big values. */
2093 while (*ptr && *ptr != ';')
2094 text_addr = (text_addr << 4) + fromhex (*ptr++);
2097 if (strncmp (ptr, ";DataSeg=", 9) == 0)
2100 while (*ptr && *ptr != ';')
2101 data_addr = (data_addr << 4) + fromhex (*ptr++);
2109 error (_("Malformed response to offset query, %s"), buf);
2110 else if (*ptr != '\0')
2111 warning (_("Target reported unsupported offsets: %s"), buf);
2113 offs = ((struct section_offsets *)
2114 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
2115 memcpy (offs, symfile_objfile->section_offsets,
2116 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
2118 data = get_symfile_segment_data (symfile_objfile->obfd);
2119 do_segments = (data != NULL);
2120 do_sections = num_segments == 0;
2122 if (num_segments > 0)
2124 segments[0] = text_addr;
2125 segments[1] = data_addr;
2127 /* If we have two segments, we can still try to relocate everything
2128 by assuming that the .text and .data offsets apply to the whole
2129 text and data segments. Convert the offsets given in the packet
2130 to base addresses for symfile_map_offsets_to_segments. */
2131 else if (data && data->num_segments == 2)
2133 segments[0] = data->segment_bases[0] + text_addr;
2134 segments[1] = data->segment_bases[1] + data_addr;
2137 /* If the object file has only one segment, assume that it is text
2138 rather than data; main programs with no writable data are rare,
2139 but programs with no code are useless. Of course the code might
2140 have ended up in the data segment... to detect that we would need
2141 the permissions here. */
2142 else if (data && data->num_segments == 1)
2144 segments[0] = data->segment_bases[0] + text_addr;
2147 /* There's no way to relocate by segment. */
2153 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
2154 offs, num_segments, segments);
2156 if (ret == 0 && !do_sections)
2157 error (_("Can not handle qOffsets TextSeg response with this symbol file"));
2164 free_symfile_segment_data (data);
2168 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
2170 /* This is a temporary kludge to force data and bss to use the same offsets
2171 because that's what nlmconv does now. The real solution requires changes
2172 to the stub and remote.c that I don't have time to do right now. */
2174 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
2175 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
2178 objfile_relocate (symfile_objfile, offs);
2181 /* Stub for catch_exception. */
2183 struct start_remote_args
2187 /* The current target. */
2188 struct target_ops *target;
2190 /* Non-zero if this is an extended-remote target. */
2195 remote_start_remote (struct ui_out *uiout, void *opaque)
2197 struct remote_state *rs = get_remote_state ();
2198 struct start_remote_args *args = opaque;
2199 char *wait_status = NULL;
2201 immediate_quit++; /* Allow user to interrupt it. */
2203 /* Ack any packet which the remote side has already sent. */
2204 serial_write (remote_desc, "+", 1);
2206 /* Check whether the target is running now. */
2208 getpkt (&rs->buf, &rs->buf_size, 0);
2210 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
2212 if (args->extended_p)
2214 /* We're connected, but not running. Drop out before we
2215 call start_remote. */
2216 target_mark_exited (args->target);
2220 error (_("The target is not running (try extended-remote?)"));
2224 if (args->extended_p)
2225 target_mark_running (args->target);
2227 /* Save the reply for later. */
2228 wait_status = alloca (strlen (rs->buf) + 1);
2229 strcpy (wait_status, rs->buf);
2232 /* Let the stub know that we want it to return the thread. */
2235 /* Without this, some commands which require an active target
2236 (such as kill) won't work. This variable serves (at least)
2237 double duty as both the pid of the target process (if it has
2238 such), and as a flag indicating that a target is active.
2239 These functions should be split out into seperate variables,
2240 especially since GDB will someday have a notion of debugging
2241 several processes. */
2242 inferior_ptid = pid_to_ptid (MAGIC_NULL_PID);
2244 /* Now, if we have thread information, update inferior_ptid. */
2245 inferior_ptid = remote_current_thread (inferior_ptid);
2247 get_offsets (); /* Get text, data & bss offsets. */
2249 /* Use the previously fetched status. */
2250 gdb_assert (wait_status != NULL);
2251 strcpy (rs->buf, wait_status);
2252 rs->cached_wait_status = 1;
2255 start_remote (args->from_tty); /* Initialize gdb process mechanisms. */
2258 /* Open a connection to a remote debugger.
2259 NAME is the filename used for communication. */
2262 remote_open (char *name, int from_tty)
2264 remote_open_1 (name, from_tty, &remote_ops, 0, 0);
2267 /* Just like remote_open, but with asynchronous support. */
2269 remote_async_open (char *name, int from_tty)
2271 remote_open_1 (name, from_tty, &remote_async_ops, 0, 1);
2274 /* Open a connection to a remote debugger using the extended
2275 remote gdb protocol. NAME is the filename used for communication. */
2278 extended_remote_open (char *name, int from_tty)
2280 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */,
2284 /* Just like extended_remote_open, but with asynchronous support. */
2286 extended_remote_async_open (char *name, int from_tty)
2288 remote_open_1 (name, from_tty, &extended_async_remote_ops,
2289 1 /*extended_p */, 1 /* async_p */);
2292 /* Generic code for opening a connection to a remote target. */
2295 init_all_packet_configs (void)
2298 for (i = 0; i < PACKET_MAX; i++)
2299 update_packet_config (&remote_protocol_packets[i]);
2302 /* Symbol look-up. */
2305 remote_check_symbols (struct objfile *objfile)
2307 struct remote_state *rs = get_remote_state ();
2308 char *msg, *reply, *tmp;
2309 struct minimal_symbol *sym;
2312 if (remote_protocol_packets[PACKET_qSymbol].support == PACKET_DISABLE)
2315 /* Allocate a message buffer. We can't reuse the input buffer in RS,
2316 because we need both at the same time. */
2317 msg = alloca (get_remote_packet_size ());
2319 /* Invite target to request symbol lookups. */
2321 putpkt ("qSymbol::");
2322 getpkt (&rs->buf, &rs->buf_size, 0);
2323 packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSymbol]);
2326 while (strncmp (reply, "qSymbol:", 8) == 0)
2329 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
2331 sym = lookup_minimal_symbol (msg, NULL, NULL);
2333 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
2336 CORE_ADDR sym_addr = SYMBOL_VALUE_ADDRESS (sym);
2338 /* If this is a function address, return the start of code
2339 instead of any data function descriptor. */
2340 sym_addr = gdbarch_convert_from_func_ptr_addr (current_gdbarch,
2344 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
2345 paddr_nz (sym_addr), &reply[8]);
2349 getpkt (&rs->buf, &rs->buf_size, 0);
2354 static struct serial *
2355 remote_serial_open (char *name)
2357 static int udp_warning = 0;
2359 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
2360 of in ser-tcp.c, because it is the remote protocol assuming that the
2361 serial connection is reliable and not the serial connection promising
2363 if (!udp_warning && strncmp (name, "udp:", 4) == 0)
2366 The remote protocol may be unreliable over UDP.\n\
2367 Some events may be lost, rendering further debugging impossible."));
2371 return serial_open (name);
2374 /* This type describes each known response to the qSupported
2376 struct protocol_feature
2378 /* The name of this protocol feature. */
2381 /* The default for this protocol feature. */
2382 enum packet_support default_support;
2384 /* The function to call when this feature is reported, or after
2385 qSupported processing if the feature is not supported.
2386 The first argument points to this structure. The second
2387 argument indicates whether the packet requested support be
2388 enabled, disabled, or probed (or the default, if this function
2389 is being called at the end of processing and this feature was
2390 not reported). The third argument may be NULL; if not NULL, it
2391 is a NUL-terminated string taken from the packet following
2392 this feature's name and an equals sign. */
2393 void (*func) (const struct protocol_feature *, enum packet_support,
2396 /* The corresponding packet for this feature. Only used if
2397 FUNC is remote_supported_packet. */
2402 remote_supported_packet (const struct protocol_feature *feature,
2403 enum packet_support support,
2404 const char *argument)
2408 warning (_("Remote qSupported response supplied an unexpected value for"
2409 " \"%s\"."), feature->name);
2413 if (remote_protocol_packets[feature->packet].support
2414 == PACKET_SUPPORT_UNKNOWN)
2415 remote_protocol_packets[feature->packet].support = support;
2419 remote_packet_size (const struct protocol_feature *feature,
2420 enum packet_support support, const char *value)
2422 struct remote_state *rs = get_remote_state ();
2427 if (support != PACKET_ENABLE)
2430 if (value == NULL || *value == '\0')
2432 warning (_("Remote target reported \"%s\" without a size."),
2438 packet_size = strtol (value, &value_end, 16);
2439 if (errno != 0 || *value_end != '\0' || packet_size < 0)
2441 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
2442 feature->name, value);
2446 if (packet_size > MAX_REMOTE_PACKET_SIZE)
2448 warning (_("limiting remote suggested packet size (%d bytes) to %d"),
2449 packet_size, MAX_REMOTE_PACKET_SIZE);
2450 packet_size = MAX_REMOTE_PACKET_SIZE;
2453 /* Record the new maximum packet size. */
2454 rs->explicit_packet_size = packet_size;
2457 static struct protocol_feature remote_protocol_features[] = {
2458 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
2459 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
2460 PACKET_qXfer_auxv },
2461 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
2462 PACKET_qXfer_features },
2463 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
2464 PACKET_qXfer_libraries },
2465 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
2466 PACKET_qXfer_memory_map },
2467 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
2468 PACKET_qXfer_spu_read },
2469 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
2470 PACKET_qXfer_spu_write },
2471 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
2472 PACKET_QPassSignals },
2476 remote_query_supported (void)
2478 struct remote_state *rs = get_remote_state ();
2481 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
2483 /* The packet support flags are handled differently for this packet
2484 than for most others. We treat an error, a disabled packet, and
2485 an empty response identically: any features which must be reported
2486 to be used will be automatically disabled. An empty buffer
2487 accomplishes this, since that is also the representation for a list
2488 containing no features. */
2491 if (remote_protocol_packets[PACKET_qSupported].support != PACKET_DISABLE)
2493 putpkt ("qSupported");
2494 getpkt (&rs->buf, &rs->buf_size, 0);
2496 /* If an error occured, warn, but do not return - just reset the
2497 buffer to empty and go on to disable features. */
2498 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
2501 warning (_("Remote failure reply: %s"), rs->buf);
2506 memset (seen, 0, sizeof (seen));
2511 enum packet_support is_supported;
2512 char *p, *end, *name_end, *value;
2514 /* First separate out this item from the rest of the packet. If
2515 there's another item after this, we overwrite the separator
2516 (terminated strings are much easier to work with). */
2518 end = strchr (p, ';');
2521 end = p + strlen (p);
2531 warning (_("empty item in \"qSupported\" response"));
2536 name_end = strchr (p, '=');
2539 /* This is a name=value entry. */
2540 is_supported = PACKET_ENABLE;
2541 value = name_end + 1;
2550 is_supported = PACKET_ENABLE;
2554 is_supported = PACKET_DISABLE;
2558 is_supported = PACKET_SUPPORT_UNKNOWN;
2562 warning (_("unrecognized item \"%s\" in \"qSupported\" response"), p);
2568 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
2569 if (strcmp (remote_protocol_features[i].name, p) == 0)
2571 const struct protocol_feature *feature;
2574 feature = &remote_protocol_features[i];
2575 feature->func (feature, is_supported, value);
2580 /* If we increased the packet size, make sure to increase the global
2581 buffer size also. We delay this until after parsing the entire
2582 qSupported packet, because this is the same buffer we were
2584 if (rs->buf_size < rs->explicit_packet_size)
2586 rs->buf_size = rs->explicit_packet_size;
2587 rs->buf = xrealloc (rs->buf, rs->buf_size);
2590 /* Handle the defaults for unmentioned features. */
2591 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
2594 const struct protocol_feature *feature;
2596 feature = &remote_protocol_features[i];
2597 feature->func (feature, feature->default_support, NULL);
2603 remote_open_1 (char *name, int from_tty, struct target_ops *target,
2604 int extended_p, int async_p)
2606 struct remote_state *rs = get_remote_state ();
2608 error (_("To open a remote debug connection, you need to specify what\n"
2609 "serial device is attached to the remote system\n"
2610 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
2612 /* See FIXME above. */
2614 wait_forever_enabled_p = 1;
2616 /* If we're connected to a running target, target_preopen will kill it.
2617 But if we're connected to a target system with no running process,
2618 then we will still be connected when it returns. Ask this question
2619 first, before target_preopen has a chance to kill anything. */
2620 if (remote_desc != NULL && !target_has_execution)
2623 || query (_("Already connected to a remote target. Disconnect? ")))
2626 error (_("Still connected."));
2629 target_preopen (from_tty);
2631 unpush_target (target);
2633 /* This time without a query. If we were connected to an
2634 extended-remote target and target_preopen killed the running
2635 process, we may still be connected. If we are starting "target
2636 remote" now, the extended-remote target will not have been
2637 removed by unpush_target. */
2638 if (remote_desc != NULL && !target_has_execution)
2641 /* Make sure we send the passed signals list the next time we resume. */
2642 xfree (last_pass_packet);
2643 last_pass_packet = NULL;
2645 remote_fileio_reset ();
2646 reopen_exec_file ();
2649 remote_desc = remote_serial_open (name);
2651 perror_with_name (name);
2653 if (baud_rate != -1)
2655 if (serial_setbaudrate (remote_desc, baud_rate))
2657 /* The requested speed could not be set. Error out to
2658 top level after closing remote_desc. Take care to
2659 set remote_desc to NULL to avoid closing remote_desc
2661 serial_close (remote_desc);
2663 perror_with_name (name);
2667 serial_raw (remote_desc);
2669 /* If there is something sitting in the buffer we might take it as a
2670 response to a command, which would be bad. */
2671 serial_flush_input (remote_desc);
2675 puts_filtered ("Remote debugging using ");
2676 puts_filtered (name);
2677 puts_filtered ("\n");
2679 push_target (target); /* Switch to using remote target now. */
2681 /* Assume that the target is running, unless we learn otherwise. */
2682 target_mark_running (target);
2684 /* Reset the target state; these things will be queried either by
2685 remote_query_supported or as they are needed. */
2686 init_all_packet_configs ();
2687 rs->explicit_packet_size = 0;
2689 general_thread = -2;
2690 continue_thread = -2;
2692 /* Probe for ability to use "ThreadInfo" query, as required. */
2693 use_threadinfo_query = 1;
2694 use_threadextra_query = 1;
2696 /* The first packet we send to the target is the optional "supported
2697 packets" request. If the target can answer this, it will tell us
2698 which later probes to skip. */
2699 remote_query_supported ();
2701 /* Next, if the target can specify a description, read it. We do
2702 this before anything involving memory or registers. */
2703 target_find_description ();
2707 /* With this target we start out by owning the terminal. */
2708 remote_async_terminal_ours_p = 1;
2710 /* FIXME: cagney/1999-09-23: During the initial connection it is
2711 assumed that the target is already ready and able to respond to
2712 requests. Unfortunately remote_start_remote() eventually calls
2713 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
2714 around this. Eventually a mechanism that allows
2715 wait_for_inferior() to expect/get timeouts will be
2717 wait_forever_enabled_p = 0;
2720 /* First delete any symbols previously loaded from shared libraries. */
2721 no_shared_libraries (NULL, 0);
2723 /* Start the remote connection. If error() or QUIT, discard this
2724 target (we'd otherwise be in an inconsistent state) and then
2725 propogate the error on up the exception chain. This ensures that
2726 the caller doesn't stumble along blindly assuming that the
2727 function succeeded. The CLI doesn't have this problem but other
2728 UI's, such as MI do.
2730 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
2731 this function should return an error indication letting the
2732 caller restore the previous state. Unfortunately the command
2733 ``target remote'' is directly wired to this function making that
2734 impossible. On a positive note, the CLI side of this problem has
2735 been fixed - the function set_cmd_context() makes it possible for
2736 all the ``target ....'' commands to share a common callback
2737 function. See cli-dump.c. */
2739 struct gdb_exception ex;
2740 struct start_remote_args args;
2742 args.from_tty = from_tty;
2743 args.target = target;
2744 args.extended_p = extended_p;
2746 ex = catch_exception (uiout, remote_start_remote, &args, RETURN_MASK_ALL);
2751 wait_forever_enabled_p = 1;
2752 throw_exception (ex);
2757 wait_forever_enabled_p = 1;
2761 /* Tell the remote that we are using the extended protocol. */
2763 getpkt (&rs->buf, &rs->buf_size, 0);
2766 /* If we connected to a live target, do some additional setup. */
2767 if (target_has_execution)
2769 if (exec_bfd) /* No use without an exec file. */
2770 remote_check_symbols (symfile_objfile);
2774 /* This takes a program previously attached to and detaches it. After
2775 this is done, GDB can be used to debug some other program. We
2776 better not have left any breakpoints in the target program or it'll
2777 die when it hits one. */
2780 remote_detach_1 (char *args, int from_tty, int extended)
2782 struct remote_state *rs = get_remote_state ();
2785 error (_("Argument given to \"detach\" when remotely debugging."));
2787 if (!target_has_execution)
2788 error (_("No process to detach from."));
2790 /* Tell the remote target to detach. */
2791 strcpy (rs->buf, "D");
2793 getpkt (&rs->buf, &rs->buf_size, 0);
2795 if (rs->buf[0] == 'E')
2796 error (_("Can't detach process."));
2798 /* Unregister the file descriptor from the event loop. */
2799 if (target_is_async_p ())
2800 serial_async (remote_desc, NULL, 0);
2802 target_mourn_inferior ();
2806 puts_filtered ("Detached from remote process.\n");
2808 puts_filtered ("Ending remote debugging.\n");
2813 remote_detach (char *args, int from_tty)
2815 remote_detach_1 (args, from_tty, 0);
2819 extended_remote_detach (char *args, int from_tty)
2821 remote_detach_1 (args, from_tty, 1);
2824 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
2827 remote_disconnect (struct target_ops *target, char *args, int from_tty)
2830 error (_("Argument given to \"disconnect\" when remotely debugging."));
2832 /* Unregister the file descriptor from the event loop. */
2833 if (target_is_async_p ())
2834 serial_async (remote_desc, NULL, 0);
2836 /* Make sure we unpush even the extended remote targets; mourn
2837 won't do it. So call remote_mourn_1 directly instead of
2838 target_mourn_inferior. */
2839 remote_mourn_1 (target);
2842 puts_filtered ("Ending remote debugging.\n");
2845 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
2846 be chatty about it. */
2849 extended_remote_attach_1 (struct target_ops *target, char *args, int from_tty)
2851 struct remote_state *rs = get_remote_state ();
2854 char *wait_status = NULL;
2857 error_no_arg (_("process-id to attach"));
2860 pid = strtol (args, &dummy, 0);
2861 /* Some targets don't set errno on errors, grrr! */
2862 if (pid == 0 && args == dummy)
2863 error (_("Illegal process-id: %s."), args);
2865 if (remote_protocol_packets[PACKET_vAttach].support == PACKET_DISABLE)
2866 error (_("This target does not support attaching to a process"));
2868 sprintf (rs->buf, "vAttach;%x", pid);
2870 getpkt (&rs->buf, &rs->buf_size, 0);
2872 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vAttach]) == PACKET_OK)
2875 printf_unfiltered (_("Attached to %s\n"),
2876 target_pid_to_str (pid_to_ptid (pid)));
2878 /* Save the reply for later. */
2879 wait_status = alloca (strlen (rs->buf) + 1);
2880 strcpy (wait_status, rs->buf);
2882 else if (remote_protocol_packets[PACKET_vAttach].support == PACKET_DISABLE)
2883 error (_("This target does not support attaching to a process"));
2885 error (_("Attaching to %s failed"),
2886 target_pid_to_str (pid_to_ptid (pid)));
2888 target_mark_running (target);
2889 inferior_ptid = pid_to_ptid (pid);
2892 /* Next, if the target can specify a description, read it. We do
2893 this before anything involving memory or registers. */
2894 target_find_description ();
2896 /* Use the previously fetched status. */
2897 gdb_assert (wait_status != NULL);
2898 strcpy (rs->buf, wait_status);
2899 rs->cached_wait_status = 1;
2903 extended_remote_attach (char *args, int from_tty)
2905 extended_remote_attach_1 (&extended_remote_ops, args, from_tty);
2909 extended_async_remote_attach (char *args, int from_tty)
2911 extended_remote_attach_1 (&extended_async_remote_ops, args, from_tty);
2914 /* Convert hex digit A to a number. */
2919 if (a >= '0' && a <= '9')
2921 else if (a >= 'a' && a <= 'f')
2922 return a - 'a' + 10;
2923 else if (a >= 'A' && a <= 'F')
2924 return a - 'A' + 10;
2926 error (_("Reply contains invalid hex digit %d"), a);
2930 hex2bin (const char *hex, gdb_byte *bin, int count)
2934 for (i = 0; i < count; i++)
2936 if (hex[0] == 0 || hex[1] == 0)
2938 /* Hex string is short, or of uneven length.
2939 Return the count that has been converted so far. */
2942 *bin++ = fromhex (hex[0]) * 16 + fromhex (hex[1]);
2948 /* Convert number NIB to a hex digit. */
2956 return 'a' + nib - 10;
2960 bin2hex (const gdb_byte *bin, char *hex, int count)
2963 /* May use a length, or a nul-terminated string as input. */
2965 count = strlen ((char *) bin);
2967 for (i = 0; i < count; i++)
2969 *hex++ = tohex ((*bin >> 4) & 0xf);
2970 *hex++ = tohex (*bin++ & 0xf);
2976 /* Check for the availability of vCont. This function should also check
2980 remote_vcont_probe (struct remote_state *rs)
2984 strcpy (rs->buf, "vCont?");
2986 getpkt (&rs->buf, &rs->buf_size, 0);
2989 /* Make sure that the features we assume are supported. */
2990 if (strncmp (buf, "vCont", 5) == 0)
2993 int support_s, support_S, support_c, support_C;
2999 while (p && *p == ';')
3002 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
3004 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
3006 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
3008 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
3011 p = strchr (p, ';');
3014 /* If s, S, c, and C are not all supported, we can't use vCont. Clearing
3015 BUF will make packet_ok disable the packet. */
3016 if (!support_s || !support_S || !support_c || !support_C)
3020 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
3023 /* Resume the remote inferior by using a "vCont" packet. The thread
3024 to be resumed is PTID; STEP and SIGGNAL indicate whether the
3025 resumed thread should be single-stepped and/or signalled. If PTID's
3026 PID is -1, then all threads are resumed; the thread to be stepped and/or
3027 signalled is given in the global INFERIOR_PTID. This function returns
3028 non-zero iff it resumes the inferior.
3030 This function issues a strict subset of all possible vCont commands at the
3034 remote_vcont_resume (ptid_t ptid, int step, enum target_signal siggnal)
3036 struct remote_state *rs = get_remote_state ();
3037 int pid = PIDGET (ptid);
3039 struct cleanup *old_cleanup;
3041 if (remote_protocol_packets[PACKET_vCont].support == PACKET_SUPPORT_UNKNOWN)
3042 remote_vcont_probe (rs);
3044 if (remote_protocol_packets[PACKET_vCont].support == PACKET_DISABLE)
3047 /* If we could generate a wider range of packets, we'd have to worry
3048 about overflowing BUF. Should there be a generic
3049 "multi-part-packet" packet? */
3051 if (PIDGET (inferior_ptid) == MAGIC_NULL_PID)
3053 /* MAGIC_NULL_PTID means that we don't have any active threads, so we
3054 don't have any PID numbers the inferior will understand. Make sure
3055 to only send forms that do not specify a PID. */
3056 if (step && siggnal != TARGET_SIGNAL_0)
3057 outbuf = xstrprintf ("vCont;S%02x", siggnal);
3059 outbuf = xstrprintf ("vCont;s");
3060 else if (siggnal != TARGET_SIGNAL_0)
3061 outbuf = xstrprintf ("vCont;C%02x", siggnal);
3063 outbuf = xstrprintf ("vCont;c");
3067 /* Resume all threads, with preference for INFERIOR_PTID. */
3068 if (step && siggnal != TARGET_SIGNAL_0)
3069 outbuf = xstrprintf ("vCont;S%02x:%x;c", siggnal,
3070 PIDGET (inferior_ptid));
3072 outbuf = xstrprintf ("vCont;s:%x;c", PIDGET (inferior_ptid));
3073 else if (siggnal != TARGET_SIGNAL_0)
3074 outbuf = xstrprintf ("vCont;C%02x:%x;c", siggnal,
3075 PIDGET (inferior_ptid));
3077 outbuf = xstrprintf ("vCont;c");
3081 /* Scheduler locking; resume only PTID. */
3082 if (step && siggnal != TARGET_SIGNAL_0)
3083 outbuf = xstrprintf ("vCont;S%02x:%x", siggnal, pid);
3085 outbuf = xstrprintf ("vCont;s:%x", pid);
3086 else if (siggnal != TARGET_SIGNAL_0)
3087 outbuf = xstrprintf ("vCont;C%02x:%x", siggnal, pid);
3089 outbuf = xstrprintf ("vCont;c:%x", pid);
3092 gdb_assert (outbuf && strlen (outbuf) < get_remote_packet_size ());
3093 old_cleanup = make_cleanup (xfree, outbuf);
3097 do_cleanups (old_cleanup);
3102 /* Tell the remote machine to resume. */
3104 static enum target_signal last_sent_signal = TARGET_SIGNAL_0;
3106 static int last_sent_step;
3109 remote_resume (ptid_t ptid, int step, enum target_signal siggnal)
3111 struct remote_state *rs = get_remote_state ();
3113 int pid = PIDGET (ptid);
3115 last_sent_signal = siggnal;
3116 last_sent_step = step;
3118 /* Update the inferior on signals to silently pass, if they've changed. */
3119 remote_pass_signals ();
3121 /* The vCont packet doesn't need to specify threads via Hc. */
3122 if (remote_vcont_resume (ptid, step, siggnal))
3125 /* All other supported resume packets do use Hc, so call set_thread. */
3127 set_thread (0, 0); /* Run any thread. */
3129 set_thread (pid, 0); /* Run this thread. */
3132 if (siggnal != TARGET_SIGNAL_0)
3134 buf[0] = step ? 'S' : 'C';
3135 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
3136 buf[2] = tohex (((int) siggnal) & 0xf);
3140 strcpy (buf, step ? "s" : "c");
3145 /* Same as remote_resume, but with async support. */
3147 remote_async_resume (ptid_t ptid, int step, enum target_signal siggnal)
3149 remote_resume (ptid, step, siggnal);
3151 /* We are about to start executing the inferior, let's register it
3152 with the event loop. NOTE: this is the one place where all the
3153 execution commands end up. We could alternatively do this in each
3154 of the execution commands in infcmd.c. */
3155 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
3156 into infcmd.c in order to allow inferior function calls to work
3157 NOT asynchronously. */
3158 if (target_can_async_p ())
3159 target_async (inferior_event_handler, 0);
3160 /* Tell the world that the target is now executing. */
3161 /* FIXME: cagney/1999-09-23: Is it the targets responsibility to set
3162 this? Instead, should the client of target just assume (for
3163 async targets) that the target is going to start executing? Is
3164 this information already found in the continuation block? */
3165 if (target_is_async_p ())
3166 target_executing = 1;
3170 /* Set up the signal handler for SIGINT, while the target is
3171 executing, ovewriting the 'regular' SIGINT signal handler. */
3173 initialize_sigint_signal_handler (void)
3175 signal (SIGINT, handle_remote_sigint);
3178 /* Signal handler for SIGINT, while the target is executing. */
3180 handle_remote_sigint (int sig)
3182 signal (sig, handle_remote_sigint_twice);
3183 mark_async_signal_handler_wrapper (sigint_remote_token);
3186 /* Signal handler for SIGINT, installed after SIGINT has already been
3187 sent once. It will take effect the second time that the user sends
3190 handle_remote_sigint_twice (int sig)
3192 signal (sig, handle_remote_sigint);
3193 mark_async_signal_handler_wrapper (sigint_remote_twice_token);
3196 /* Perform the real interruption of the target execution, in response
3199 async_remote_interrupt (gdb_client_data arg)
3202 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
3207 /* Perform interrupt, if the first attempt did not succeed. Just give
3208 up on the target alltogether. */
3210 async_remote_interrupt_twice (gdb_client_data arg)
3213 fprintf_unfiltered (gdb_stdlog, "remote_interrupt_twice called\n");
3218 /* Reinstall the usual SIGINT handlers, after the target has
3221 cleanup_sigint_signal_handler (void *dummy)
3223 signal (SIGINT, handle_sigint);
3226 /* Send ^C to target to halt it. Target will respond, and send us a
3228 static void (*ofunc) (int);
3230 /* The command line interface's stop routine. This function is installed
3231 as a signal handler for SIGINT. The first time a user requests a
3232 stop, we call remote_stop to send a break or ^C. If there is no
3233 response from the target (it didn't stop when the user requested it),
3234 we ask the user if he'd like to detach from the target. */
3236 remote_interrupt (int signo)
3238 /* If this doesn't work, try more severe steps. */
3239 signal (signo, remote_interrupt_twice);
3241 gdb_call_async_signal_handler (sigint_remote_token, 1);
3244 /* The user typed ^C twice. */
3247 remote_interrupt_twice (int signo)
3249 signal (signo, ofunc);
3250 gdb_call_async_signal_handler (sigint_remote_twice_token, 1);
3251 signal (signo, remote_interrupt);
3254 /* This is the generic stop called via the target vector. When a target
3255 interrupt is requested, either by the command line or the GUI, we
3256 will eventually end up here. */
3260 /* Send a break or a ^C, depending on user preference. */
3262 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
3265 serial_send_break (remote_desc);
3267 serial_write (remote_desc, "\003", 1);
3270 /* Ask the user what to do when an interrupt is received. */
3273 interrupt_query (void)
3275 target_terminal_ours ();
3277 if (query ("Interrupted while waiting for the program.\n\
3278 Give up (and stop debugging it)? "))
3280 target_mourn_inferior ();
3281 signal (SIGINT, handle_sigint);
3282 deprecated_throw_reason (RETURN_QUIT);
3285 target_terminal_inferior ();
3288 /* Enable/disable target terminal ownership. Most targets can use
3289 terminal groups to control terminal ownership. Remote targets are
3290 different in that explicit transfer of ownership to/from GDB/target
3294 remote_async_terminal_inferior (void)
3296 /* FIXME: cagney/1999-09-27: Shouldn't need to test for
3297 sync_execution here. This function should only be called when
3298 GDB is resuming the inferior in the forground. A background
3299 resume (``run&'') should leave GDB in control of the terminal and
3300 consequently should not call this code. */
3301 if (!sync_execution)
3303 /* FIXME: cagney/1999-09-27: Closely related to the above. Make
3304 calls target_terminal_*() idenpotent. The event-loop GDB talking
3305 to an asynchronous target with a synchronous command calls this
3306 function from both event-top.c and infrun.c/infcmd.c. Once GDB
3307 stops trying to transfer the terminal to the target when it
3308 shouldn't this guard can go away. */
3309 if (!remote_async_terminal_ours_p)
3311 delete_file_handler (input_fd);
3312 remote_async_terminal_ours_p = 0;
3313 initialize_sigint_signal_handler ();
3314 /* NOTE: At this point we could also register our selves as the
3315 recipient of all input. Any characters typed could then be
3316 passed on down to the target. */
3320 remote_async_terminal_ours (void)
3322 /* See FIXME in remote_async_terminal_inferior. */
3323 if (!sync_execution)
3325 /* See FIXME in remote_async_terminal_inferior. */
3326 if (remote_async_terminal_ours_p)
3328 cleanup_sigint_signal_handler (NULL);
3329 add_file_handler (input_fd, stdin_event_handler, 0);
3330 remote_async_terminal_ours_p = 1;
3334 remote_console_output (char *msg)
3338 for (p = msg; p[0] && p[1]; p += 2)
3341 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
3344 fputs_unfiltered (tb, gdb_stdtarg);
3346 gdb_flush (gdb_stdtarg);
3349 /* Wait until the remote machine stops, then return,
3350 storing status in STATUS just as `wait' would.
3351 Returns "pid", which in the case of a multi-threaded
3352 remote OS, is the thread-id. */
3355 remote_wait (ptid_t ptid, struct target_waitstatus *status)
3357 struct remote_state *rs = get_remote_state ();
3358 struct remote_arch_state *rsa = get_remote_arch_state ();
3359 ULONGEST thread_num = -1;
3361 int solibs_changed = 0;
3363 status->kind = TARGET_WAITKIND_EXITED;
3364 status->value.integer = 0;
3370 if (rs->cached_wait_status)
3371 /* Use the cached wait status, but only once. */
3372 rs->cached_wait_status = 0;
3375 ofunc = signal (SIGINT, remote_interrupt);
3376 /* If the user hit C-c before this packet, or between packets,
3377 pretend that it was hit right here. */
3381 remote_interrupt (SIGINT);
3383 getpkt (&rs->buf, &rs->buf_size, 1);
3384 signal (SIGINT, ofunc);
3389 remote_stopped_by_watchpoint_p = 0;
3393 case 'E': /* Error of some sort. */
3394 /* We're out of sync with the target now. Did it continue or not?
3395 Not is more likely, so report a stop. */
3396 warning (_("Remote failure reply: %s"), buf);
3397 status->kind = TARGET_WAITKIND_STOPPED;
3398 status->value.sig = TARGET_SIGNAL_0;
3400 case 'F': /* File-I/O request. */
3401 remote_fileio_request (buf);
3403 case 'T': /* Status with PC, SP, FP, ... */
3405 gdb_byte regs[MAX_REGISTER_SIZE];
3407 /* Expedited reply, containing Signal, {regno, reg} repeat. */
3408 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
3410 n... = register number
3411 r... = register contents
3413 p = &buf[3]; /* after Txx */
3422 /* If the packet contains a register number save it in
3423 pnum and set p1 to point to the character following
3424 it. Otherwise p1 points to p. */
3426 /* If this packet is an awatch packet, don't parse the
3427 'a' as a register number. */
3429 if (strncmp (p, "awatch", strlen("awatch")) != 0)
3431 /* Read the ``P'' register number. */
3432 pnum = strtol (p, &p_temp, 16);
3438 if (p1 == p) /* No register number present here. */
3440 p1 = strchr (p, ':');
3442 error (_("Malformed packet(a) (missing colon): %s\n\
3445 if (strncmp (p, "thread", p1 - p) == 0)
3447 p_temp = unpack_varlen_hex (++p1, &thread_num);
3448 record_currthread (thread_num);
3451 else if ((strncmp (p, "watch", p1 - p) == 0)
3452 || (strncmp (p, "rwatch", p1 - p) == 0)
3453 || (strncmp (p, "awatch", p1 - p) == 0))
3455 remote_stopped_by_watchpoint_p = 1;
3456 p = unpack_varlen_hex (++p1, &addr);
3457 remote_watch_data_address = (CORE_ADDR)addr;
3459 else if (strncmp (p, "library", p1 - p) == 0)
3463 while (*p_temp && *p_temp != ';')
3471 /* Silently skip unknown optional info. */
3472 p_temp = strchr (p1 + 1, ';');
3479 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
3483 error (_("Malformed packet(b) (missing colon): %s\n\
3488 error (_("Remote sent bad register number %s: %s\n\
3490 phex_nz (pnum, 0), p, buf);
3492 fieldsize = hex2bin (p, regs,
3493 register_size (current_gdbarch,
3496 if (fieldsize < register_size (current_gdbarch,
3498 warning (_("Remote reply is too short: %s"), buf);
3499 regcache_raw_supply (get_current_regcache (),
3504 error (_("Remote register badly formatted: %s\nhere: %s"),
3509 case 'S': /* Old style status, just signal only. */
3511 status->kind = TARGET_WAITKIND_LOADED;
3514 status->kind = TARGET_WAITKIND_STOPPED;
3515 status->value.sig = (enum target_signal)
3516 (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
3521 thread_num = strtol ((const char *) &buf[4], NULL, 16);
3522 record_currthread (thread_num);
3525 case 'W': /* Target exited. */
3527 /* The remote process exited. */
3528 status->kind = TARGET_WAITKIND_EXITED;
3529 status->value.integer = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
3533 status->kind = TARGET_WAITKIND_SIGNALLED;
3534 status->value.sig = (enum target_signal)
3535 (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
3538 case 'O': /* Console output. */
3539 remote_console_output (buf + 1);
3542 if (last_sent_signal != TARGET_SIGNAL_0)
3544 /* Zero length reply means that we tried 'S' or 'C' and
3545 the remote system doesn't support it. */
3546 target_terminal_ours_for_output ();
3548 ("Can't send signals to this remote system. %s not sent.\n",
3549 target_signal_to_name (last_sent_signal));
3550 last_sent_signal = TARGET_SIGNAL_0;
3551 target_terminal_inferior ();
3553 strcpy ((char *) buf, last_sent_step ? "s" : "c");
3554 putpkt ((char *) buf);
3557 /* else fallthrough */
3559 warning (_("Invalid remote reply: %s"), buf);
3564 if (thread_num != -1)
3566 return pid_to_ptid (thread_num);
3568 return inferior_ptid;
3571 /* Async version of remote_wait. */
3573 remote_async_wait (ptid_t ptid, struct target_waitstatus *status)
3575 struct remote_state *rs = get_remote_state ();
3576 struct remote_arch_state *rsa = get_remote_arch_state ();
3577 ULONGEST thread_num = -1;
3579 int solibs_changed = 0;
3581 status->kind = TARGET_WAITKIND_EXITED;
3582 status->value.integer = 0;
3584 remote_stopped_by_watchpoint_p = 0;
3590 if (rs->cached_wait_status)
3591 /* Use the cached wait status, but only once. */
3592 rs->cached_wait_status = 0;
3595 if (!target_is_async_p ())
3597 ofunc = signal (SIGINT, remote_interrupt);
3598 /* If the user hit C-c before this packet, or between packets,
3599 pretend that it was hit right here. */
3603 remote_interrupt (SIGINT);
3606 /* FIXME: cagney/1999-09-27: If we're in async mode we should
3607 _never_ wait for ever -> test on target_is_async_p().
3608 However, before we do that we need to ensure that the caller
3609 knows how to take the target into/out of async mode. */
3610 getpkt (&rs->buf, &rs->buf_size, wait_forever_enabled_p);
3611 if (!target_is_async_p ())
3612 signal (SIGINT, ofunc);
3619 case 'E': /* Error of some sort. */
3620 /* We're out of sync with the target now. Did it continue or not?
3621 Not is more likely, so report a stop. */
3622 warning (_("Remote failure reply: %s"), buf);
3623 status->kind = TARGET_WAITKIND_STOPPED;
3624 status->value.sig = TARGET_SIGNAL_0;
3626 case 'F': /* File-I/O request. */
3627 remote_fileio_request (buf);
3629 case 'T': /* Status with PC, SP, FP, ... */
3631 gdb_byte regs[MAX_REGISTER_SIZE];
3633 /* Expedited reply, containing Signal, {regno, reg} repeat. */
3634 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
3636 n... = register number
3637 r... = register contents
3639 p = &buf[3]; /* after Txx */
3648 /* If the packet contains a register number, save it
3649 in pnum and set p1 to point to the character
3650 following it. Otherwise p1 points to p. */
3652 /* If this packet is an awatch packet, don't parse the 'a'
3653 as a register number. */
3655 if (strncmp (p, "awatch", strlen("awatch")) != 0)
3657 /* Read the register number. */
3658 pnum = strtol (p, &p_temp, 16);
3664 if (p1 == p) /* No register number present here. */
3666 p1 = strchr (p, ':');
3668 error (_("Malformed packet(a) (missing colon): %s\n\
3671 if (strncmp (p, "thread", p1 - p) == 0)
3673 p_temp = unpack_varlen_hex (++p1, &thread_num);
3674 record_currthread (thread_num);
3677 else if ((strncmp (p, "watch", p1 - p) == 0)
3678 || (strncmp (p, "rwatch", p1 - p) == 0)
3679 || (strncmp (p, "awatch", p1 - p) == 0))
3681 remote_stopped_by_watchpoint_p = 1;
3682 p = unpack_varlen_hex (++p1, &addr);
3683 remote_watch_data_address = (CORE_ADDR)addr;
3685 else if (strncmp (p, "library", p1 - p) == 0)
3689 while (*p_temp && *p_temp != ';')
3697 /* Silently skip unknown optional info. */
3698 p_temp = strchr (p1 + 1, ';');
3706 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
3709 error (_("Malformed packet(b) (missing colon): %s\n\
3714 error (_("Remote sent bad register number %ld: %s\n\
3718 fieldsize = hex2bin (p, regs,
3719 register_size (current_gdbarch,
3722 if (fieldsize < register_size (current_gdbarch,
3724 warning (_("Remote reply is too short: %s"), buf);
3725 regcache_raw_supply (get_current_regcache (),
3730 error (_("Remote register badly formatted: %s\nhere: %s"),
3735 case 'S': /* Old style status, just signal only. */
3737 status->kind = TARGET_WAITKIND_LOADED;
3740 status->kind = TARGET_WAITKIND_STOPPED;
3741 status->value.sig = (enum target_signal)
3742 (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
3747 thread_num = strtol ((const char *) &buf[4], NULL, 16);
3748 record_currthread (thread_num);
3751 case 'W': /* Target exited. */
3753 /* The remote process exited. */
3754 status->kind = TARGET_WAITKIND_EXITED;
3755 status->value.integer = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
3759 status->kind = TARGET_WAITKIND_SIGNALLED;
3760 status->value.sig = (enum target_signal)
3761 (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
3764 case 'O': /* Console output. */
3765 remote_console_output (buf + 1);
3766 /* Return immediately to the event loop. The event loop will
3767 still be waiting on the inferior afterwards. */
3768 status->kind = TARGET_WAITKIND_IGNORE;
3771 if (last_sent_signal != TARGET_SIGNAL_0)
3773 /* Zero length reply means that we tried 'S' or 'C' and
3774 the remote system doesn't support it. */
3775 target_terminal_ours_for_output ();
3777 ("Can't send signals to this remote system. %s not sent.\n",
3778 target_signal_to_name (last_sent_signal));
3779 last_sent_signal = TARGET_SIGNAL_0;
3780 target_terminal_inferior ();
3782 strcpy ((char *) buf, last_sent_step ? "s" : "c");
3783 putpkt ((char *) buf);
3786 /* else fallthrough */
3788 warning (_("Invalid remote reply: %s"), buf);
3793 if (thread_num != -1)
3795 return pid_to_ptid (thread_num);
3797 return inferior_ptid;
3800 /* Fetch a single register using a 'p' packet. */
3803 fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
3805 struct remote_state *rs = get_remote_state ();
3807 char regp[MAX_REGISTER_SIZE];
3810 if (remote_protocol_packets[PACKET_p].support == PACKET_DISABLE)
3813 if (reg->pnum == -1)
3818 p += hexnumstr (p, reg->pnum);
3820 remote_send (&rs->buf, &rs->buf_size);
3824 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
3828 case PACKET_UNKNOWN:
3831 error (_("Could not fetch register \"%s\""),
3832 gdbarch_register_name (get_regcache_arch (regcache), reg->regnum));
3835 /* If this register is unfetchable, tell the regcache. */
3838 regcache_raw_supply (regcache, reg->regnum, NULL);
3842 /* Otherwise, parse and supply the value. */
3848 error (_("fetch_register_using_p: early buf termination"));
3850 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
3853 regcache_raw_supply (regcache, reg->regnum, regp);
3857 /* Fetch the registers included in the target's 'g' packet. */
3860 send_g_packet (void)
3862 struct remote_state *rs = get_remote_state ();
3867 sprintf (rs->buf, "g");
3868 remote_send (&rs->buf, &rs->buf_size);
3870 /* We can get out of synch in various cases. If the first character
3871 in the buffer is not a hex character, assume that has happened
3872 and try to fetch another packet to read. */
3873 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
3874 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
3875 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
3876 && rs->buf[0] != 'x') /* New: unavailable register value. */
3879 fprintf_unfiltered (gdb_stdlog,
3880 "Bad register packet; fetching a new packet\n");
3881 getpkt (&rs->buf, &rs->buf_size, 0);
3884 buf_len = strlen (rs->buf);
3886 /* Sanity check the received packet. */
3887 if (buf_len % 2 != 0)
3888 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
3894 process_g_packet (struct regcache *regcache)
3896 struct gdbarch *gdbarch = get_regcache_arch (regcache);
3897 struct remote_state *rs = get_remote_state ();
3898 struct remote_arch_state *rsa = get_remote_arch_state ();
3903 buf_len = strlen (rs->buf);
3905 /* Further sanity checks, with knowledge of the architecture. */
3906 if (buf_len > 2 * rsa->sizeof_g_packet)
3907 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
3909 /* Save the size of the packet sent to us by the target. It is used
3910 as a heuristic when determining the max size of packets that the
3911 target can safely receive. */
3912 if (rsa->actual_register_packet_size == 0)
3913 rsa->actual_register_packet_size = buf_len;
3915 /* If this is smaller than we guessed the 'g' packet would be,
3916 update our records. A 'g' reply that doesn't include a register's
3917 value implies either that the register is not available, or that
3918 the 'p' packet must be used. */
3919 if (buf_len < 2 * rsa->sizeof_g_packet)
3921 rsa->sizeof_g_packet = buf_len / 2;
3923 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
3925 if (rsa->regs[i].pnum == -1)
3928 if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
3929 rsa->regs[i].in_g_packet = 0;
3931 rsa->regs[i].in_g_packet = 1;
3935 regs = alloca (rsa->sizeof_g_packet);
3937 /* Unimplemented registers read as all bits zero. */
3938 memset (regs, 0, rsa->sizeof_g_packet);
3940 /* Reply describes registers byte by byte, each byte encoded as two
3941 hex characters. Suck them all up, then supply them to the
3942 register cacheing/storage mechanism. */
3945 for (i = 0; i < rsa->sizeof_g_packet; i++)
3947 if (p[0] == 0 || p[1] == 0)
3948 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
3949 internal_error (__FILE__, __LINE__,
3950 "unexpected end of 'g' packet reply");
3952 if (p[0] == 'x' && p[1] == 'x')
3953 regs[i] = 0; /* 'x' */
3955 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
3961 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
3963 struct packet_reg *r = &rsa->regs[i];
3966 if (r->offset * 2 >= strlen (rs->buf))
3967 /* This shouldn't happen - we adjusted in_g_packet above. */
3968 internal_error (__FILE__, __LINE__,
3969 "unexpected end of 'g' packet reply");
3970 else if (rs->buf[r->offset * 2] == 'x')
3972 gdb_assert (r->offset * 2 < strlen (rs->buf));
3973 /* The register isn't available, mark it as such (at
3974 the same time setting the value to zero). */
3975 regcache_raw_supply (regcache, r->regnum, NULL);
3978 regcache_raw_supply (regcache, r->regnum,
3986 fetch_registers_using_g (struct regcache *regcache)
3989 process_g_packet (regcache);
3993 remote_fetch_registers (struct regcache *regcache, int regnum)
3995 struct remote_state *rs = get_remote_state ();
3996 struct remote_arch_state *rsa = get_remote_arch_state ();
3999 set_thread (PIDGET (inferior_ptid), 1);
4003 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
4004 gdb_assert (reg != NULL);
4006 /* If this register might be in the 'g' packet, try that first -
4007 we are likely to read more than one register. If this is the
4008 first 'g' packet, we might be overly optimistic about its
4009 contents, so fall back to 'p'. */
4010 if (reg->in_g_packet)
4012 fetch_registers_using_g (regcache);
4013 if (reg->in_g_packet)
4017 if (fetch_register_using_p (regcache, reg))
4020 /* This register is not available. */
4021 regcache_raw_supply (regcache, reg->regnum, NULL);
4026 fetch_registers_using_g (regcache);
4028 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
4029 if (!rsa->regs[i].in_g_packet)
4030 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
4032 /* This register is not available. */
4033 regcache_raw_supply (regcache, i, NULL);
4037 /* Prepare to store registers. Since we may send them all (using a
4038 'G' request), we have to read out the ones we don't want to change
4042 remote_prepare_to_store (struct regcache *regcache)
4044 struct remote_arch_state *rsa = get_remote_arch_state ();
4046 gdb_byte buf[MAX_REGISTER_SIZE];
4048 /* Make sure the entire registers array is valid. */
4049 switch (remote_protocol_packets[PACKET_P].support)
4051 case PACKET_DISABLE:
4052 case PACKET_SUPPORT_UNKNOWN:
4053 /* Make sure all the necessary registers are cached. */
4054 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
4055 if (rsa->regs[i].in_g_packet)
4056 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
4063 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
4064 packet was not recognized. */
4067 store_register_using_P (const struct regcache *regcache, struct packet_reg *reg)
4069 struct gdbarch *gdbarch = get_regcache_arch (regcache);
4070 struct remote_state *rs = get_remote_state ();
4071 struct remote_arch_state *rsa = get_remote_arch_state ();
4072 /* Try storing a single register. */
4073 char *buf = rs->buf;
4074 gdb_byte regp[MAX_REGISTER_SIZE];
4077 if (remote_protocol_packets[PACKET_P].support == PACKET_DISABLE)
4080 if (reg->pnum == -1)
4083 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
4084 p = buf + strlen (buf);
4085 regcache_raw_collect (regcache, reg->regnum, regp);
4086 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
4087 remote_send (&rs->buf, &rs->buf_size);
4089 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
4094 error (_("Could not write register \"%s\""),
4095 gdbarch_register_name (gdbarch, reg->regnum));
4096 case PACKET_UNKNOWN:
4099 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
4103 /* Store register REGNUM, or all registers if REGNUM == -1, from the
4104 contents of the register cache buffer. FIXME: ignores errors. */
4107 store_registers_using_G (const struct regcache *regcache)
4109 struct remote_state *rs = get_remote_state ();
4110 struct remote_arch_state *rsa = get_remote_arch_state ();
4114 /* Extract all the registers in the regcache copying them into a
4118 regs = alloca (rsa->sizeof_g_packet);
4119 memset (regs, 0, rsa->sizeof_g_packet);
4120 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
4122 struct packet_reg *r = &rsa->regs[i];
4124 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
4128 /* Command describes registers byte by byte,
4129 each byte encoded as two hex characters. */
4132 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
4134 bin2hex (regs, p, rsa->sizeof_g_packet);
4135 remote_send (&rs->buf, &rs->buf_size);
4138 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
4139 of the register cache buffer. FIXME: ignores errors. */
4142 remote_store_registers (struct regcache *regcache, int regnum)
4144 struct remote_state *rs = get_remote_state ();
4145 struct remote_arch_state *rsa = get_remote_arch_state ();
4148 set_thread (PIDGET (inferior_ptid), 1);
4152 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
4153 gdb_assert (reg != NULL);
4155 /* Always prefer to store registers using the 'P' packet if
4156 possible; we often change only a small number of registers.
4157 Sometimes we change a larger number; we'd need help from a
4158 higher layer to know to use 'G'. */
4159 if (store_register_using_P (regcache, reg))
4162 /* For now, don't complain if we have no way to write the
4163 register. GDB loses track of unavailable registers too
4164 easily. Some day, this may be an error. We don't have
4165 any way to read the register, either... */
4166 if (!reg->in_g_packet)
4169 store_registers_using_G (regcache);
4173 store_registers_using_G (regcache);
4175 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
4176 if (!rsa->regs[i].in_g_packet)
4177 if (!store_register_using_P (regcache, &rsa->regs[i]))
4178 /* See above for why we do not issue an error here. */
4183 /* Return the number of hex digits in num. */
4186 hexnumlen (ULONGEST num)
4190 for (i = 0; num != 0; i++)
4196 /* Set BUF to the minimum number of hex digits representing NUM. */
4199 hexnumstr (char *buf, ULONGEST num)
4201 int len = hexnumlen (num);
4202 return hexnumnstr (buf, num, len);
4206 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
4209 hexnumnstr (char *buf, ULONGEST num, int width)
4215 for (i = width - 1; i >= 0; i--)
4217 buf[i] = "0123456789abcdef"[(num & 0xf)];
4224 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
4227 remote_address_masked (CORE_ADDR addr)
4229 int address_size = remote_address_size;
4230 /* If "remoteaddresssize" was not set, default to target address size. */
4232 address_size = gdbarch_addr_bit (current_gdbarch);
4234 if (address_size > 0
4235 && address_size < (sizeof (ULONGEST) * 8))
4237 /* Only create a mask when that mask can safely be constructed
4238 in a ULONGEST variable. */
4240 mask = (mask << address_size) - 1;
4246 /* Convert BUFFER, binary data at least LEN bytes long, into escaped
4247 binary data in OUT_BUF. Set *OUT_LEN to the length of the data
4248 encoded in OUT_BUF, and return the number of bytes in OUT_BUF
4249 (which may be more than *OUT_LEN due to escape characters). The
4250 total number of bytes in the output buffer will be at most
4254 remote_escape_output (const gdb_byte *buffer, int len,
4255 gdb_byte *out_buf, int *out_len,
4258 int input_index, output_index;
4261 for (input_index = 0; input_index < len; input_index++)
4263 gdb_byte b = buffer[input_index];
4265 if (b == '$' || b == '#' || b == '}')
4267 /* These must be escaped. */
4268 if (output_index + 2 > out_maxlen)
4270 out_buf[output_index++] = '}';
4271 out_buf[output_index++] = b ^ 0x20;
4275 if (output_index + 1 > out_maxlen)
4277 out_buf[output_index++] = b;
4281 *out_len = input_index;
4282 return output_index;
4285 /* Convert BUFFER, escaped data LEN bytes long, into binary data
4286 in OUT_BUF. Return the number of bytes written to OUT_BUF.
4287 Raise an error if the total number of bytes exceeds OUT_MAXLEN.
4289 This function reverses remote_escape_output. It allows more
4290 escaped characters than that function does, in particular because
4291 '*' must be escaped to avoid the run-length encoding processing
4292 in reading packets. */
4295 remote_unescape_input (const gdb_byte *buffer, int len,
4296 gdb_byte *out_buf, int out_maxlen)
4298 int input_index, output_index;
4303 for (input_index = 0; input_index < len; input_index++)
4305 gdb_byte b = buffer[input_index];
4307 if (output_index + 1 > out_maxlen)
4309 warning (_("Received too much data from remote target;"
4310 " ignoring overflow."));
4311 return output_index;
4316 out_buf[output_index++] = b ^ 0x20;
4322 out_buf[output_index++] = b;
4326 error (_("Unmatched escape character in target response."));
4328 return output_index;
4331 /* Determine whether the remote target supports binary downloading.
4332 This is accomplished by sending a no-op memory write of zero length
4333 to the target at the specified address. It does not suffice to send
4334 the whole packet, since many stubs strip the eighth bit and
4335 subsequently compute a wrong checksum, which causes real havoc with
4338 NOTE: This can still lose if the serial line is not eight-bit
4339 clean. In cases like this, the user should clear "remote
4343 check_binary_download (CORE_ADDR addr)
4345 struct remote_state *rs = get_remote_state ();
4347 switch (remote_protocol_packets[PACKET_X].support)
4349 case PACKET_DISABLE:
4353 case PACKET_SUPPORT_UNKNOWN:
4359 p += hexnumstr (p, (ULONGEST) addr);
4361 p += hexnumstr (p, (ULONGEST) 0);
4365 putpkt_binary (rs->buf, (int) (p - rs->buf));
4366 getpkt (&rs->buf, &rs->buf_size, 0);
4368 if (rs->buf[0] == '\0')
4371 fprintf_unfiltered (gdb_stdlog,
4372 "binary downloading NOT suppported by target\n");
4373 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
4378 fprintf_unfiltered (gdb_stdlog,
4379 "binary downloading suppported by target\n");
4380 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
4387 /* Write memory data directly to the remote machine.
4388 This does not inform the data cache; the data cache uses this.
4389 HEADER is the starting part of the packet.
4390 MEMADDR is the address in the remote memory space.
4391 MYADDR is the address of the buffer in our space.
4392 LEN is the number of bytes.
4393 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
4394 should send data as binary ('X'), or hex-encoded ('M').
4396 The function creates packet of the form
4397 <HEADER><ADDRESS>,<LENGTH>:<DATA>
4399 where encoding of <DATA> is termined by PACKET_FORMAT.
4401 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
4404 Returns the number of bytes transferred, or 0 (setting errno) for
4405 error. Only transfer a single packet. */
4408 remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
4409 const gdb_byte *myaddr, int len,
4410 char packet_format, int use_length)
4412 struct remote_state *rs = get_remote_state ();
4422 if (packet_format != 'X' && packet_format != 'M')
4423 internal_error (__FILE__, __LINE__,
4424 "remote_write_bytes_aux: bad packet format");
4429 payload_size = get_memory_write_packet_size ();
4431 /* The packet buffer will be large enough for the payload;
4432 get_memory_packet_size ensures this. */
4435 /* Compute the size of the actual payload by subtracting out the
4436 packet header and footer overhead: "$M<memaddr>,<len>:...#nn".
4438 payload_size -= strlen ("$,:#NN");
4440 /* The comma won't be used. */
4442 header_length = strlen (header);
4443 payload_size -= header_length;
4444 payload_size -= hexnumlen (memaddr);
4446 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
4448 strcat (rs->buf, header);
4449 p = rs->buf + strlen (header);
4451 /* Compute a best guess of the number of bytes actually transfered. */
4452 if (packet_format == 'X')
4454 /* Best guess at number of bytes that will fit. */
4455 todo = min (len, payload_size);
4457 payload_size -= hexnumlen (todo);
4458 todo = min (todo, payload_size);
4462 /* Num bytes that will fit. */
4463 todo = min (len, payload_size / 2);
4465 payload_size -= hexnumlen (todo);
4466 todo = min (todo, payload_size / 2);
4470 internal_error (__FILE__, __LINE__,
4471 _("minumum packet size too small to write data"));
4473 /* If we already need another packet, then try to align the end
4474 of this packet to a useful boundary. */
4475 if (todo > 2 * REMOTE_ALIGN_WRITES && todo < len)
4476 todo = ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
4478 /* Append "<memaddr>". */
4479 memaddr = remote_address_masked (memaddr);
4480 p += hexnumstr (p, (ULONGEST) memaddr);
4487 /* Append <len>. Retain the location/size of <len>. It may need to
4488 be adjusted once the packet body has been created. */
4490 plenlen = hexnumstr (p, (ULONGEST) todo);
4498 /* Append the packet body. */
4499 if (packet_format == 'X')
4501 /* Binary mode. Send target system values byte by byte, in
4502 increasing byte addresses. Only escape certain critical
4504 payload_length = remote_escape_output (myaddr, todo, p, &nr_bytes,
4507 /* If not all TODO bytes fit, then we'll need another packet. Make
4508 a second try to keep the end of the packet aligned. Don't do
4509 this if the packet is tiny. */
4510 if (nr_bytes < todo && nr_bytes > 2 * REMOTE_ALIGN_WRITES)
4514 new_nr_bytes = (((memaddr + nr_bytes) & ~(REMOTE_ALIGN_WRITES - 1))
4516 if (new_nr_bytes != nr_bytes)
4517 payload_length = remote_escape_output (myaddr, new_nr_bytes,
4522 p += payload_length;
4523 if (use_length && nr_bytes < todo)
4525 /* Escape chars have filled up the buffer prematurely,
4526 and we have actually sent fewer bytes than planned.
4527 Fix-up the length field of the packet. Use the same
4528 number of characters as before. */
4529 plen += hexnumnstr (plen, (ULONGEST) nr_bytes, plenlen);
4530 *plen = ':'; /* overwrite \0 from hexnumnstr() */
4535 /* Normal mode: Send target system values byte by byte, in
4536 increasing byte addresses. Each byte is encoded as a two hex
4538 nr_bytes = bin2hex (myaddr, p, todo);
4542 putpkt_binary (rs->buf, (int) (p - rs->buf));
4543 getpkt (&rs->buf, &rs->buf_size, 0);
4545 if (rs->buf[0] == 'E')
4547 /* There is no correspondance between what the remote protocol
4548 uses for errors and errno codes. We would like a cleaner way
4549 of representing errors (big enough to include errno codes,
4550 bfd_error codes, and others). But for now just return EIO. */
4555 /* Return NR_BYTES, not TODO, in case escape chars caused us to send
4556 fewer bytes than we'd planned. */
4560 /* Write memory data directly to the remote machine.
4561 This does not inform the data cache; the data cache uses this.
4562 MEMADDR is the address in the remote memory space.
4563 MYADDR is the address of the buffer in our space.
4564 LEN is the number of bytes.
4566 Returns number of bytes transferred, or 0 (setting errno) for
4567 error. Only transfer a single packet. */
4570 remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, int len)
4572 char *packet_format = 0;
4574 /* Check whether the target supports binary download. */
4575 check_binary_download (memaddr);
4577 switch (remote_protocol_packets[PACKET_X].support)
4580 packet_format = "X";
4582 case PACKET_DISABLE:
4583 packet_format = "M";
4585 case PACKET_SUPPORT_UNKNOWN:
4586 internal_error (__FILE__, __LINE__,
4587 _("remote_write_bytes: bad internal state"));
4589 internal_error (__FILE__, __LINE__, _("bad switch"));
4592 return remote_write_bytes_aux (packet_format,
4593 memaddr, myaddr, len, packet_format[0], 1);
4596 /* Read memory data directly from the remote machine.
4597 This does not use the data cache; the data cache uses this.
4598 MEMADDR is the address in the remote memory space.
4599 MYADDR is the address of the buffer in our space.
4600 LEN is the number of bytes.
4602 Returns number of bytes transferred, or 0 for error. */
4604 /* NOTE: cagney/1999-10-18: This function (and its siblings in other
4605 remote targets) shouldn't attempt to read the entire buffer.
4606 Instead it should read a single packet worth of data and then
4607 return the byte size of that packet to the caller. The caller (its
4608 caller and its callers caller ;-) already contains code for
4609 handling partial reads. */
4612 remote_read_bytes (CORE_ADDR memaddr, gdb_byte *myaddr, int len)
4614 struct remote_state *rs = get_remote_state ();
4615 int max_buf_size; /* Max size of packet output buffer. */
4621 max_buf_size = get_memory_read_packet_size ();
4622 /* The packet buffer will be large enough for the payload;
4623 get_memory_packet_size ensures this. */
4632 todo = min (len, max_buf_size / 2); /* num bytes that will fit */
4634 /* construct "m"<memaddr>","<len>" */
4635 /* sprintf (rs->buf, "m%lx,%x", (unsigned long) memaddr, todo); */
4636 memaddr = remote_address_masked (memaddr);
4639 p += hexnumstr (p, (ULONGEST) memaddr);
4641 p += hexnumstr (p, (ULONGEST) todo);
4645 getpkt (&rs->buf, &rs->buf_size, 0);
4647 if (rs->buf[0] == 'E'
4648 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
4649 && rs->buf[3] == '\0')
4651 /* There is no correspondance between what the remote
4652 protocol uses for errors and errno codes. We would like
4653 a cleaner way of representing errors (big enough to
4654 include errno codes, bfd_error codes, and others). But
4655 for now just return EIO. */
4660 /* Reply describes memory byte by byte,
4661 each byte encoded as two hex characters. */
4664 if ((i = hex2bin (p, myaddr, todo)) < todo)
4666 /* Reply is short. This means that we were able to read
4667 only part of what we wanted to. */
4668 return i + (origlen - len);
4677 /* Read or write LEN bytes from inferior memory at MEMADDR,
4678 transferring to or from debugger address BUFFER. Write to inferior
4679 if SHOULD_WRITE is nonzero. Returns length of data written or
4680 read; 0 for error. TARGET is unused. */
4683 remote_xfer_memory (CORE_ADDR mem_addr, gdb_byte *buffer, int mem_len,
4684 int should_write, struct mem_attrib *attrib,
4685 struct target_ops *target)
4690 res = remote_write_bytes (mem_addr, buffer, mem_len);
4692 res = remote_read_bytes (mem_addr, buffer, mem_len);
4697 /* Sends a packet with content determined by the printf format string
4698 FORMAT and the remaining arguments, then gets the reply. Returns
4699 whether the packet was a success, a failure, or unknown. */
4702 remote_send_printf (const char *format, ...)
4704 struct remote_state *rs = get_remote_state ();
4705 int max_size = get_remote_packet_size ();
4708 va_start (ap, format);
4711 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
4712 internal_error (__FILE__, __LINE__, "Too long remote packet.");
4714 if (putpkt (rs->buf) < 0)
4715 error (_("Communication problem with target."));
4718 getpkt (&rs->buf, &rs->buf_size, 0);
4720 return packet_check_result (rs->buf);
4724 restore_remote_timeout (void *p)
4726 int value = *(int *)p;
4727 remote_timeout = value;
4730 /* Flash writing can take quite some time. We'll set
4731 effectively infinite timeout for flash operations.
4732 In future, we'll need to decide on a better approach. */
4733 static const int remote_flash_timeout = 1000;
4736 remote_flash_erase (struct target_ops *ops,
4737 ULONGEST address, LONGEST length)
4739 int saved_remote_timeout = remote_timeout;
4740 enum packet_result ret;
4742 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
4743 &saved_remote_timeout);
4744 remote_timeout = remote_flash_timeout;
4746 ret = remote_send_printf ("vFlashErase:%s,%s",
4751 case PACKET_UNKNOWN:
4752 error (_("Remote target does not support flash erase"));
4754 error (_("Error erasing flash with vFlashErase packet"));
4759 do_cleanups (back_to);
4763 remote_flash_write (struct target_ops *ops,
4764 ULONGEST address, LONGEST length,
4765 const gdb_byte *data)
4767 int saved_remote_timeout = remote_timeout;
4769 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
4770 &saved_remote_timeout);
4772 remote_timeout = remote_flash_timeout;
4773 ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length, 'X', 0);
4774 do_cleanups (back_to);
4780 remote_flash_done (struct target_ops *ops)
4782 int saved_remote_timeout = remote_timeout;
4784 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
4785 &saved_remote_timeout);
4787 remote_timeout = remote_flash_timeout;
4788 ret = remote_send_printf ("vFlashDone");
4789 do_cleanups (back_to);
4793 case PACKET_UNKNOWN:
4794 error (_("Remote target does not support vFlashDone"));
4796 error (_("Error finishing flash operation"));
4803 remote_files_info (struct target_ops *ignore)
4805 puts_filtered ("Debugging a target over a serial line.\n");
4808 /* Stuff for dealing with the packets which are part of this protocol.
4809 See comment at top of file for details. */
4811 /* Read a single character from the remote end. */
4814 readchar (int timeout)
4818 ch = serial_readchar (remote_desc, timeout);
4823 switch ((enum serial_rc) ch)
4826 target_mourn_inferior ();
4827 error (_("Remote connection closed"));
4830 perror_with_name (_("Remote communication error"));
4832 case SERIAL_TIMEOUT:
4838 /* Send the command in *BUF to the remote machine, and read the reply
4839 into *BUF. Report an error if we get an error reply. Resize
4840 *BUF using xrealloc if necessary to hold the result, and update
4844 remote_send (char **buf,
4848 getpkt (buf, sizeof_buf, 0);
4850 if ((*buf)[0] == 'E')
4851 error (_("Remote failure reply: %s"), *buf);
4854 /* Display a null-terminated packet on stdout, for debugging, using C
4858 print_packet (char *buf)
4860 puts_filtered ("\"");
4861 fputstr_filtered (buf, '"', gdb_stdout);
4862 puts_filtered ("\"");
4868 return putpkt_binary (buf, strlen (buf));
4871 /* Send a packet to the remote machine, with error checking. The data
4872 of the packet is in BUF. The string in BUF can be at most
4873 get_remote_packet_size () - 5 to account for the $, # and checksum,
4874 and for a possible /0 if we are debugging (remote_debug) and want
4875 to print the sent packet as a string. */
4878 putpkt_binary (char *buf, int cnt)
4880 struct remote_state *rs = get_remote_state ();
4882 unsigned char csum = 0;
4883 char *buf2 = alloca (cnt + 6);
4889 /* We're sending out a new packet. Make sure we don't look at a
4890 stale cached response. */
4891 rs->cached_wait_status = 0;
4893 /* Copy the packet into buffer BUF2, encapsulating it
4894 and giving it a checksum. */
4899 for (i = 0; i < cnt; i++)
4905 *p++ = tohex ((csum >> 4) & 0xf);
4906 *p++ = tohex (csum & 0xf);
4908 /* Send it over and over until we get a positive ack. */
4912 int started_error_output = 0;
4917 fprintf_unfiltered (gdb_stdlog, "Sending packet: ");
4918 fputstrn_unfiltered (buf2, p - buf2, 0, gdb_stdlog);
4919 fprintf_unfiltered (gdb_stdlog, "...");
4920 gdb_flush (gdb_stdlog);
4922 if (serial_write (remote_desc, buf2, p - buf2))
4923 perror_with_name (_("putpkt: write failed"));
4925 /* Read until either a timeout occurs (-2) or '+' is read. */
4928 ch = readchar (remote_timeout);
4936 case SERIAL_TIMEOUT:
4938 if (started_error_output)
4940 putchar_unfiltered ('\n');
4941 started_error_output = 0;
4950 fprintf_unfiltered (gdb_stdlog, "Ack\n");
4954 fprintf_unfiltered (gdb_stdlog, "Nak\n");
4955 case SERIAL_TIMEOUT:
4959 break; /* Retransmit buffer. */
4963 fprintf_unfiltered (gdb_stdlog,
4964 "Packet instead of Ack, ignoring it\n");
4965 /* It's probably an old response sent because an ACK
4966 was lost. Gobble up the packet and ack it so it
4967 doesn't get retransmitted when we resend this
4970 serial_write (remote_desc, "+", 1);
4971 continue; /* Now, go look for +. */
4976 if (!started_error_output)
4978 started_error_output = 1;
4979 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
4981 fputc_unfiltered (ch & 0177, gdb_stdlog);
4985 break; /* Here to retransmit. */
4989 /* This is wrong. If doing a long backtrace, the user should be
4990 able to get out next time we call QUIT, without anything as
4991 violent as interrupt_query. If we want to provide a way out of
4992 here without getting to the next QUIT, it should be based on
4993 hitting ^C twice as in remote_wait. */
5003 /* Come here after finding the start of a frame when we expected an
5004 ack. Do our best to discard the rest of this packet. */
5013 c = readchar (remote_timeout);
5016 case SERIAL_TIMEOUT:
5017 /* Nothing we can do. */
5020 /* Discard the two bytes of checksum and stop. */
5021 c = readchar (remote_timeout);
5023 c = readchar (remote_timeout);
5026 case '*': /* Run length encoding. */
5027 /* Discard the repeat count. */
5028 c = readchar (remote_timeout);
5033 /* A regular character. */
5039 /* Come here after finding the start of the frame. Collect the rest
5040 into *BUF, verifying the checksum, length, and handling run-length
5041 compression. NUL terminate the buffer. If there is not enough room,
5042 expand *BUF using xrealloc.
5044 Returns -1 on error, number of characters in buffer (ignoring the
5045 trailing NULL) on success. (could be extended to return one of the
5046 SERIAL status indications). */
5049 read_frame (char **buf_p,
5062 c = readchar (remote_timeout);
5065 case SERIAL_TIMEOUT:
5067 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
5071 fputs_filtered ("Saw new packet start in middle of old one\n",
5073 return -1; /* Start a new packet, count retries. */
5076 unsigned char pktcsum;
5082 check_0 = readchar (remote_timeout);
5084 check_1 = readchar (remote_timeout);
5086 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
5089 fputs_filtered ("Timeout in checksum, retrying\n",
5093 else if (check_0 < 0 || check_1 < 0)
5096 fputs_filtered ("Communication error in checksum\n",
5101 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
5102 if (csum == pktcsum)
5107 fprintf_filtered (gdb_stdlog,
5108 "Bad checksum, sentsum=0x%x, csum=0x%x, buf=",
5110 fputstrn_filtered (buf, bc, 0, gdb_stdlog);
5111 fputs_filtered ("\n", gdb_stdlog);
5113 /* Number of characters in buffer ignoring trailing
5117 case '*': /* Run length encoding. */
5122 c = readchar (remote_timeout);
5124 repeat = c - ' ' + 3; /* Compute repeat count. */
5126 /* The character before ``*'' is repeated. */
5128 if (repeat > 0 && repeat <= 255 && bc > 0)
5130 if (bc + repeat - 1 >= *sizeof_buf - 1)
5132 /* Make some more room in the buffer. */
5133 *sizeof_buf += repeat;
5134 *buf_p = xrealloc (*buf_p, *sizeof_buf);
5138 memset (&buf[bc], buf[bc - 1], repeat);
5144 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
5148 if (bc >= *sizeof_buf - 1)
5150 /* Make some more room in the buffer. */
5152 *buf_p = xrealloc (*buf_p, *sizeof_buf);
5163 /* Read a packet from the remote machine, with error checking, and
5164 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
5165 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
5166 rather than timing out; this is used (in synchronous mode) to wait
5167 for a target that is is executing user code to stop. */
5168 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
5169 don't have to change all the calls to getpkt to deal with the
5170 return value, because at the moment I don't know what the right
5171 thing to do it for those. */
5179 timed_out = getpkt_sane (buf, sizeof_buf, forever);
5183 /* Read a packet from the remote machine, with error checking, and
5184 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
5185 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
5186 rather than timing out; this is used (in synchronous mode) to wait
5187 for a target that is is executing user code to stop. If FOREVER ==
5188 0, this function is allowed to time out gracefully and return an
5189 indication of this to the caller. Otherwise return the number
5192 getpkt_sane (char **buf, long *sizeof_buf, int forever)
5194 struct remote_state *rs = get_remote_state ();
5200 /* We're reading a new response. Make sure we don't look at a
5201 previously cached response. */
5202 rs->cached_wait_status = 0;
5204 strcpy (*buf, "timeout");
5208 timeout = watchdog > 0 ? watchdog : -1;
5212 timeout = remote_timeout;
5216 for (tries = 1; tries <= MAX_TRIES; tries++)
5218 /* This can loop forever if the remote side sends us characters
5219 continuously, but if it pauses, we'll get a zero from
5220 readchar because of timeout. Then we'll count that as a
5223 /* Note that we will only wait forever prior to the start of a
5224 packet. After that, we expect characters to arrive at a
5225 brisk pace. They should show up within remote_timeout
5230 c = readchar (timeout);
5232 if (c == SERIAL_TIMEOUT)
5234 if (forever) /* Watchdog went off? Kill the target. */
5237 target_mourn_inferior ();
5238 error (_("Watchdog timeout has expired. Target detached."));
5241 fputs_filtered ("Timed out.\n", gdb_stdlog);
5247 /* We've found the start of a packet, now collect the data. */
5249 val = read_frame (buf, sizeof_buf);
5255 fprintf_unfiltered (gdb_stdlog, "Packet received: ");
5256 fputstrn_unfiltered (*buf, val, 0, gdb_stdlog);
5257 fprintf_unfiltered (gdb_stdlog, "\n");
5259 serial_write (remote_desc, "+", 1);
5263 /* Try the whole thing again. */
5265 serial_write (remote_desc, "-", 1);
5268 /* We have tried hard enough, and just can't receive the packet.
5271 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
5272 serial_write (remote_desc, "+", 1);
5279 /* Use catch_errors so the user can quit from gdb even when we aren't on
5280 speaking terms with the remote system. */
5281 catch_errors ((catch_errors_ftype *) putpkt, "k", "", RETURN_MASK_ERROR);
5283 /* Don't wait for it to die. I'm not really sure it matters whether
5284 we do or not. For the existing stubs, kill is a noop. */
5285 target_mourn_inferior ();
5288 /* Async version of remote_kill. */
5290 remote_async_kill (void)
5292 /* Unregister the file descriptor from the event loop. */
5293 if (target_is_async_p ())
5294 serial_async (remote_desc, NULL, 0);
5296 /* Use catch_errors so the user can quit from gdb even when we
5297 aren't on speaking terms with the remote system. */
5298 catch_errors ((catch_errors_ftype *) putpkt, "k", "", RETURN_MASK_ERROR);
5300 /* Don't wait for it to die. I'm not really sure it matters whether
5301 we do or not. For the existing stubs, kill is a noop. */
5302 target_mourn_inferior ();
5308 remote_mourn_1 (&remote_ops);
5312 remote_async_mourn (void)
5314 remote_mourn_1 (&remote_async_ops);
5317 /* Worker function for remote_mourn. */
5319 remote_mourn_1 (struct target_ops *target)
5321 unpush_target (target);
5322 generic_mourn_inferior ();
5326 extended_remote_mourn_1 (struct target_ops *target)
5328 struct remote_state *rs = get_remote_state ();
5330 /* Unlike "target remote", we do not want to unpush the target; then
5331 the next time the user says "run", we won't be connected. */
5333 /* Call common code to mark the inferior as not running. */
5334 generic_mourn_inferior ();
5336 /* Check whether the target is running now - some remote stubs
5337 automatically restart after kill. */
5339 getpkt (&rs->buf, &rs->buf_size, 0);
5341 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
5343 /* Assume that the target has been restarted. Set inferior_ptid
5344 so that bits of core GDB realizes there's something here, e.g.,
5345 so that the user can say "kill" again. */
5346 inferior_ptid = pid_to_ptid (MAGIC_NULL_PID);
5350 /* Mark this (still pushed) target as not executable until we
5352 target_mark_exited (target);
5357 extended_remote_mourn (void)
5359 extended_remote_mourn_1 (&extended_remote_ops);
5363 extended_async_remote_mourn (void)
5365 extended_remote_mourn_1 (&extended_async_remote_ops);
5369 extended_remote_run (char *args)
5371 struct remote_state *rs = get_remote_state ();
5375 /* If the user has disabled vRun support, or we have detected that
5376 support is not available, do not try it. */
5377 if (remote_protocol_packets[PACKET_vRun].support == PACKET_DISABLE)
5380 strcpy (rs->buf, "vRun;");
5381 len = strlen (rs->buf);
5383 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
5384 error (_("Remote file name too long for run packet"));
5385 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len, 0);
5389 struct cleanup *back_to;
5393 argv = buildargv (args);
5394 back_to = make_cleanup ((void (*) (void *)) freeargv, argv);
5395 for (i = 0; argv[i] != NULL; i++)
5397 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
5398 error (_("Argument list too long for run packet"));
5399 rs->buf[len++] = ';';
5400 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len, 0);
5402 do_cleanups (back_to);
5405 rs->buf[len++] = '\0';
5408 getpkt (&rs->buf, &rs->buf_size, 0);
5410 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]) == PACKET_OK)
5412 /* We have a wait response; we don't need it, though. All is well. */
5415 else if (remote_protocol_packets[PACKET_vRun].support == PACKET_DISABLE)
5416 /* It wasn't disabled before, but it is now. */
5420 if (remote_exec_file[0] == '\0')
5421 error (_("Running the default executable on the remote target failed; "
5422 "try \"set remote exec-file\"?"));
5424 error (_("Running \"%s\" on the remote target failed"),
5429 /* In the extended protocol we want to be able to do things like
5430 "run" and have them basically work as expected. So we need
5431 a special create_inferior function. We support changing the
5432 executable file and the command line arguments, but not the
5436 extended_remote_create_inferior_1 (char *exec_file, char *args,
5437 char **env, int from_tty,
5440 /* If running asynchronously, register the target file descriptor
5441 with the event loop. */
5442 if (async_p && target_can_async_p ())
5443 target_async (inferior_event_handler, 0);
5445 /* Now restart the remote server. */
5446 if (extended_remote_run (args) == -1)
5448 /* vRun was not supported. Fail if we need it to do what the
5450 if (remote_exec_file[0])
5451 error (_("Remote target does not support \"set remote exec-file\""));
5453 error (_("Remote target does not support \"set args\" or run <ARGS>"));
5455 /* Fall back to "R". */
5456 extended_remote_restart ();
5459 /* Clean up from the last time we ran, before we mark the target
5460 running again. This will mark breakpoints uninserted, and
5461 get_offsets may insert breakpoints. */
5462 init_thread_list ();
5463 init_wait_for_inferior ();
5465 /* Now mark the inferior as running before we do anything else. */
5467 inferior_ptid = pid_to_ptid (MAGIC_NULL_PID);
5469 target_mark_running (&extended_async_remote_ops);
5471 target_mark_running (&extended_remote_ops);
5473 /* Get updated offsets, if the stub uses qOffsets. */
5478 extended_remote_create_inferior (char *exec_file, char *args,
5479 char **env, int from_tty)
5481 extended_remote_create_inferior_1 (exec_file, args, env, from_tty, 0);
5485 extended_remote_async_create_inferior (char *exec_file, char *args,
5486 char **env, int from_tty)
5488 extended_remote_create_inferior_1 (exec_file, args, env, from_tty, 1);
5492 /* Insert a breakpoint. On targets that have software breakpoint
5493 support, we ask the remote target to do the work; on targets
5494 which don't, we insert a traditional memory breakpoint. */
5497 remote_insert_breakpoint (struct bp_target_info *bp_tgt)
5499 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
5500 If it succeeds, then set the support to PACKET_ENABLE. If it
5501 fails, and the user has explicitly requested the Z support then
5502 report an error, otherwise, mark it disabled and go on. */
5504 if (remote_protocol_packets[PACKET_Z0].support != PACKET_DISABLE)
5507 struct remote_state *rs;
5510 gdbarch_breakpoint_from_pc
5511 (current_gdbarch, &bp_tgt->placed_address, &bp_tgt->placed_size);
5513 rs = get_remote_state ();
5519 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
5520 p += hexnumstr (p, addr);
5521 sprintf (p, ",%d", bp_tgt->placed_size);
5524 getpkt (&rs->buf, &rs->buf_size, 0);
5526 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
5532 case PACKET_UNKNOWN:
5537 return memory_insert_breakpoint (bp_tgt);
5541 remote_remove_breakpoint (struct bp_target_info *bp_tgt)
5543 CORE_ADDR addr = bp_tgt->placed_address;
5544 struct remote_state *rs = get_remote_state ();
5547 if (remote_protocol_packets[PACKET_Z0].support != PACKET_DISABLE)
5555 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
5556 p += hexnumstr (p, addr);
5557 sprintf (p, ",%d", bp_tgt->placed_size);
5560 getpkt (&rs->buf, &rs->buf_size, 0);
5562 return (rs->buf[0] == 'E');
5565 return memory_remove_breakpoint (bp_tgt);
5569 watchpoint_to_Z_packet (int type)
5574 return Z_PACKET_WRITE_WP;
5577 return Z_PACKET_READ_WP;
5580 return Z_PACKET_ACCESS_WP;
5583 internal_error (__FILE__, __LINE__,
5584 _("hw_bp_to_z: bad watchpoint type %d"), type);
5589 remote_insert_watchpoint (CORE_ADDR addr, int len, int type)
5591 struct remote_state *rs = get_remote_state ();
5593 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
5595 if (remote_protocol_packets[PACKET_Z0 + packet].support == PACKET_DISABLE)
5598 sprintf (rs->buf, "Z%x,", packet);
5599 p = strchr (rs->buf, '\0');
5600 addr = remote_address_masked (addr);
5601 p += hexnumstr (p, (ULONGEST) addr);
5602 sprintf (p, ",%x", len);
5605 getpkt (&rs->buf, &rs->buf_size, 0);
5607 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
5610 case PACKET_UNKNOWN:
5615 internal_error (__FILE__, __LINE__,
5616 _("remote_insert_watchpoint: reached end of function"));
5621 remote_remove_watchpoint (CORE_ADDR addr, int len, int type)
5623 struct remote_state *rs = get_remote_state ();
5625 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
5627 if (remote_protocol_packets[PACKET_Z0 + packet].support == PACKET_DISABLE)
5630 sprintf (rs->buf, "z%x,", packet);
5631 p = strchr (rs->buf, '\0');
5632 addr = remote_address_masked (addr);
5633 p += hexnumstr (p, (ULONGEST) addr);
5634 sprintf (p, ",%x", len);
5636 getpkt (&rs->buf, &rs->buf_size, 0);
5638 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
5641 case PACKET_UNKNOWN:
5646 internal_error (__FILE__, __LINE__,
5647 _("remote_remove_watchpoint: reached end of function"));
5651 int remote_hw_watchpoint_limit = -1;
5652 int remote_hw_breakpoint_limit = -1;
5655 remote_check_watch_resources (int type, int cnt, int ot)
5657 if (type == bp_hardware_breakpoint)
5659 if (remote_hw_breakpoint_limit == 0)
5661 else if (remote_hw_breakpoint_limit < 0)
5663 else if (cnt <= remote_hw_breakpoint_limit)
5668 if (remote_hw_watchpoint_limit == 0)
5670 else if (remote_hw_watchpoint_limit < 0)
5674 else if (cnt <= remote_hw_watchpoint_limit)
5681 remote_stopped_by_watchpoint (void)
5683 return remote_stopped_by_watchpoint_p;
5687 remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
5690 if (remote_stopped_by_watchpoint ())
5692 *addr_p = remote_watch_data_address;
5701 remote_insert_hw_breakpoint (struct bp_target_info *bp_tgt)
5704 struct remote_state *rs;
5707 /* The length field should be set to the size of a breakpoint
5708 instruction, even though we aren't inserting one ourselves. */
5710 gdbarch_breakpoint_from_pc
5711 (current_gdbarch, &bp_tgt->placed_address, &bp_tgt->placed_size);
5713 if (remote_protocol_packets[PACKET_Z1].support == PACKET_DISABLE)
5716 rs = get_remote_state ();
5723 addr = remote_address_masked (bp_tgt->placed_address);
5724 p += hexnumstr (p, (ULONGEST) addr);
5725 sprintf (p, ",%x", bp_tgt->placed_size);
5728 getpkt (&rs->buf, &rs->buf_size, 0);
5730 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
5733 case PACKET_UNKNOWN:
5738 internal_error (__FILE__, __LINE__,
5739 _("remote_insert_hw_breakpoint: reached end of function"));
5744 remote_remove_hw_breakpoint (struct bp_target_info *bp_tgt)
5747 struct remote_state *rs = get_remote_state ();
5750 if (remote_protocol_packets[PACKET_Z1].support == PACKET_DISABLE)
5757 addr = remote_address_masked (bp_tgt->placed_address);
5758 p += hexnumstr (p, (ULONGEST) addr);
5759 sprintf (p, ",%x", bp_tgt->placed_size);
5762 getpkt (&rs->buf, &rs->buf_size, 0);
5764 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
5767 case PACKET_UNKNOWN:
5772 internal_error (__FILE__, __LINE__,
5773 _("remote_remove_hw_breakpoint: reached end of function"));
5776 /* Some targets are only capable of doing downloads, and afterwards
5777 they switch to the remote serial protocol. This function provides
5778 a clean way to get from the download target to the remote target.
5779 It's basically just a wrapper so that we don't have to expose any
5780 of the internal workings of remote.c.
5782 Prior to calling this routine, you should shutdown the current
5783 target code, else you will get the "A program is being debugged
5784 already..." message. Usually a call to pop_target() suffices. */
5787 push_remote_target (char *name, int from_tty)
5789 printf_filtered (_("Switching to remote protocol\n"));
5790 remote_open (name, from_tty);
5793 /* Table used by the crc32 function to calcuate the checksum. */
5795 static unsigned long crc32_table[256] =
5798 static unsigned long
5799 crc32 (unsigned char *buf, int len, unsigned int crc)
5801 if (!crc32_table[1])
5803 /* Initialize the CRC table and the decoding table. */
5807 for (i = 0; i < 256; i++)
5809 for (c = i << 24, j = 8; j > 0; --j)
5810 c = c & 0x80000000 ? (c << 1) ^ 0x04c11db7 : (c << 1);
5817 crc = (crc << 8) ^ crc32_table[((crc >> 24) ^ *buf) & 255];
5823 /* compare-sections command
5825 With no arguments, compares each loadable section in the exec bfd
5826 with the same memory range on the target, and reports mismatches.
5827 Useful for verifying the image on the target against the exec file.
5828 Depends on the target understanding the new "qCRC:" request. */
5830 /* FIXME: cagney/1999-10-26: This command should be broken down into a
5831 target method (target verify memory) and generic version of the
5832 actual command. This will allow other high-level code (especially
5833 generic_load()) to make use of this target functionality. */
5836 compare_sections_command (char *args, int from_tty)
5838 struct remote_state *rs = get_remote_state ();
5840 unsigned long host_crc, target_crc;
5841 extern bfd *exec_bfd;
5842 struct cleanup *old_chain;
5845 const char *sectname;
5852 error (_("command cannot be used without an exec file"));
5853 if (!current_target.to_shortname ||
5854 strcmp (current_target.to_shortname, "remote") != 0)
5855 error (_("command can only be used with remote target"));
5857 for (s = exec_bfd->sections; s; s = s->next)
5859 if (!(s->flags & SEC_LOAD))
5860 continue; /* skip non-loadable section */
5862 size = bfd_get_section_size (s);
5864 continue; /* skip zero-length section */
5866 sectname = bfd_get_section_name (exec_bfd, s);
5867 if (args && strcmp (args, sectname) != 0)
5868 continue; /* not the section selected by user */
5870 matched = 1; /* do this section */
5872 /* FIXME: assumes lma can fit into long. */
5873 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
5874 (long) lma, (long) size);
5877 /* Be clever; compute the host_crc before waiting for target
5879 sectdata = xmalloc (size);
5880 old_chain = make_cleanup (xfree, sectdata);
5881 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
5882 host_crc = crc32 ((unsigned char *) sectdata, size, 0xffffffff);
5884 getpkt (&rs->buf, &rs->buf_size, 0);
5885 if (rs->buf[0] == 'E')
5886 error (_("target memory fault, section %s, range 0x%s -- 0x%s"),
5887 sectname, paddr (lma), paddr (lma + size));
5888 if (rs->buf[0] != 'C')
5889 error (_("remote target does not support this operation"));
5891 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
5892 target_crc = target_crc * 16 + fromhex (*tmp);
5894 printf_filtered ("Section %s, range 0x%s -- 0x%s: ",
5895 sectname, paddr (lma), paddr (lma + size));
5896 if (host_crc == target_crc)
5897 printf_filtered ("matched.\n");
5900 printf_filtered ("MIS-MATCHED!\n");
5904 do_cleanups (old_chain);
5907 warning (_("One or more sections of the remote executable does not match\n\
5908 the loaded file\n"));
5909 if (args && !matched)
5910 printf_filtered (_("No loaded section named '%s'.\n"), args);
5913 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
5914 into remote target. The number of bytes written to the remote
5915 target is returned, or -1 for error. */
5918 remote_write_qxfer (struct target_ops *ops, const char *object_name,
5919 const char *annex, const gdb_byte *writebuf,
5920 ULONGEST offset, LONGEST len,
5921 struct packet_config *packet)
5926 struct remote_state *rs = get_remote_state ();
5927 int max_size = get_memory_write_packet_size ();
5929 if (packet->support == PACKET_DISABLE)
5932 /* Insert header. */
5933 i = snprintf (rs->buf, max_size,
5934 "qXfer:%s:write:%s:%s:",
5935 object_name, annex ? annex : "",
5936 phex_nz (offset, sizeof offset));
5937 max_size -= (i + 1);
5939 /* Escape as much data as fits into rs->buf. */
5940 buf_len = remote_escape_output
5941 (writebuf, len, (rs->buf + i), &max_size, max_size);
5943 if (putpkt_binary (rs->buf, i + buf_len) < 0
5944 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
5945 || packet_ok (rs->buf, packet) != PACKET_OK)
5948 unpack_varlen_hex (rs->buf, &n);
5952 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
5953 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
5954 number of bytes read is returned, or 0 for EOF, or -1 for error.
5955 The number of bytes read may be less than LEN without indicating an
5956 EOF. PACKET is checked and updated to indicate whether the remote
5957 target supports this object. */
5960 remote_read_qxfer (struct target_ops *ops, const char *object_name,
5962 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
5963 struct packet_config *packet)
5965 static char *finished_object;
5966 static char *finished_annex;
5967 static ULONGEST finished_offset;
5969 struct remote_state *rs = get_remote_state ();
5970 unsigned int total = 0;
5971 LONGEST i, n, packet_len;
5973 if (packet->support == PACKET_DISABLE)
5976 /* Check whether we've cached an end-of-object packet that matches
5978 if (finished_object)
5980 if (strcmp (object_name, finished_object) == 0
5981 && strcmp (annex ? annex : "", finished_annex) == 0
5982 && offset == finished_offset)
5985 /* Otherwise, we're now reading something different. Discard
5987 xfree (finished_object);
5988 xfree (finished_annex);
5989 finished_object = NULL;
5990 finished_annex = NULL;
5993 /* Request only enough to fit in a single packet. The actual data
5994 may not, since we don't know how much of it will need to be escaped;
5995 the target is free to respond with slightly less data. We subtract
5996 five to account for the response type and the protocol frame. */
5997 n = min (get_remote_packet_size () - 5, len);
5998 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
5999 object_name, annex ? annex : "",
6000 phex_nz (offset, sizeof offset),
6001 phex_nz (n, sizeof n));
6002 i = putpkt (rs->buf);
6007 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
6008 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
6011 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
6012 error (_("Unknown remote qXfer reply: %s"), rs->buf);
6014 /* 'm' means there is (or at least might be) more data after this
6015 batch. That does not make sense unless there's at least one byte
6016 of data in this reply. */
6017 if (rs->buf[0] == 'm' && packet_len == 1)
6018 error (_("Remote qXfer reply contained no data."));
6020 /* Got some data. */
6021 i = remote_unescape_input (rs->buf + 1, packet_len - 1, readbuf, n);
6023 /* 'l' is an EOF marker, possibly including a final block of data,
6024 or possibly empty. If we have the final block of a non-empty
6025 object, record this fact to bypass a subsequent partial read. */
6026 if (rs->buf[0] == 'l' && offset + i > 0)
6028 finished_object = xstrdup (object_name);
6029 finished_annex = xstrdup (annex ? annex : "");
6030 finished_offset = offset + i;
6037 remote_xfer_partial (struct target_ops *ops, enum target_object object,
6038 const char *annex, gdb_byte *readbuf,
6039 const gdb_byte *writebuf, ULONGEST offset, LONGEST len)
6041 struct remote_state *rs = get_remote_state ();
6046 /* Handle memory using the standard memory routines. */
6047 if (object == TARGET_OBJECT_MEMORY)
6052 /* If the remote target is connected but not running, we should
6053 pass this request down to a lower stratum (e.g. the executable
6055 if (!target_has_execution)
6058 if (writebuf != NULL)
6059 xfered = remote_write_bytes (offset, writebuf, len);
6061 xfered = remote_read_bytes (offset, readbuf, len);
6065 else if (xfered == 0 && errno == 0)
6071 /* Handle SPU memory using qxfer packets. */
6072 if (object == TARGET_OBJECT_SPU)
6075 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
6076 &remote_protocol_packets
6077 [PACKET_qXfer_spu_read]);
6079 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
6080 &remote_protocol_packets
6081 [PACKET_qXfer_spu_write]);
6084 /* Only handle flash writes. */
6085 if (writebuf != NULL)
6091 case TARGET_OBJECT_FLASH:
6092 xfered = remote_flash_write (ops, offset, len, writebuf);
6096 else if (xfered == 0 && errno == 0)
6106 /* Map pre-existing objects onto letters. DO NOT do this for new
6107 objects!!! Instead specify new query packets. */
6110 case TARGET_OBJECT_AVR:
6114 case TARGET_OBJECT_AUXV:
6115 gdb_assert (annex == NULL);
6116 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
6117 &remote_protocol_packets[PACKET_qXfer_auxv]);
6119 case TARGET_OBJECT_AVAILABLE_FEATURES:
6120 return remote_read_qxfer
6121 (ops, "features", annex, readbuf, offset, len,
6122 &remote_protocol_packets[PACKET_qXfer_features]);
6124 case TARGET_OBJECT_LIBRARIES:
6125 return remote_read_qxfer
6126 (ops, "libraries", annex, readbuf, offset, len,
6127 &remote_protocol_packets[PACKET_qXfer_libraries]);
6129 case TARGET_OBJECT_MEMORY_MAP:
6130 gdb_assert (annex == NULL);
6131 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
6132 &remote_protocol_packets[PACKET_qXfer_memory_map]);
6138 /* Note: a zero OFFSET and LEN can be used to query the minimum
6140 if (offset == 0 && len == 0)
6141 return (get_remote_packet_size ());
6142 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
6143 large enough let the caller deal with it. */
6144 if (len < get_remote_packet_size ())
6146 len = get_remote_packet_size ();
6148 /* Except for querying the minimum buffer size, target must be open. */
6150 error (_("remote query is only available after target open"));
6152 gdb_assert (annex != NULL);
6153 gdb_assert (readbuf != NULL);
6159 /* We used one buffer char for the remote protocol q command and
6160 another for the query type. As the remote protocol encapsulation
6161 uses 4 chars plus one extra in case we are debugging
6162 (remote_debug), we have PBUFZIZ - 7 left to pack the query
6165 while (annex[i] && (i < (get_remote_packet_size () - 8)))
6167 /* Bad caller may have sent forbidden characters. */
6168 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
6173 gdb_assert (annex[i] == '\0');
6175 i = putpkt (rs->buf);
6179 getpkt (&rs->buf, &rs->buf_size, 0);
6180 strcpy ((char *) readbuf, rs->buf);
6182 return strlen ((char *) readbuf);
6186 remote_search_memory (struct target_ops* ops,
6187 CORE_ADDR start_addr, ULONGEST search_space_len,
6188 const gdb_byte *pattern, ULONGEST pattern_len,
6189 CORE_ADDR *found_addrp)
6191 struct remote_state *rs = get_remote_state ();
6192 int max_size = get_memory_write_packet_size ();
6193 struct packet_config *packet =
6194 &remote_protocol_packets[PACKET_qSearch_memory];
6195 /* number of packet bytes used to encode the pattern,
6196 this could be more than PATTERN_LEN due to escape characters */
6197 int escaped_pattern_len;
6198 /* amount of pattern that was encodable in the packet */
6199 int used_pattern_len;
6202 ULONGEST found_addr;
6204 /* Don't go to the target if we don't have to.
6205 This is done before checking packet->support to avoid the possibility that
6206 a success for this edge case means the facility works in general. */
6207 if (pattern_len > search_space_len)
6209 if (pattern_len == 0)
6211 *found_addrp = start_addr;
6215 /* If we already know the packet isn't supported, fall back to the simple
6216 way of searching memory. */
6218 if (packet->support == PACKET_DISABLE)
6220 /* Target doesn't provided special support, fall back and use the
6221 standard support (copy memory and do the search here). */
6222 return simple_search_memory (ops, start_addr, search_space_len,
6223 pattern, pattern_len, found_addrp);
6226 /* Insert header. */
6227 i = snprintf (rs->buf, max_size,
6228 "qSearch:memory:%s;%s;",
6229 paddr_nz (start_addr),
6230 phex_nz (search_space_len, sizeof (search_space_len)));
6231 max_size -= (i + 1);
6233 /* Escape as much data as fits into rs->buf. */
6234 escaped_pattern_len =
6235 remote_escape_output (pattern, pattern_len, (rs->buf + i),
6236 &used_pattern_len, max_size);
6238 /* Bail if the pattern is too large. */
6239 if (used_pattern_len != pattern_len)
6240 error ("Pattern is too large to transmit to remote target.");
6242 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
6243 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
6244 || packet_ok (rs->buf, packet) != PACKET_OK)
6246 /* The request may not have worked because the command is not
6247 supported. If so, fall back to the simple way. */
6248 if (packet->support == PACKET_DISABLE)
6250 return simple_search_memory (ops, start_addr, search_space_len,
6251 pattern, pattern_len, found_addrp);
6256 if (rs->buf[0] == '0')
6258 else if (rs->buf[0] == '1')
6261 if (rs->buf[1] != ',')
6262 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
6263 unpack_varlen_hex (rs->buf + 2, &found_addr);
6264 *found_addrp = found_addr;
6267 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
6273 remote_rcmd (char *command,
6274 struct ui_file *outbuf)
6276 struct remote_state *rs = get_remote_state ();
6280 error (_("remote rcmd is only available after target open"));
6282 /* Send a NULL command across as an empty command. */
6283 if (command == NULL)
6286 /* The query prefix. */
6287 strcpy (rs->buf, "qRcmd,");
6288 p = strchr (rs->buf, '\0');
6290 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/) > get_remote_packet_size ())
6291 error (_("\"monitor\" command ``%s'' is too long."), command);
6293 /* Encode the actual command. */
6294 bin2hex ((gdb_byte *) command, p, 0);
6296 if (putpkt (rs->buf) < 0)
6297 error (_("Communication problem with target."));
6299 /* get/display the response */
6304 /* XXX - see also tracepoint.c:remote_get_noisy_reply(). */
6306 getpkt (&rs->buf, &rs->buf_size, 0);
6309 error (_("Target does not support this command."));
6310 if (buf[0] == 'O' && buf[1] != 'K')
6312 remote_console_output (buf + 1); /* 'O' message from stub. */
6315 if (strcmp (buf, "OK") == 0)
6317 if (strlen (buf) == 3 && buf[0] == 'E'
6318 && isdigit (buf[1]) && isdigit (buf[2]))
6320 error (_("Protocol error with Rcmd"));
6322 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
6324 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
6325 fputc_unfiltered (c, outbuf);
6331 static VEC(mem_region_s) *
6332 remote_memory_map (struct target_ops *ops)
6334 VEC(mem_region_s) *result = NULL;
6335 char *text = target_read_stralloc (¤t_target,
6336 TARGET_OBJECT_MEMORY_MAP, NULL);
6340 struct cleanup *back_to = make_cleanup (xfree, text);
6341 result = parse_memory_map (text);
6342 do_cleanups (back_to);
6349 packet_command (char *args, int from_tty)
6351 struct remote_state *rs = get_remote_state ();
6354 error (_("command can only be used with remote target"));
6357 error (_("remote-packet command requires packet text as argument"));
6359 puts_filtered ("sending: ");
6360 print_packet (args);
6361 puts_filtered ("\n");
6364 getpkt (&rs->buf, &rs->buf_size, 0);
6365 puts_filtered ("received: ");
6366 print_packet (rs->buf);
6367 puts_filtered ("\n");
6371 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
6373 static void display_thread_info (struct gdb_ext_thread_info *info);
6375 static void threadset_test_cmd (char *cmd, int tty);
6377 static void threadalive_test (char *cmd, int tty);
6379 static void threadlist_test_cmd (char *cmd, int tty);
6381 int get_and_display_threadinfo (threadref *ref);
6383 static void threadinfo_test_cmd (char *cmd, int tty);
6385 static int thread_display_step (threadref *ref, void *context);
6387 static void threadlist_update_test_cmd (char *cmd, int tty);
6389 static void init_remote_threadtests (void);
6391 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
6394 threadset_test_cmd (char *cmd, int tty)
6396 int sample_thread = SAMPLE_THREAD;
6398 printf_filtered (_("Remote threadset test\n"));
6399 set_thread (sample_thread, 1);
6404 threadalive_test (char *cmd, int tty)
6406 int sample_thread = SAMPLE_THREAD;
6408 if (remote_thread_alive (pid_to_ptid (sample_thread)))
6409 printf_filtered ("PASS: Thread alive test\n");
6411 printf_filtered ("FAIL: Thread alive test\n");
6414 void output_threadid (char *title, threadref *ref);
6417 output_threadid (char *title, threadref *ref)
6421 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
6423 printf_filtered ("%s %s\n", title, (&hexid[0]));
6427 threadlist_test_cmd (char *cmd, int tty)
6430 threadref nextthread;
6431 int done, result_count;
6432 threadref threadlist[3];
6434 printf_filtered ("Remote Threadlist test\n");
6435 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
6436 &result_count, &threadlist[0]))
6437 printf_filtered ("FAIL: threadlist test\n");
6440 threadref *scan = threadlist;
6441 threadref *limit = scan + result_count;
6443 while (scan < limit)
6444 output_threadid (" thread ", scan++);
6449 display_thread_info (struct gdb_ext_thread_info *info)
6451 output_threadid ("Threadid: ", &info->threadid);
6452 printf_filtered ("Name: %s\n ", info->shortname);
6453 printf_filtered ("State: %s\n", info->display);
6454 printf_filtered ("other: %s\n\n", info->more_display);
6458 get_and_display_threadinfo (threadref *ref)
6462 struct gdb_ext_thread_info threadinfo;
6464 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
6465 | TAG_MOREDISPLAY | TAG_DISPLAY;
6466 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
6467 display_thread_info (&threadinfo);
6472 threadinfo_test_cmd (char *cmd, int tty)
6474 int athread = SAMPLE_THREAD;
6478 int_to_threadref (&thread, athread);
6479 printf_filtered ("Remote Threadinfo test\n");
6480 if (!get_and_display_threadinfo (&thread))
6481 printf_filtered ("FAIL cannot get thread info\n");
6485 thread_display_step (threadref *ref, void *context)
6487 /* output_threadid(" threadstep ",ref); *//* simple test */
6488 return get_and_display_threadinfo (ref);
6492 threadlist_update_test_cmd (char *cmd, int tty)
6494 printf_filtered ("Remote Threadlist update test\n");
6495 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
6499 init_remote_threadtests (void)
6501 add_com ("tlist", class_obscure, threadlist_test_cmd, _("\
6502 Fetch and print the remote list of thread identifiers, one pkt only"));
6503 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
6504 _("Fetch and display info about one thread"));
6505 add_com ("tset", class_obscure, threadset_test_cmd,
6506 _("Test setting to a different thread"));
6507 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
6508 _("Iterate through updating all remote thread info"));
6509 add_com ("talive", class_obscure, threadalive_test,
6510 _(" Remote thread alive test "));
6515 /* Convert a thread ID to a string. Returns the string in a static
6519 remote_pid_to_str (ptid_t ptid)
6521 static char buf[32];
6523 xsnprintf (buf, sizeof buf, "Thread %d", ptid_get_pid (ptid));
6527 /* Get the address of the thread local variable in OBJFILE which is
6528 stored at OFFSET within the thread local storage for thread PTID. */
6531 remote_get_thread_local_address (ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
6533 if (remote_protocol_packets[PACKET_qGetTLSAddr].support != PACKET_DISABLE)
6535 struct remote_state *rs = get_remote_state ();
6537 enum packet_result result;
6539 strcpy (p, "qGetTLSAddr:");
6541 p += hexnumstr (p, PIDGET (ptid));
6543 p += hexnumstr (p, offset);
6545 p += hexnumstr (p, lm);
6549 getpkt (&rs->buf, &rs->buf_size, 0);
6550 result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_qGetTLSAddr]);
6551 if (result == PACKET_OK)
6555 unpack_varlen_hex (rs->buf, &result);
6558 else if (result == PACKET_UNKNOWN)
6559 throw_error (TLS_GENERIC_ERROR,
6560 _("Remote target doesn't support qGetTLSAddr packet"));
6562 throw_error (TLS_GENERIC_ERROR,
6563 _("Remote target failed to process qGetTLSAddr request"));
6566 throw_error (TLS_GENERIC_ERROR,
6567 _("TLS not supported or disabled on this target"));
6572 /* Support for inferring a target description based on the current
6573 architecture and the size of a 'g' packet. While the 'g' packet
6574 can have any size (since optional registers can be left off the
6575 end), some sizes are easily recognizable given knowledge of the
6576 approximate architecture. */
6578 struct remote_g_packet_guess
6581 const struct target_desc *tdesc;
6583 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
6584 DEF_VEC_O(remote_g_packet_guess_s);
6586 struct remote_g_packet_data
6588 VEC(remote_g_packet_guess_s) *guesses;
6591 static struct gdbarch_data *remote_g_packet_data_handle;
6594 remote_g_packet_data_init (struct obstack *obstack)
6596 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
6600 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
6601 const struct target_desc *tdesc)
6603 struct remote_g_packet_data *data
6604 = gdbarch_data (gdbarch, remote_g_packet_data_handle);
6605 struct remote_g_packet_guess new_guess, *guess;
6608 gdb_assert (tdesc != NULL);
6611 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
6613 if (guess->bytes == bytes)
6614 internal_error (__FILE__, __LINE__,
6615 "Duplicate g packet description added for size %d",
6618 new_guess.bytes = bytes;
6619 new_guess.tdesc = tdesc;
6620 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
6623 static const struct target_desc *
6624 remote_read_description (struct target_ops *target)
6626 struct remote_g_packet_data *data
6627 = gdbarch_data (current_gdbarch, remote_g_packet_data_handle);
6629 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
6631 struct remote_g_packet_guess *guess;
6633 int bytes = send_g_packet ();
6636 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
6638 if (guess->bytes == bytes)
6639 return guess->tdesc;
6641 /* We discard the g packet. A minor optimization would be to
6642 hold on to it, and fill the register cache once we have selected
6643 an architecture, but it's too tricky to do safely. */
6649 /* Remote file transfer support. This is host-initiated I/O, not
6650 target-initiated; for target-initiated, see remote-fileio.c. */
6652 /* If *LEFT is at least the length of STRING, copy STRING to
6653 *BUFFER, update *BUFFER to point to the new end of the buffer, and
6654 decrease *LEFT. Otherwise raise an error. */
6657 remote_buffer_add_string (char **buffer, int *left, char *string)
6659 int len = strlen (string);
6662 error (_("Packet too long for target."));
6664 memcpy (*buffer, string, len);
6668 /* NUL-terminate the buffer as a convenience, if there is
6674 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
6675 *BUFFER, update *BUFFER to point to the new end of the buffer, and
6676 decrease *LEFT. Otherwise raise an error. */
6679 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
6682 if (2 * len > *left)
6683 error (_("Packet too long for target."));
6685 bin2hex (bytes, *buffer, len);
6689 /* NUL-terminate the buffer as a convenience, if there is
6695 /* If *LEFT is large enough, convert VALUE to hex and add it to
6696 *BUFFER, update *BUFFER to point to the new end of the buffer, and
6697 decrease *LEFT. Otherwise raise an error. */
6700 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
6702 int len = hexnumlen (value);
6705 error (_("Packet too long for target."));
6707 hexnumstr (*buffer, value);
6711 /* NUL-terminate the buffer as a convenience, if there is
6717 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
6718 value, *REMOTE_ERRNO to the remote error number or zero if none
6719 was included, and *ATTACHMENT to point to the start of the annex
6720 if any. The length of the packet isn't needed here; there may
6721 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
6723 Return 0 if the packet could be parsed, -1 if it could not. If
6724 -1 is returned, the other variables may not be initialized. */
6727 remote_hostio_parse_result (char *buffer, int *retcode,
6728 int *remote_errno, char **attachment)
6735 if (buffer[0] != 'F')
6739 *retcode = strtol (&buffer[1], &p, 16);
6740 if (errno != 0 || p == &buffer[1])
6743 /* Check for ",errno". */
6747 *remote_errno = strtol (p + 1, &p2, 16);
6748 if (errno != 0 || p + 1 == p2)
6753 /* Check for ";attachment". If there is no attachment, the
6754 packet should end here. */
6757 *attachment = p + 1;
6760 else if (*p == '\0')
6766 /* Send a prepared I/O packet to the target and read its response.
6767 The prepared packet is in the global RS->BUF before this function
6768 is called, and the answer is there when we return.
6770 COMMAND_BYTES is the length of the request to send, which may include
6771 binary data. WHICH_PACKET is the packet configuration to check
6772 before attempting a packet. If an error occurs, *REMOTE_ERRNO
6773 is set to the error number and -1 is returned. Otherwise the value
6774 returned by the function is returned.
6776 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
6777 attachment is expected; an error will be reported if there's a
6778 mismatch. If one is found, *ATTACHMENT will be set to point into
6779 the packet buffer and *ATTACHMENT_LEN will be set to the
6780 attachment's length. */
6783 remote_hostio_send_command (int command_bytes, int which_packet,
6784 int *remote_errno, char **attachment,
6785 int *attachment_len)
6787 struct remote_state *rs = get_remote_state ();
6788 int ret, bytes_read;
6789 char *attachment_tmp;
6791 if (remote_protocol_packets[which_packet].support == PACKET_DISABLE)
6793 *remote_errno = FILEIO_ENOSYS;
6797 putpkt_binary (rs->buf, command_bytes);
6798 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
6800 /* If it timed out, something is wrong. Don't try to parse the
6804 *remote_errno = FILEIO_EINVAL;
6808 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
6811 *remote_errno = FILEIO_EINVAL;
6813 case PACKET_UNKNOWN:
6814 *remote_errno = FILEIO_ENOSYS;
6820 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
6823 *remote_errno = FILEIO_EINVAL;
6827 /* Make sure we saw an attachment if and only if we expected one. */
6828 if ((attachment_tmp == NULL && attachment != NULL)
6829 || (attachment_tmp != NULL && attachment == NULL))
6831 *remote_errno = FILEIO_EINVAL;
6835 /* If an attachment was found, it must point into the packet buffer;
6836 work out how many bytes there were. */
6837 if (attachment_tmp != NULL)
6839 *attachment = attachment_tmp;
6840 *attachment_len = bytes_read - (*attachment - rs->buf);
6846 /* Open FILENAME on the remote target, using FLAGS and MODE. Return a
6847 remote file descriptor, or -1 if an error occurs (and set
6851 remote_hostio_open (const char *filename, int flags, int mode,
6854 struct remote_state *rs = get_remote_state ();
6856 int left = get_remote_packet_size () - 1;
6858 remote_buffer_add_string (&p, &left, "vFile:open:");
6860 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
6862 remote_buffer_add_string (&p, &left, ",");
6864 remote_buffer_add_int (&p, &left, flags);
6865 remote_buffer_add_string (&p, &left, ",");
6867 remote_buffer_add_int (&p, &left, mode);
6869 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
6870 remote_errno, NULL, NULL);
6873 /* Write up to LEN bytes from WRITE_BUF to FD on the remote target.
6874 Return the number of bytes written, or -1 if an error occurs (and
6875 set *REMOTE_ERRNO). */
6878 remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
6879 ULONGEST offset, int *remote_errno)
6881 struct remote_state *rs = get_remote_state ();
6883 int left = get_remote_packet_size ();
6886 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
6888 remote_buffer_add_int (&p, &left, fd);
6889 remote_buffer_add_string (&p, &left, ",");
6891 remote_buffer_add_int (&p, &left, offset);
6892 remote_buffer_add_string (&p, &left, ",");
6894 p += remote_escape_output (write_buf, len, p, &out_len,
6895 get_remote_packet_size () - (p - rs->buf));
6897 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
6898 remote_errno, NULL, NULL);
6901 /* Read up to LEN bytes FD on the remote target into READ_BUF
6902 Return the number of bytes read, or -1 if an error occurs (and
6903 set *REMOTE_ERRNO). */
6906 remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
6907 ULONGEST offset, int *remote_errno)
6909 struct remote_state *rs = get_remote_state ();
6912 int left = get_remote_packet_size ();
6913 int ret, attachment_len;
6916 remote_buffer_add_string (&p, &left, "vFile:pread:");
6918 remote_buffer_add_int (&p, &left, fd);
6919 remote_buffer_add_string (&p, &left, ",");
6921 remote_buffer_add_int (&p, &left, len);
6922 remote_buffer_add_string (&p, &left, ",");
6924 remote_buffer_add_int (&p, &left, offset);
6926 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
6927 remote_errno, &attachment,
6933 read_len = remote_unescape_input (attachment, attachment_len,
6935 if (read_len != ret)
6936 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
6941 /* Close FD on the remote target. Return 0, or -1 if an error occurs
6942 (and set *REMOTE_ERRNO). */
6945 remote_hostio_close (int fd, int *remote_errno)
6947 struct remote_state *rs = get_remote_state ();
6949 int left = get_remote_packet_size () - 1;
6951 remote_buffer_add_string (&p, &left, "vFile:close:");
6953 remote_buffer_add_int (&p, &left, fd);
6955 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
6956 remote_errno, NULL, NULL);
6959 /* Unlink FILENAME on the remote target. Return 0, or -1 if an error
6960 occurs (and set *REMOTE_ERRNO). */
6963 remote_hostio_unlink (const char *filename, int *remote_errno)
6965 struct remote_state *rs = get_remote_state ();
6967 int left = get_remote_packet_size () - 1;
6969 remote_buffer_add_string (&p, &left, "vFile:unlink:");
6971 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
6974 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
6975 remote_errno, NULL, NULL);
6979 remote_fileio_errno_to_host (int errnum)
7003 case FILEIO_ENOTDIR:
7023 case FILEIO_ENAMETOOLONG:
7024 return ENAMETOOLONG;
7030 remote_hostio_error (int errnum)
7032 int host_error = remote_fileio_errno_to_host (errnum);
7034 if (host_error == -1)
7035 error (_("Unknown remote I/O error %d"), errnum);
7037 error (_("Remote I/O error: %s"), safe_strerror (host_error));
7041 fclose_cleanup (void *file)
7047 remote_hostio_close_cleanup (void *opaque)
7049 int fd = *(int *) opaque;
7052 remote_hostio_close (fd, &remote_errno);
7056 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
7058 struct cleanup *back_to, *close_cleanup;
7059 int retcode, fd, remote_errno, bytes, io_size;
7062 int bytes_in_buffer;
7067 error (_("command can only be used with remote target"));
7069 file = fopen (local_file, "rb");
7071 perror_with_name (local_file);
7072 back_to = make_cleanup (fclose_cleanup, file);
7074 fd = remote_hostio_open (remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
7076 0700, &remote_errno);
7078 remote_hostio_error (remote_errno);
7080 /* Send up to this many bytes at once. They won't all fit in the
7081 remote packet limit, so we'll transfer slightly fewer. */
7082 io_size = get_remote_packet_size ();
7083 buffer = xmalloc (io_size);
7084 make_cleanup (xfree, buffer);
7086 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
7088 bytes_in_buffer = 0;
7091 while (bytes_in_buffer || !saw_eof)
7095 bytes = fread (buffer + bytes_in_buffer, 1, io_size - bytes_in_buffer,
7100 error (_("Error reading %s."), local_file);
7103 /* EOF. Unless there is something still in the
7104 buffer from the last iteration, we are done. */
7106 if (bytes_in_buffer == 0)
7114 bytes += bytes_in_buffer;
7115 bytes_in_buffer = 0;
7117 retcode = remote_hostio_pwrite (fd, buffer, bytes, offset, &remote_errno);
7120 remote_hostio_error (remote_errno);
7121 else if (retcode == 0)
7122 error (_("Remote write of %d bytes returned 0!"), bytes);
7123 else if (retcode < bytes)
7125 /* Short write. Save the rest of the read data for the next
7127 bytes_in_buffer = bytes - retcode;
7128 memmove (buffer, buffer + retcode, bytes_in_buffer);
7134 discard_cleanups (close_cleanup);
7135 if (remote_hostio_close (fd, &remote_errno))
7136 remote_hostio_error (remote_errno);
7139 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
7140 do_cleanups (back_to);
7144 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
7146 struct cleanup *back_to, *close_cleanup;
7147 int retcode, fd, remote_errno, bytes, io_size;
7153 error (_("command can only be used with remote target"));
7155 fd = remote_hostio_open (remote_file, FILEIO_O_RDONLY, 0, &remote_errno);
7157 remote_hostio_error (remote_errno);
7159 file = fopen (local_file, "wb");
7161 perror_with_name (local_file);
7162 back_to = make_cleanup (fclose_cleanup, file);
7164 /* Send up to this many bytes at once. They won't all fit in the
7165 remote packet limit, so we'll transfer slightly fewer. */
7166 io_size = get_remote_packet_size ();
7167 buffer = xmalloc (io_size);
7168 make_cleanup (xfree, buffer);
7170 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
7175 bytes = remote_hostio_pread (fd, buffer, io_size, offset, &remote_errno);
7177 /* Success, but no bytes, means end-of-file. */
7180 remote_hostio_error (remote_errno);
7184 bytes = fwrite (buffer, 1, bytes, file);
7186 perror_with_name (local_file);
7189 discard_cleanups (close_cleanup);
7190 if (remote_hostio_close (fd, &remote_errno))
7191 remote_hostio_error (remote_errno);
7194 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
7195 do_cleanups (back_to);
7199 remote_file_delete (const char *remote_file, int from_tty)
7201 int retcode, remote_errno;
7204 error (_("command can only be used with remote target"));
7206 retcode = remote_hostio_unlink (remote_file, &remote_errno);
7208 remote_hostio_error (remote_errno);
7211 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
7215 remote_put_command (char *args, int from_tty)
7217 struct cleanup *back_to;
7220 argv = buildargv (args);
7223 back_to = make_cleanup_freeargv (argv);
7224 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
7225 error (_("Invalid parameters to remote put"));
7227 remote_file_put (argv[0], argv[1], from_tty);
7229 do_cleanups (back_to);
7233 remote_get_command (char *args, int from_tty)
7235 struct cleanup *back_to;
7238 argv = buildargv (args);
7241 back_to = make_cleanup_freeargv (argv);
7242 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
7243 error (_("Invalid parameters to remote get"));
7245 remote_file_get (argv[0], argv[1], from_tty);
7247 do_cleanups (back_to);
7251 remote_delete_command (char *args, int from_tty)
7253 struct cleanup *back_to;
7256 argv = buildargv (args);
7259 back_to = make_cleanup_freeargv (argv);
7260 if (argv[0] == NULL || argv[1] != NULL)
7261 error (_("Invalid parameters to remote delete"));
7263 remote_file_delete (argv[0], from_tty);
7265 do_cleanups (back_to);
7269 remote_command (char *args, int from_tty)
7271 help_list (remote_cmdlist, "remote ", -1, gdb_stdout);
7275 remote_return_zero (void)
7281 init_remote_ops (void)
7283 remote_ops.to_shortname = "remote";
7284 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
7286 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
7287 Specify the serial device it is connected to\n\
7288 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
7289 remote_ops.to_open = remote_open;
7290 remote_ops.to_close = remote_close;
7291 remote_ops.to_detach = remote_detach;
7292 remote_ops.to_disconnect = remote_disconnect;
7293 remote_ops.to_resume = remote_resume;
7294 remote_ops.to_wait = remote_wait;
7295 remote_ops.to_fetch_registers = remote_fetch_registers;
7296 remote_ops.to_store_registers = remote_store_registers;
7297 remote_ops.to_prepare_to_store = remote_prepare_to_store;
7298 remote_ops.deprecated_xfer_memory = remote_xfer_memory;
7299 remote_ops.to_files_info = remote_files_info;
7300 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
7301 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
7302 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
7303 remote_ops.to_stopped_data_address = remote_stopped_data_address;
7304 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
7305 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
7306 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
7307 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
7308 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
7309 remote_ops.to_kill = remote_kill;
7310 remote_ops.to_load = generic_load;
7311 remote_ops.to_mourn_inferior = remote_mourn;
7312 remote_ops.to_thread_alive = remote_thread_alive;
7313 remote_ops.to_find_new_threads = remote_threads_info;
7314 remote_ops.to_pid_to_str = remote_pid_to_str;
7315 remote_ops.to_extra_thread_info = remote_threads_extra_info;
7316 remote_ops.to_stop = remote_stop;
7317 remote_ops.to_xfer_partial = remote_xfer_partial;
7318 remote_ops.to_rcmd = remote_rcmd;
7319 remote_ops.to_log_command = serial_log_command;
7320 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
7321 remote_ops.to_stratum = process_stratum;
7322 remote_ops.to_has_all_memory = 1;
7323 remote_ops.to_has_memory = 1;
7324 remote_ops.to_has_stack = 1;
7325 remote_ops.to_has_registers = 1;
7326 remote_ops.to_has_execution = 1;
7327 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
7328 remote_ops.to_magic = OPS_MAGIC;
7329 remote_ops.to_memory_map = remote_memory_map;
7330 remote_ops.to_flash_erase = remote_flash_erase;
7331 remote_ops.to_flash_done = remote_flash_done;
7332 remote_ops.to_read_description = remote_read_description;
7333 remote_ops.to_search_memory = remote_search_memory;
7334 remote_ops.to_can_async_p = remote_return_zero;
7335 remote_ops.to_is_async_p = remote_return_zero;
7338 /* Set up the extended remote vector by making a copy of the standard
7339 remote vector and adding to it. */
7342 init_extended_remote_ops (void)
7344 extended_remote_ops = remote_ops;
7346 extended_remote_ops.to_shortname = "extended-remote";
7347 extended_remote_ops.to_longname =
7348 "Extended remote serial target in gdb-specific protocol";
7349 extended_remote_ops.to_doc =
7350 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
7351 Specify the serial device it is connected to (e.g. /dev/ttya).";
7352 extended_remote_ops.to_open = extended_remote_open;
7353 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
7354 extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
7355 extended_remote_ops.to_detach = extended_remote_detach;
7356 extended_remote_ops.to_attach = extended_remote_attach;
7360 remote_can_async_p (void)
7362 /* We're async whenever the serial device is. */
7363 return remote_async_mask_value && serial_can_async_p (remote_desc);
7367 remote_is_async_p (void)
7369 /* We're async whenever the serial device is. */
7370 return remote_async_mask_value && serial_is_async_p (remote_desc);
7373 /* Pass the SERIAL event on and up to the client. One day this code
7374 will be able to delay notifying the client of an event until the
7375 point where an entire packet has been received. */
7377 static void (*async_client_callback) (enum inferior_event_type event_type,
7379 static void *async_client_context;
7380 static serial_event_ftype remote_async_serial_handler;
7383 remote_async_serial_handler (struct serial *scb, void *context)
7385 /* Don't propogate error information up to the client. Instead let
7386 the client find out about the error by querying the target. */
7387 async_client_callback (INF_REG_EVENT, async_client_context);
7391 remote_async (void (*callback) (enum inferior_event_type event_type,
7392 void *context), void *context)
7394 if (remote_async_mask_value == 0)
7395 internal_error (__FILE__, __LINE__,
7396 _("Calling remote_async when async is masked"));
7398 if (callback != NULL)
7400 serial_async (remote_desc, remote_async_serial_handler, NULL);
7401 async_client_callback = callback;
7402 async_client_context = context;
7405 serial_async (remote_desc, NULL, NULL);
7409 remote_async_mask (int new_mask)
7411 int curr_mask = remote_async_mask_value;
7412 remote_async_mask_value = new_mask;
7416 /* Target async and target extended-async.
7418 This are temporary targets, until it is all tested. Eventually
7419 async support will be incorporated int the usual 'remote'
7423 init_remote_async_ops (void)
7425 remote_async_ops.to_shortname = "async";
7426 remote_async_ops.to_longname =
7427 "Remote serial target in async version of the gdb-specific protocol";
7428 remote_async_ops.to_doc =
7429 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
7430 Specify the serial device it is connected to (e.g. /dev/ttya).";
7431 remote_async_ops.to_open = remote_async_open;
7432 remote_async_ops.to_close = remote_close;
7433 remote_async_ops.to_detach = remote_detach;
7434 remote_async_ops.to_disconnect = remote_disconnect;
7435 remote_async_ops.to_resume = remote_async_resume;
7436 remote_async_ops.to_wait = remote_async_wait;
7437 remote_async_ops.to_fetch_registers = remote_fetch_registers;
7438 remote_async_ops.to_store_registers = remote_store_registers;
7439 remote_async_ops.to_prepare_to_store = remote_prepare_to_store;
7440 remote_async_ops.deprecated_xfer_memory = remote_xfer_memory;
7441 remote_async_ops.to_files_info = remote_files_info;
7442 remote_async_ops.to_insert_breakpoint = remote_insert_breakpoint;
7443 remote_async_ops.to_remove_breakpoint = remote_remove_breakpoint;
7444 remote_async_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
7445 remote_async_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
7446 remote_async_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
7447 remote_async_ops.to_insert_watchpoint = remote_insert_watchpoint;
7448 remote_async_ops.to_remove_watchpoint = remote_remove_watchpoint;
7449 remote_async_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
7450 remote_async_ops.to_stopped_data_address = remote_stopped_data_address;
7451 remote_async_ops.to_terminal_inferior = remote_async_terminal_inferior;
7452 remote_async_ops.to_terminal_ours = remote_async_terminal_ours;
7453 remote_async_ops.to_kill = remote_async_kill;
7454 remote_async_ops.to_load = generic_load;
7455 remote_async_ops.to_mourn_inferior = remote_async_mourn;
7456 remote_async_ops.to_thread_alive = remote_thread_alive;
7457 remote_async_ops.to_find_new_threads = remote_threads_info;
7458 remote_async_ops.to_pid_to_str = remote_pid_to_str;
7459 remote_async_ops.to_extra_thread_info = remote_threads_extra_info;
7460 remote_async_ops.to_stop = remote_stop;
7461 remote_async_ops.to_xfer_partial = remote_xfer_partial;
7462 remote_async_ops.to_rcmd = remote_rcmd;
7463 remote_async_ops.to_get_thread_local_address
7464 = remote_get_thread_local_address;
7465 remote_async_ops.to_stratum = process_stratum;
7466 remote_async_ops.to_has_all_memory = 1;
7467 remote_async_ops.to_has_memory = 1;
7468 remote_async_ops.to_has_stack = 1;
7469 remote_async_ops.to_has_registers = 1;
7470 remote_async_ops.to_has_execution = 1;
7471 remote_async_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
7472 remote_async_ops.to_can_async_p = remote_can_async_p;
7473 remote_async_ops.to_is_async_p = remote_is_async_p;
7474 remote_async_ops.to_async = remote_async;
7475 remote_async_ops.to_async_mask = remote_async_mask;
7476 remote_async_ops.to_magic = OPS_MAGIC;
7477 remote_async_ops.to_memory_map = remote_memory_map;
7478 remote_async_ops.to_flash_erase = remote_flash_erase;
7479 remote_async_ops.to_flash_done = remote_flash_done;
7480 remote_async_ops.to_read_description = remote_read_description;
7481 remote_async_ops.to_search_memory = remote_search_memory;
7484 /* Set up the async extended remote vector by making a copy of the standard
7485 remote vector and adding to it. */
7488 init_extended_async_remote_ops (void)
7490 extended_async_remote_ops = remote_async_ops;
7492 extended_async_remote_ops.to_shortname = "extended-async";
7493 extended_async_remote_ops.to_longname =
7494 "Extended remote serial target in async gdb-specific protocol";
7495 extended_async_remote_ops.to_doc =
7496 "Use a remote computer via a serial line, using an async gdb-specific protocol.\n\
7497 Specify the serial device it is connected to (e.g. /dev/ttya).",
7498 extended_async_remote_ops.to_open = extended_remote_async_open;
7499 extended_async_remote_ops.to_create_inferior = extended_remote_async_create_inferior;
7500 extended_async_remote_ops.to_mourn_inferior = extended_async_remote_mourn;
7501 extended_async_remote_ops.to_detach = extended_remote_detach;
7502 extended_async_remote_ops.to_attach = extended_async_remote_attach;
7506 set_remote_cmd (char *args, int from_tty)
7508 help_list (remote_set_cmdlist, "set remote ", -1, gdb_stdout);
7512 show_remote_cmd (char *args, int from_tty)
7514 /* We can't just use cmd_show_list here, because we want to skip
7515 the redundant "show remote Z-packet" and the legacy aliases. */
7516 struct cleanup *showlist_chain;
7517 struct cmd_list_element *list = remote_show_cmdlist;
7519 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
7520 for (; list != NULL; list = list->next)
7521 if (strcmp (list->name, "Z-packet") == 0)
7523 else if (list->type == not_set_cmd)
7524 /* Alias commands are exactly like the original, except they
7525 don't have the normal type. */
7529 struct cleanup *option_chain
7530 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
7531 ui_out_field_string (uiout, "name", list->name);
7532 ui_out_text (uiout, ": ");
7533 if (list->type == show_cmd)
7534 do_setshow_command ((char *) NULL, from_tty, list);
7536 cmd_func (list, NULL, from_tty);
7537 /* Close the tuple. */
7538 do_cleanups (option_chain);
7541 /* Close the tuple. */
7542 do_cleanups (showlist_chain);
7546 /* Function to be called whenever a new objfile (shlib) is detected. */
7548 remote_new_objfile (struct objfile *objfile)
7550 if (remote_desc != 0) /* Have a remote connection. */
7551 remote_check_symbols (objfile);
7555 _initialize_remote (void)
7557 struct remote_state *rs;
7559 /* architecture specific data */
7560 remote_gdbarch_data_handle =
7561 gdbarch_data_register_post_init (init_remote_state);
7562 remote_g_packet_data_handle =
7563 gdbarch_data_register_pre_init (remote_g_packet_data_init);
7565 /* Initialize the per-target state. At the moment there is only one
7566 of these, not one per target. Only one target is active at a
7567 time. The default buffer size is unimportant; it will be expanded
7568 whenever a larger buffer is needed. */
7569 rs = get_remote_state_raw ();
7571 rs->buf = xmalloc (rs->buf_size);
7574 add_target (&remote_ops);
7576 init_extended_remote_ops ();
7577 add_target (&extended_remote_ops);
7579 init_remote_async_ops ();
7580 add_target (&remote_async_ops);
7582 init_extended_async_remote_ops ();
7583 add_target (&extended_async_remote_ops);
7585 /* Hook into new objfile notification. */
7586 observer_attach_new_objfile (remote_new_objfile);
7588 /* Set up signal handlers. */
7589 sigint_remote_token =
7590 create_async_signal_handler (async_remote_interrupt, NULL);
7591 sigint_remote_twice_token =
7592 create_async_signal_handler (inferior_event_handler_wrapper, NULL);
7595 init_remote_threadtests ();
7598 /* set/show remote ... */
7600 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
7601 Remote protocol specific variables\n\
7602 Configure various remote-protocol specific variables such as\n\
7603 the packets being used"),
7604 &remote_set_cmdlist, "set remote ",
7605 0 /* allow-unknown */, &setlist);
7606 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
7607 Remote protocol specific variables\n\
7608 Configure various remote-protocol specific variables such as\n\
7609 the packets being used"),
7610 &remote_show_cmdlist, "show remote ",
7611 0 /* allow-unknown */, &showlist);
7613 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
7614 Compare section data on target to the exec file.\n\
7615 Argument is a single section name (default: all loaded sections)."),
7618 add_cmd ("packet", class_maintenance, packet_command, _("\
7619 Send an arbitrary packet to a remote target.\n\
7620 maintenance packet TEXT\n\
7621 If GDB is talking to an inferior via the GDB serial protocol, then\n\
7622 this command sends the string TEXT to the inferior, and displays the\n\
7623 response packet. GDB supplies the initial `$' character, and the\n\
7624 terminating `#' character and checksum."),
7627 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
7628 Set whether to send break if interrupted."), _("\
7629 Show whether to send break if interrupted."), _("\
7630 If set, a break, instead of a cntrl-c, is sent to the remote target."),
7631 NULL, NULL, /* FIXME: i18n: Whether to send break if interrupted is %s. */
7632 &setlist, &showlist);
7634 /* Install commands for configuring memory read/write packets. */
7636 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
7637 Set the maximum number of bytes per memory write packet (deprecated)."),
7639 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
7640 Show the maximum number of bytes per memory write packet (deprecated)."),
7642 add_cmd ("memory-write-packet-size", no_class,
7643 set_memory_write_packet_size, _("\
7644 Set the maximum number of bytes per memory-write packet.\n\
7645 Specify the number of bytes in a packet or 0 (zero) for the\n\
7646 default packet size. The actual limit is further reduced\n\
7647 dependent on the target. Specify ``fixed'' to disable the\n\
7648 further restriction and ``limit'' to enable that restriction."),
7649 &remote_set_cmdlist);
7650 add_cmd ("memory-read-packet-size", no_class,
7651 set_memory_read_packet_size, _("\
7652 Set the maximum number of bytes per memory-read packet.\n\
7653 Specify the number of bytes in a packet or 0 (zero) for the\n\
7654 default packet size. The actual limit is further reduced\n\
7655 dependent on the target. Specify ``fixed'' to disable the\n\
7656 further restriction and ``limit'' to enable that restriction."),
7657 &remote_set_cmdlist);
7658 add_cmd ("memory-write-packet-size", no_class,
7659 show_memory_write_packet_size,
7660 _("Show the maximum number of bytes per memory-write packet."),
7661 &remote_show_cmdlist);
7662 add_cmd ("memory-read-packet-size", no_class,
7663 show_memory_read_packet_size,
7664 _("Show the maximum number of bytes per memory-read packet."),
7665 &remote_show_cmdlist);
7667 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
7668 &remote_hw_watchpoint_limit, _("\
7669 Set the maximum number of target hardware watchpoints."), _("\
7670 Show the maximum number of target hardware watchpoints."), _("\
7671 Specify a negative limit for unlimited."),
7672 NULL, NULL, /* FIXME: i18n: The maximum number of target hardware watchpoints is %s. */
7673 &remote_set_cmdlist, &remote_show_cmdlist);
7674 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
7675 &remote_hw_breakpoint_limit, _("\
7676 Set the maximum number of target hardware breakpoints."), _("\
7677 Show the maximum number of target hardware breakpoints."), _("\
7678 Specify a negative limit for unlimited."),
7679 NULL, NULL, /* FIXME: i18n: The maximum number of target hardware breakpoints is %s. */
7680 &remote_set_cmdlist, &remote_show_cmdlist);
7682 add_setshow_integer_cmd ("remoteaddresssize", class_obscure,
7683 &remote_address_size, _("\
7684 Set the maximum size of the address (in bits) in a memory packet."), _("\
7685 Show the maximum size of the address (in bits) in a memory packet."), NULL,
7687 NULL, /* FIXME: i18n: */
7688 &setlist, &showlist);
7690 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
7691 "X", "binary-download", 1);
7693 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
7694 "vCont", "verbose-resume", 0);
7696 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
7697 "QPassSignals", "pass-signals", 0);
7699 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
7700 "qSymbol", "symbol-lookup", 0);
7702 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
7703 "P", "set-register", 1);
7705 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
7706 "p", "fetch-register", 1);
7708 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
7709 "Z0", "software-breakpoint", 0);
7711 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
7712 "Z1", "hardware-breakpoint", 0);
7714 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
7715 "Z2", "write-watchpoint", 0);
7717 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
7718 "Z3", "read-watchpoint", 0);
7720 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
7721 "Z4", "access-watchpoint", 0);
7723 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
7724 "qXfer:auxv:read", "read-aux-vector", 0);
7726 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
7727 "qXfer:features:read", "target-features", 0);
7729 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
7730 "qXfer:libraries:read", "library-info", 0);
7732 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
7733 "qXfer:memory-map:read", "memory-map", 0);
7735 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
7736 "qXfer:spu:read", "read-spu-object", 0);
7738 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
7739 "qXfer:spu:write", "write-spu-object", 0);
7741 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
7742 "qGetTLSAddr", "get-thread-local-storage-address",
7745 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
7746 "qSupported", "supported-packets", 0);
7748 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
7749 "qSearch:memory", "search-memory", 0);
7751 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
7752 "vFile:open", "hostio-open", 0);
7754 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
7755 "vFile:pread", "hostio-pread", 0);
7757 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
7758 "vFile:pwrite", "hostio-pwrite", 0);
7760 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
7761 "vFile:close", "hostio-close", 0);
7763 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
7764 "vFile:unlink", "hostio-unlink", 0);
7766 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
7767 "vAttach", "attach", 0);
7769 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
7772 /* Keep the old ``set remote Z-packet ...'' working. Each individual
7773 Z sub-packet has its own set and show commands, but users may
7774 have sets to this variable in their .gdbinit files (or in their
7776 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
7777 &remote_Z_packet_detect, _("\
7778 Set use of remote protocol `Z' packets"), _("\
7779 Show use of remote protocol `Z' packets "), _("\
7780 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
7782 set_remote_protocol_Z_packet_cmd,
7783 show_remote_protocol_Z_packet_cmd, /* FIXME: i18n: Use of remote protocol `Z' packets is %s. */
7784 &remote_set_cmdlist, &remote_show_cmdlist);
7786 add_prefix_cmd ("remote", class_files, remote_command, _("\
7787 Manipulate files on the remote system\n\
7788 Transfer files to and from the remote target system."),
7789 &remote_cmdlist, "remote ",
7790 0 /* allow-unknown */, &cmdlist);
7792 add_cmd ("put", class_files, remote_put_command,
7793 _("Copy a local file to the remote system."),
7796 add_cmd ("get", class_files, remote_get_command,
7797 _("Copy a remote file to the local system."),
7800 add_cmd ("delete", class_files, remote_delete_command,
7801 _("Delete a remote file."),
7804 remote_exec_file = xstrdup ("");
7805 add_setshow_string_noescape_cmd ("exec-file", class_files,
7806 &remote_exec_file, _("\
7807 Set the remote pathname for \"run\""), _("\
7808 Show the remote pathname for \"run\""), NULL, NULL, NULL,
7809 &remote_set_cmdlist, &remote_show_cmdlist);
7811 /* Eventually initialize fileio. See fileio.c */
7812 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);