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_open (char *name, int from_tty);
97 static void extended_remote_open (char *name, int from_tty);
99 static void remote_open_1 (char *, int, struct target_ops *, int extended_p);
101 static void remote_close (int quitting);
103 static void remote_store_registers (struct regcache *regcache, int regno);
105 static void remote_mourn (void);
107 static void extended_remote_restart (void);
109 static void extended_remote_mourn (void);
111 static void remote_mourn_1 (struct target_ops *);
113 static void remote_send (char **buf, long *sizeof_buf_p);
115 static int readchar (int timeout);
117 static ptid_t remote_wait (ptid_t ptid,
118 struct target_waitstatus *status);
120 static void remote_kill (void);
122 static int tohex (int nib);
124 static int remote_can_async_p (void);
126 static int remote_is_async_p (void);
128 static void remote_async (void (*callback) (enum inferior_event_type event_type,
129 void *context), void *context);
131 static int remote_async_mask (int new_mask);
133 static void remote_detach (char *args, int from_tty);
135 static void remote_interrupt (int signo);
137 static void remote_interrupt_twice (int signo);
139 static void interrupt_query (void);
141 static void set_general_thread (struct ptid ptid);
142 static void set_continue_thread (struct ptid ptid);
144 static int remote_thread_alive (ptid_t);
146 static void get_offsets (void);
148 static void skip_frame (void);
150 static long read_frame (char **buf_p, long *sizeof_buf);
152 static int hexnumlen (ULONGEST num);
154 static void init_remote_ops (void);
156 static void init_extended_remote_ops (void);
158 static void remote_stop (ptid_t);
160 static int ishex (int ch, int *val);
162 static int stubhex (int ch);
164 static int hexnumstr (char *, ULONGEST);
166 static int hexnumnstr (char *, ULONGEST, int);
168 static CORE_ADDR remote_address_masked (CORE_ADDR);
170 static void print_packet (char *);
172 static unsigned long crc32 (unsigned char *, int, unsigned int);
174 static void compare_sections_command (char *, int);
176 static void packet_command (char *, int);
178 static int stub_unpack_int (char *buff, int fieldlength);
180 static ptid_t remote_current_thread (ptid_t oldptid);
182 static void remote_find_new_threads (void);
184 static void record_currthread (ptid_t currthread);
186 static int fromhex (int a);
188 static int hex2bin (const char *hex, gdb_byte *bin, int count);
190 static int bin2hex (const gdb_byte *bin, char *hex, int count);
192 static int putpkt_binary (char *buf, int cnt);
194 static void check_binary_download (CORE_ADDR addr);
196 struct packet_config;
198 static void show_packet_config_cmd (struct packet_config *config);
200 static void update_packet_config (struct packet_config *config);
202 static void set_remote_protocol_packet_cmd (char *args, int from_tty,
203 struct cmd_list_element *c);
205 static void show_remote_protocol_packet_cmd (struct ui_file *file,
207 struct cmd_list_element *c,
210 void _initialize_remote (void);
212 /* Controls if async mode is permitted. */
213 static int remote_async_permitted = 0;
215 static int remote_async_permitted_set = 0;
218 set_maintenance_remote_async_permitted (char *args, int from_tty,
219 struct cmd_list_element *c)
221 if (target_has_execution)
223 remote_async_permitted_set = remote_async_permitted; /* revert */
224 error (_("Cannot change this setting while the inferior is running."));
227 remote_async_permitted = remote_async_permitted_set;
231 show_maintenance_remote_async_permitted (struct ui_file *file, int from_tty,
232 struct cmd_list_element *c, const char *value)
234 fprintf_filtered (file, _("\
235 Controlling the remote inferior in asynchronous mode is %s.\n"),
241 static struct cmd_list_element *remote_cmdlist;
243 /* For "set remote" and "show remote". */
245 static struct cmd_list_element *remote_set_cmdlist;
246 static struct cmd_list_element *remote_show_cmdlist;
248 /* Description of the remote protocol state for the currently
249 connected target. This is per-target state, and independent of the
250 selected architecture. */
254 /* A buffer to use for incoming packets, and its current size. The
255 buffer is grown dynamically for larger incoming packets.
256 Outgoing packets may also be constructed in this buffer.
257 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
258 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
263 /* If we negotiated packet size explicitly (and thus can bypass
264 heuristics for the largest packet size that will not overflow
265 a buffer in the stub), this will be set to that packet size.
266 Otherwise zero, meaning to use the guessed size. */
267 long explicit_packet_size;
269 /* remote_wait is normally called when the target is running and
270 waits for a stop reply packet. But sometimes we need to call it
271 when the target is already stopped. We can send a "?" packet
272 and have remote_wait read the response. Or, if we already have
273 the response, we can stash it in BUF and tell remote_wait to
274 skip calling getpkt. This flag is set when BUF contains a
275 stop reply packet and the target is not waiting. */
276 int cached_wait_status;
278 /* True, if in no ack mode. That is, neither GDB nor the stub will
279 expect acks from each other. The connection is assumed to be
284 /* This data could be associated with a target, but we do not always
285 have access to the current target when we need it, so for now it is
286 static. This will be fine for as long as only one target is in use
288 static struct remote_state remote_state;
290 static struct remote_state *
291 get_remote_state_raw (void)
293 return &remote_state;
296 /* Description of the remote protocol for a given architecture. */
300 long offset; /* Offset into G packet. */
301 long regnum; /* GDB's internal register number. */
302 LONGEST pnum; /* Remote protocol register number. */
303 int in_g_packet; /* Always part of G packet. */
304 /* long size in bytes; == register_size (current_gdbarch, regnum);
306 /* char *name; == gdbarch_register_name (current_gdbarch, regnum);
310 struct remote_arch_state
312 /* Description of the remote protocol registers. */
313 long sizeof_g_packet;
315 /* Description of the remote protocol registers indexed by REGNUM
316 (making an array gdbarch_num_regs in size). */
317 struct packet_reg *regs;
319 /* This is the size (in chars) of the first response to the ``g''
320 packet. It is used as a heuristic when determining the maximum
321 size of memory-read and memory-write packets. A target will
322 typically only reserve a buffer large enough to hold the ``g''
323 packet. The size does not include packet overhead (headers and
325 long actual_register_packet_size;
327 /* This is the maximum size (in chars) of a non read/write packet.
328 It is also used as a cap on the size of read/write packets. */
329 long remote_packet_size;
333 /* Handle for retreving the remote protocol data from gdbarch. */
334 static struct gdbarch_data *remote_gdbarch_data_handle;
336 static struct remote_arch_state *
337 get_remote_arch_state (void)
339 return gdbarch_data (current_gdbarch, remote_gdbarch_data_handle);
342 /* Fetch the global remote target state. */
344 static struct remote_state *
345 get_remote_state (void)
347 /* Make sure that the remote architecture state has been
348 initialized, because doing so might reallocate rs->buf. Any
349 function which calls getpkt also needs to be mindful of changes
350 to rs->buf, but this call limits the number of places which run
352 get_remote_arch_state ();
354 return get_remote_state_raw ();
358 compare_pnums (const void *lhs_, const void *rhs_)
360 const struct packet_reg * const *lhs = lhs_;
361 const struct packet_reg * const *rhs = rhs_;
363 if ((*lhs)->pnum < (*rhs)->pnum)
365 else if ((*lhs)->pnum == (*rhs)->pnum)
372 init_remote_state (struct gdbarch *gdbarch)
374 int regnum, num_remote_regs, offset;
375 struct remote_state *rs = get_remote_state_raw ();
376 struct remote_arch_state *rsa;
377 struct packet_reg **remote_regs;
379 rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
381 /* Use the architecture to build a regnum<->pnum table, which will be
382 1:1 unless a feature set specifies otherwise. */
383 rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
384 gdbarch_num_regs (gdbarch),
386 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
388 struct packet_reg *r = &rsa->regs[regnum];
390 if (register_size (gdbarch, regnum) == 0)
391 /* Do not try to fetch zero-sized (placeholder) registers. */
394 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
399 /* Define the g/G packet format as the contents of each register
400 with a remote protocol number, in order of ascending protocol
403 remote_regs = alloca (gdbarch_num_regs (gdbarch)
404 * sizeof (struct packet_reg *));
405 for (num_remote_regs = 0, regnum = 0;
406 regnum < gdbarch_num_regs (gdbarch);
408 if (rsa->regs[regnum].pnum != -1)
409 remote_regs[num_remote_regs++] = &rsa->regs[regnum];
411 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
414 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
416 remote_regs[regnum]->in_g_packet = 1;
417 remote_regs[regnum]->offset = offset;
418 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
421 /* Record the maximum possible size of the g packet - it may turn out
423 rsa->sizeof_g_packet = offset;
425 /* Default maximum number of characters in a packet body. Many
426 remote stubs have a hardwired buffer size of 400 bytes
427 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
428 as the maximum packet-size to ensure that the packet and an extra
429 NUL character can always fit in the buffer. This stops GDB
430 trashing stubs that try to squeeze an extra NUL into what is
431 already a full buffer (As of 1999-12-04 that was most stubs). */
432 rsa->remote_packet_size = 400 - 1;
434 /* This one is filled in when a ``g'' packet is received. */
435 rsa->actual_register_packet_size = 0;
437 /* Should rsa->sizeof_g_packet needs more space than the
438 default, adjust the size accordingly. Remember that each byte is
439 encoded as two characters. 32 is the overhead for the packet
440 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
441 (``$NN:G...#NN'') is a better guess, the below has been padded a
443 if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
444 rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
446 /* Make sure that the packet buffer is plenty big enough for
447 this architecture. */
448 if (rs->buf_size < rsa->remote_packet_size)
450 rs->buf_size = 2 * rsa->remote_packet_size;
451 rs->buf = xrealloc (rs->buf, rs->buf_size);
457 /* Return the current allowed size of a remote packet. This is
458 inferred from the current architecture, and should be used to
459 limit the length of outgoing packets. */
461 get_remote_packet_size (void)
463 struct remote_state *rs = get_remote_state ();
464 struct remote_arch_state *rsa = get_remote_arch_state ();
466 if (rs->explicit_packet_size)
467 return rs->explicit_packet_size;
469 return rsa->remote_packet_size;
472 static struct packet_reg *
473 packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
475 if (regnum < 0 && regnum >= gdbarch_num_regs (current_gdbarch))
479 struct packet_reg *r = &rsa->regs[regnum];
480 gdb_assert (r->regnum == regnum);
485 static struct packet_reg *
486 packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
489 for (i = 0; i < gdbarch_num_regs (current_gdbarch); i++)
491 struct packet_reg *r = &rsa->regs[i];
498 /* FIXME: graces/2002-08-08: These variables should eventually be
499 bound to an instance of the target object (as in gdbarch-tdep()),
500 when such a thing exists. */
502 /* This is set to the data address of the access causing the target
503 to stop for a watchpoint. */
504 static CORE_ADDR remote_watch_data_address;
506 /* This is non-zero if target stopped for a watchpoint. */
507 static int remote_stopped_by_watchpoint_p;
509 static struct target_ops remote_ops;
511 static struct target_ops extended_remote_ops;
513 static int remote_async_mask_value = 1;
515 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
516 ``forever'' still use the normal timeout mechanism. This is
517 currently used by the ASYNC code to guarentee that target reads
518 during the initial connect always time-out. Once getpkt has been
519 modified to return a timeout indication and, in turn
520 remote_wait()/wait_for_inferior() have gained a timeout parameter
522 static int wait_forever_enabled_p = 1;
525 /* This variable chooses whether to send a ^C or a break when the user
526 requests program interruption. Although ^C is usually what remote
527 systems expect, and that is the default here, sometimes a break is
528 preferable instead. */
530 static int remote_break;
532 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
533 remote_open knows that we don't have a file open when the program
535 static struct serial *remote_desc = NULL;
537 /* This variable sets the number of bits in an address that are to be
538 sent in a memory ("M" or "m") packet. Normally, after stripping
539 leading zeros, the entire address would be sent. This variable
540 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
541 initial implementation of remote.c restricted the address sent in
542 memory packets to ``host::sizeof long'' bytes - (typically 32
543 bits). Consequently, for 64 bit targets, the upper 32 bits of an
544 address was never sent. Since fixing this bug may cause a break in
545 some remote targets this variable is principly provided to
546 facilitate backward compatibility. */
548 static int remote_address_size;
550 /* Temporary to track who currently owns the terminal. See
551 remote_terminal_* for more details. */
553 static int remote_async_terminal_ours_p;
555 /* The executable file to use for "run" on the remote side. */
557 static char *remote_exec_file = "";
560 /* User configurable variables for the number of characters in a
561 memory read/write packet. MIN (rsa->remote_packet_size,
562 rsa->sizeof_g_packet) is the default. Some targets need smaller
563 values (fifo overruns, et.al.) and some users need larger values
564 (speed up transfers). The variables ``preferred_*'' (the user
565 request), ``current_*'' (what was actually set) and ``forced_*''
566 (Positive - a soft limit, negative - a hard limit). */
568 struct memory_packet_config
575 /* Compute the current size of a read/write packet. Since this makes
576 use of ``actual_register_packet_size'' the computation is dynamic. */
579 get_memory_packet_size (struct memory_packet_config *config)
581 struct remote_state *rs = get_remote_state ();
582 struct remote_arch_state *rsa = get_remote_arch_state ();
584 /* NOTE: The somewhat arbitrary 16k comes from the knowledge (folk
585 law?) that some hosts don't cope very well with large alloca()
586 calls. Eventually the alloca() code will be replaced by calls to
587 xmalloc() and make_cleanups() allowing this restriction to either
588 be lifted or removed. */
589 #ifndef MAX_REMOTE_PACKET_SIZE
590 #define MAX_REMOTE_PACKET_SIZE 16384
592 /* NOTE: 20 ensures we can write at least one byte. */
593 #ifndef MIN_REMOTE_PACKET_SIZE
594 #define MIN_REMOTE_PACKET_SIZE 20
599 if (config->size <= 0)
600 what_they_get = MAX_REMOTE_PACKET_SIZE;
602 what_they_get = config->size;
606 what_they_get = get_remote_packet_size ();
607 /* Limit the packet to the size specified by the user. */
609 && what_they_get > config->size)
610 what_they_get = config->size;
612 /* Limit it to the size of the targets ``g'' response unless we have
613 permission from the stub to use a larger packet size. */
614 if (rs->explicit_packet_size == 0
615 && rsa->actual_register_packet_size > 0
616 && what_they_get > rsa->actual_register_packet_size)
617 what_they_get = rsa->actual_register_packet_size;
619 if (what_they_get > MAX_REMOTE_PACKET_SIZE)
620 what_they_get = MAX_REMOTE_PACKET_SIZE;
621 if (what_they_get < MIN_REMOTE_PACKET_SIZE)
622 what_they_get = MIN_REMOTE_PACKET_SIZE;
624 /* Make sure there is room in the global buffer for this packet
625 (including its trailing NUL byte). */
626 if (rs->buf_size < what_they_get + 1)
628 rs->buf_size = 2 * what_they_get;
629 rs->buf = xrealloc (rs->buf, 2 * what_they_get);
632 return what_they_get;
635 /* Update the size of a read/write packet. If they user wants
636 something really big then do a sanity check. */
639 set_memory_packet_size (char *args, struct memory_packet_config *config)
641 int fixed_p = config->fixed_p;
642 long size = config->size;
644 error (_("Argument required (integer, `fixed' or `limited')."));
645 else if (strcmp (args, "hard") == 0
646 || strcmp (args, "fixed") == 0)
648 else if (strcmp (args, "soft") == 0
649 || strcmp (args, "limit") == 0)
654 size = strtoul (args, &end, 0);
656 error (_("Invalid %s (bad syntax)."), config->name);
658 /* Instead of explicitly capping the size of a packet to
659 MAX_REMOTE_PACKET_SIZE or dissallowing it, the user is
660 instead allowed to set the size to something arbitrarily
662 if (size > MAX_REMOTE_PACKET_SIZE)
663 error (_("Invalid %s (too large)."), config->name);
667 if (fixed_p && !config->fixed_p)
669 if (! query (_("The target may not be able to correctly handle a %s\n"
670 "of %ld bytes. Change the packet size? "),
672 error (_("Packet size not changed."));
674 /* Update the config. */
675 config->fixed_p = fixed_p;
680 show_memory_packet_size (struct memory_packet_config *config)
682 printf_filtered (_("The %s is %ld. "), config->name, config->size);
684 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
685 get_memory_packet_size (config));
687 printf_filtered (_("Packets are limited to %ld bytes.\n"),
688 get_memory_packet_size (config));
691 static struct memory_packet_config memory_write_packet_config =
693 "memory-write-packet-size",
697 set_memory_write_packet_size (char *args, int from_tty)
699 set_memory_packet_size (args, &memory_write_packet_config);
703 show_memory_write_packet_size (char *args, int from_tty)
705 show_memory_packet_size (&memory_write_packet_config);
709 get_memory_write_packet_size (void)
711 return get_memory_packet_size (&memory_write_packet_config);
714 static struct memory_packet_config memory_read_packet_config =
716 "memory-read-packet-size",
720 set_memory_read_packet_size (char *args, int from_tty)
722 set_memory_packet_size (args, &memory_read_packet_config);
726 show_memory_read_packet_size (char *args, int from_tty)
728 show_memory_packet_size (&memory_read_packet_config);
732 get_memory_read_packet_size (void)
734 long size = get_memory_packet_size (&memory_read_packet_config);
735 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
736 extra buffer size argument before the memory read size can be
737 increased beyond this. */
738 if (size > get_remote_packet_size ())
739 size = get_remote_packet_size ();
744 /* Generic configuration support for packets the stub optionally
745 supports. Allows the user to specify the use of the packet as well
746 as allowing GDB to auto-detect support in the remote stub. */
750 PACKET_SUPPORT_UNKNOWN = 0,
759 enum auto_boolean detect;
760 enum packet_support support;
763 /* Analyze a packet's return value and update the packet config
774 update_packet_config (struct packet_config *config)
776 switch (config->detect)
778 case AUTO_BOOLEAN_TRUE:
779 config->support = PACKET_ENABLE;
781 case AUTO_BOOLEAN_FALSE:
782 config->support = PACKET_DISABLE;
784 case AUTO_BOOLEAN_AUTO:
785 config->support = PACKET_SUPPORT_UNKNOWN;
791 show_packet_config_cmd (struct packet_config *config)
793 char *support = "internal-error";
794 switch (config->support)
800 support = "disabled";
802 case PACKET_SUPPORT_UNKNOWN:
806 switch (config->detect)
808 case AUTO_BOOLEAN_AUTO:
809 printf_filtered (_("Support for the `%s' packet is auto-detected, currently %s.\n"),
810 config->name, support);
812 case AUTO_BOOLEAN_TRUE:
813 case AUTO_BOOLEAN_FALSE:
814 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
815 config->name, support);
821 add_packet_config_cmd (struct packet_config *config, const char *name,
822 const char *title, int legacy)
829 config->title = title;
830 config->detect = AUTO_BOOLEAN_AUTO;
831 config->support = PACKET_SUPPORT_UNKNOWN;
832 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
834 show_doc = xstrprintf ("Show current use of remote protocol `%s' (%s) packet",
836 /* set/show TITLE-packet {auto,on,off} */
837 cmd_name = xstrprintf ("%s-packet", title);
838 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
839 &config->detect, set_doc, show_doc, NULL, /* help_doc */
840 set_remote_protocol_packet_cmd,
841 show_remote_protocol_packet_cmd,
842 &remote_set_cmdlist, &remote_show_cmdlist);
843 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
847 legacy_name = xstrprintf ("%s-packet", name);
848 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
849 &remote_set_cmdlist);
850 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
851 &remote_show_cmdlist);
855 static enum packet_result
856 packet_check_result (const char *buf)
860 /* The stub recognized the packet request. Check that the
861 operation succeeded. */
863 && isxdigit (buf[1]) && isxdigit (buf[2])
865 /* "Enn" - definitly an error. */
868 /* Always treat "E." as an error. This will be used for
869 more verbose error messages, such as E.memtypes. */
870 if (buf[0] == 'E' && buf[1] == '.')
873 /* The packet may or may not be OK. Just assume it is. */
877 /* The stub does not support the packet. */
878 return PACKET_UNKNOWN;
881 static enum packet_result
882 packet_ok (const char *buf, struct packet_config *config)
884 enum packet_result result;
886 result = packet_check_result (buf);
891 /* The stub recognized the packet request. */
892 switch (config->support)
894 case PACKET_SUPPORT_UNKNOWN:
896 fprintf_unfiltered (gdb_stdlog,
897 "Packet %s (%s) is supported\n",
898 config->name, config->title);
899 config->support = PACKET_ENABLE;
902 internal_error (__FILE__, __LINE__,
903 _("packet_ok: attempt to use a disabled packet"));
910 /* The stub does not support the packet. */
911 switch (config->support)
914 if (config->detect == AUTO_BOOLEAN_AUTO)
915 /* If the stub previously indicated that the packet was
916 supported then there is a protocol error.. */
917 error (_("Protocol error: %s (%s) conflicting enabled responses."),
918 config->name, config->title);
920 /* The user set it wrong. */
921 error (_("Enabled packet %s (%s) not recognized by stub"),
922 config->name, config->title);
924 case PACKET_SUPPORT_UNKNOWN:
926 fprintf_unfiltered (gdb_stdlog,
927 "Packet %s (%s) is NOT supported\n",
928 config->name, config->title);
929 config->support = PACKET_DISABLE;
957 PACKET_qXfer_features,
958 PACKET_qXfer_libraries,
959 PACKET_qXfer_memory_map,
960 PACKET_qXfer_spu_read,
961 PACKET_qXfer_spu_write,
965 PACKET_qSearch_memory,
968 PACKET_QStartNoAckMode,
972 static struct packet_config remote_protocol_packets[PACKET_MAX];
975 set_remote_protocol_packet_cmd (char *args, int from_tty,
976 struct cmd_list_element *c)
978 struct packet_config *packet;
980 for (packet = remote_protocol_packets;
981 packet < &remote_protocol_packets[PACKET_MAX];
984 if (&packet->detect == c->var)
986 update_packet_config (packet);
990 internal_error (__FILE__, __LINE__, "Could not find config for %s",
995 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
996 struct cmd_list_element *c,
999 struct packet_config *packet;
1001 for (packet = remote_protocol_packets;
1002 packet < &remote_protocol_packets[PACKET_MAX];
1005 if (&packet->detect == c->var)
1007 show_packet_config_cmd (packet);
1011 internal_error (__FILE__, __LINE__, "Could not find config for %s",
1015 /* Should we try one of the 'Z' requests? */
1019 Z_PACKET_SOFTWARE_BP,
1020 Z_PACKET_HARDWARE_BP,
1027 /* For compatibility with older distributions. Provide a ``set remote
1028 Z-packet ...'' command that updates all the Z packet types. */
1030 static enum auto_boolean remote_Z_packet_detect;
1033 set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1034 struct cmd_list_element *c)
1037 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1039 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
1040 update_packet_config (&remote_protocol_packets[PACKET_Z0 + i]);
1045 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1046 struct cmd_list_element *c,
1050 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1052 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
1056 /* Should we try the 'ThreadInfo' query packet?
1058 This variable (NOT available to the user: auto-detect only!)
1059 determines whether GDB will use the new, simpler "ThreadInfo"
1060 query or the older, more complex syntax for thread queries.
1061 This is an auto-detect variable (set to true at each connect,
1062 and set to false when the target fails to recognize it). */
1064 static int use_threadinfo_query;
1065 static int use_threadextra_query;
1067 /* Tokens for use by the asynchronous signal handlers for SIGINT. */
1068 static struct async_signal_handler *sigint_remote_twice_token;
1069 static struct async_signal_handler *sigint_remote_token;
1073 static ptid_t magic_null_ptid;
1074 static ptid_t not_sent_ptid;
1075 static ptid_t any_thread_ptid;
1077 /* These are the threads which we last sent to the remote system. The
1078 TID member will be -1 for all or -2 for not sent yet. */
1080 static ptid_t general_thread;
1081 static ptid_t continue_thread;
1084 /* Call this function as a result of
1085 1) A halt indication (T packet) containing a thread id
1086 2) A direct query of currthread
1087 3) Successful execution of set thread
1091 record_currthread (ptid_t currthread)
1093 general_thread = currthread;
1095 /* If this is a new thread, add it to GDB's thread list.
1096 If we leave it up to WFI to do this, bad things will happen. */
1097 if (!in_thread_list (currthread))
1099 if (ptid_equal (pid_to_ptid (ptid_get_pid (currthread)), inferior_ptid))
1101 /* inferior_ptid has no thread member yet. This can happen
1102 with the vAttach -> remote_wait,"TAAthread:" path if the
1103 stub doesn't support qC. This is the first stop reported
1104 after an attach, so this is the main thread. Update the
1105 ptid in the thread list. */
1106 struct thread_info *th = find_thread_pid (inferior_ptid);
1107 inferior_ptid = th->ptid = currthread;
1109 else if (ptid_equal (magic_null_ptid, inferior_ptid))
1111 /* inferior_ptid is not set yet. This can happen with the
1112 vRun -> remote_wait,"TAAthread:" path if the stub
1113 doesn't support qC. This is the first stop reported
1114 after an attach, so this is the main thread. Update the
1115 ptid in the thread list. */
1116 struct thread_info *th = find_thread_pid (inferior_ptid);
1117 inferior_ptid = th->ptid = currthread;
1120 /* This is really a new thread. Add it. */
1121 add_thread (currthread);
1125 static char *last_pass_packet;
1127 /* If 'QPassSignals' is supported, tell the remote stub what signals
1128 it can simply pass through to the inferior without reporting. */
1131 remote_pass_signals (void)
1133 if (remote_protocol_packets[PACKET_QPassSignals].support != PACKET_DISABLE)
1135 char *pass_packet, *p;
1136 int numsigs = (int) TARGET_SIGNAL_LAST;
1139 gdb_assert (numsigs < 256);
1140 for (i = 0; i < numsigs; i++)
1142 if (signal_stop_state (i) == 0
1143 && signal_print_state (i) == 0
1144 && signal_pass_state (i) == 1)
1147 pass_packet = xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
1148 strcpy (pass_packet, "QPassSignals:");
1149 p = pass_packet + strlen (pass_packet);
1150 for (i = 0; i < numsigs; i++)
1152 if (signal_stop_state (i) == 0
1153 && signal_print_state (i) == 0
1154 && signal_pass_state (i) == 1)
1157 *p++ = tohex (i >> 4);
1158 *p++ = tohex (i & 15);
1167 if (!last_pass_packet || strcmp (last_pass_packet, pass_packet))
1169 struct remote_state *rs = get_remote_state ();
1170 char *buf = rs->buf;
1172 putpkt (pass_packet);
1173 getpkt (&rs->buf, &rs->buf_size, 0);
1174 packet_ok (buf, &remote_protocol_packets[PACKET_QPassSignals]);
1175 if (last_pass_packet)
1176 xfree (last_pass_packet);
1177 last_pass_packet = pass_packet;
1180 xfree (pass_packet);
1184 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
1185 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
1186 thread. If GEN is set, set the general thread, if not, then set
1187 the step/continue thread. */
1189 set_thread (struct ptid ptid, int gen)
1191 struct remote_state *rs = get_remote_state ();
1192 ptid_t state = gen ? general_thread : continue_thread;
1193 char *buf = rs->buf;
1194 char *endbuf = rs->buf + get_remote_packet_size ();
1196 if (ptid_equal (state, ptid))
1200 *buf++ = gen ? 'g' : 'c';
1201 if (ptid_equal (ptid, magic_null_ptid))
1202 xsnprintf (buf, endbuf - buf, "0");
1203 else if (ptid_equal (ptid, any_thread_ptid))
1204 xsnprintf (buf, endbuf - buf, "0");
1205 else if (ptid_equal (ptid, minus_one_ptid))
1206 xsnprintf (buf, endbuf - buf, "-1");
1209 int tid = ptid_get_tid (ptid);
1211 xsnprintf (buf, endbuf - buf, "-%x", -tid);
1213 xsnprintf (buf, endbuf - buf, "%x", tid);
1216 getpkt (&rs->buf, &rs->buf_size, 0);
1218 general_thread = ptid;
1220 continue_thread = ptid;
1224 set_general_thread (struct ptid ptid)
1226 set_thread (ptid, 1);
1230 set_continue_thread (struct ptid ptid)
1232 set_thread (ptid, 0);
1236 /* Return nonzero if the thread PTID is still alive on the remote
1240 remote_thread_alive (ptid_t ptid)
1242 struct remote_state *rs = get_remote_state ();
1243 int tid = ptid_get_tid (ptid);
1245 if (ptid_equal (ptid, magic_null_ptid))
1246 /* The main thread is always alive. */
1249 if (ptid_get_pid (ptid) != 0 && ptid_get_tid (ptid) == 0)
1250 /* The main thread is always alive. This can happen after a
1251 vAttach, if the remote side doesn't support
1256 xsnprintf (rs->buf, get_remote_packet_size (), "T-%08x", -tid);
1258 xsnprintf (rs->buf, get_remote_packet_size (), "T%08x", tid);
1260 getpkt (&rs->buf, &rs->buf_size, 0);
1261 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
1264 /* About these extended threadlist and threadinfo packets. They are
1265 variable length packets but, the fields within them are often fixed
1266 length. They are redundent enough to send over UDP as is the
1267 remote protocol in general. There is a matching unit test module
1270 #define OPAQUETHREADBYTES 8
1272 /* a 64 bit opaque identifier */
1273 typedef unsigned char threadref[OPAQUETHREADBYTES];
1275 /* WARNING: This threadref data structure comes from the remote O.S.,
1276 libstub protocol encoding, and remote.c. it is not particularly
1279 /* Right now, the internal structure is int. We want it to be bigger.
1283 typedef int gdb_threadref; /* Internal GDB thread reference. */
1285 /* gdb_ext_thread_info is an internal GDB data structure which is
1286 equivalent to the reply of the remote threadinfo packet. */
1288 struct gdb_ext_thread_info
1290 threadref threadid; /* External form of thread reference. */
1291 int active; /* Has state interesting to GDB?
1293 char display[256]; /* Brief state display, name,
1294 blocked/suspended. */
1295 char shortname[32]; /* To be used to name threads. */
1296 char more_display[256]; /* Long info, statistics, queue depth,
1300 /* The volume of remote transfers can be limited by submitting
1301 a mask containing bits specifying the desired information.
1302 Use a union of these values as the 'selection' parameter to
1303 get_thread_info. FIXME: Make these TAG names more thread specific.
1306 #define TAG_THREADID 1
1307 #define TAG_EXISTS 2
1308 #define TAG_DISPLAY 4
1309 #define TAG_THREADNAME 8
1310 #define TAG_MOREDISPLAY 16
1312 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
1314 char *unpack_varlen_hex (char *buff, ULONGEST *result);
1316 static char *unpack_nibble (char *buf, int *val);
1318 static char *pack_nibble (char *buf, int nibble);
1320 static char *pack_hex_byte (char *pkt, int /* unsigned char */ byte);
1322 static char *unpack_byte (char *buf, int *value);
1324 static char *pack_int (char *buf, int value);
1326 static char *unpack_int (char *buf, int *value);
1328 static char *unpack_string (char *src, char *dest, int length);
1330 static char *pack_threadid (char *pkt, threadref *id);
1332 static char *unpack_threadid (char *inbuf, threadref *id);
1334 void int_to_threadref (threadref *id, int value);
1336 static int threadref_to_int (threadref *ref);
1338 static void copy_threadref (threadref *dest, threadref *src);
1340 static int threadmatch (threadref *dest, threadref *src);
1342 static char *pack_threadinfo_request (char *pkt, int mode,
1345 static int remote_unpack_thread_info_response (char *pkt,
1346 threadref *expectedref,
1347 struct gdb_ext_thread_info
1351 static int remote_get_threadinfo (threadref *threadid,
1352 int fieldset, /*TAG mask */
1353 struct gdb_ext_thread_info *info);
1355 static char *pack_threadlist_request (char *pkt, int startflag,
1357 threadref *nextthread);
1359 static int parse_threadlist_response (char *pkt,
1361 threadref *original_echo,
1362 threadref *resultlist,
1365 static int remote_get_threadlist (int startflag,
1366 threadref *nextthread,
1370 threadref *threadlist);
1372 typedef int (*rmt_thread_action) (threadref *ref, void *context);
1374 static int remote_threadlist_iterator (rmt_thread_action stepfunction,
1375 void *context, int looplimit);
1377 static int remote_newthread_step (threadref *ref, void *context);
1379 /* Encode 64 bits in 16 chars of hex. */
1381 static const char hexchars[] = "0123456789abcdef";
1384 ishex (int ch, int *val)
1386 if ((ch >= 'a') && (ch <= 'f'))
1388 *val = ch - 'a' + 10;
1391 if ((ch >= 'A') && (ch <= 'F'))
1393 *val = ch - 'A' + 10;
1396 if ((ch >= '0') && (ch <= '9'))
1407 if (ch >= 'a' && ch <= 'f')
1408 return ch - 'a' + 10;
1409 if (ch >= '0' && ch <= '9')
1411 if (ch >= 'A' && ch <= 'F')
1412 return ch - 'A' + 10;
1417 stub_unpack_int (char *buff, int fieldlength)
1424 nibble = stubhex (*buff++);
1428 retval = retval << 4;
1434 unpack_varlen_hex (char *buff, /* packet to parse */
1438 ULONGEST retval = 0;
1440 while (ishex (*buff, &nibble))
1443 retval = retval << 4;
1444 retval |= nibble & 0x0f;
1451 unpack_nibble (char *buf, int *val)
1453 *val = fromhex (*buf++);
1458 pack_nibble (char *buf, int nibble)
1460 *buf++ = hexchars[(nibble & 0x0f)];
1465 pack_hex_byte (char *pkt, int byte)
1467 *pkt++ = hexchars[(byte >> 4) & 0xf];
1468 *pkt++ = hexchars[(byte & 0xf)];
1473 unpack_byte (char *buf, int *value)
1475 *value = stub_unpack_int (buf, 2);
1480 pack_int (char *buf, int value)
1482 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
1483 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
1484 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
1485 buf = pack_hex_byte (buf, (value & 0xff));
1490 unpack_int (char *buf, int *value)
1492 *value = stub_unpack_int (buf, 8);
1496 #if 0 /* Currently unused, uncomment when needed. */
1497 static char *pack_string (char *pkt, char *string);
1500 pack_string (char *pkt, char *string)
1505 len = strlen (string);
1507 len = 200; /* Bigger than most GDB packets, junk??? */
1508 pkt = pack_hex_byte (pkt, len);
1512 if ((ch == '\0') || (ch == '#'))
1513 ch = '*'; /* Protect encapsulation. */
1518 #endif /* 0 (unused) */
1521 unpack_string (char *src, char *dest, int length)
1530 pack_threadid (char *pkt, threadref *id)
1533 unsigned char *altid;
1535 altid = (unsigned char *) id;
1536 limit = pkt + BUF_THREAD_ID_SIZE;
1538 pkt = pack_hex_byte (pkt, *altid++);
1544 unpack_threadid (char *inbuf, threadref *id)
1547 char *limit = inbuf + BUF_THREAD_ID_SIZE;
1550 altref = (char *) id;
1552 while (inbuf < limit)
1554 x = stubhex (*inbuf++);
1555 y = stubhex (*inbuf++);
1556 *altref++ = (x << 4) | y;
1561 /* Externally, threadrefs are 64 bits but internally, they are still
1562 ints. This is due to a mismatch of specifications. We would like
1563 to use 64bit thread references internally. This is an adapter
1567 int_to_threadref (threadref *id, int value)
1569 unsigned char *scan;
1571 scan = (unsigned char *) id;
1577 *scan++ = (value >> 24) & 0xff;
1578 *scan++ = (value >> 16) & 0xff;
1579 *scan++ = (value >> 8) & 0xff;
1580 *scan++ = (value & 0xff);
1584 threadref_to_int (threadref *ref)
1587 unsigned char *scan;
1593 value = (value << 8) | ((*scan++) & 0xff);
1598 copy_threadref (threadref *dest, threadref *src)
1601 unsigned char *csrc, *cdest;
1603 csrc = (unsigned char *) src;
1604 cdest = (unsigned char *) dest;
1611 threadmatch (threadref *dest, threadref *src)
1613 /* Things are broken right now, so just assume we got a match. */
1615 unsigned char *srcp, *destp;
1617 srcp = (char *) src;
1618 destp = (char *) dest;
1622 result &= (*srcp++ == *destp++) ? 1 : 0;
1629 threadid:1, # always request threadid
1636 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
1639 pack_threadinfo_request (char *pkt, int mode, threadref *id)
1641 *pkt++ = 'q'; /* Info Query */
1642 *pkt++ = 'P'; /* process or thread info */
1643 pkt = pack_int (pkt, mode); /* mode */
1644 pkt = pack_threadid (pkt, id); /* threadid */
1645 *pkt = '\0'; /* terminate */
1649 /* These values tag the fields in a thread info response packet. */
1650 /* Tagging the fields allows us to request specific fields and to
1651 add more fields as time goes by. */
1653 #define TAG_THREADID 1 /* Echo the thread identifier. */
1654 #define TAG_EXISTS 2 /* Is this process defined enough to
1655 fetch registers and its stack? */
1656 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
1657 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
1658 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
1662 remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
1663 struct gdb_ext_thread_info *info)
1665 struct remote_state *rs = get_remote_state ();
1669 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
1672 /* info->threadid = 0; FIXME: implement zero_threadref. */
1674 info->display[0] = '\0';
1675 info->shortname[0] = '\0';
1676 info->more_display[0] = '\0';
1678 /* Assume the characters indicating the packet type have been
1680 pkt = unpack_int (pkt, &mask); /* arg mask */
1681 pkt = unpack_threadid (pkt, &ref);
1684 warning (_("Incomplete response to threadinfo request."));
1685 if (!threadmatch (&ref, expectedref))
1686 { /* This is an answer to a different request. */
1687 warning (_("ERROR RMT Thread info mismatch."));
1690 copy_threadref (&info->threadid, &ref);
1692 /* Loop on tagged fields , try to bail if somthing goes wrong. */
1694 /* Packets are terminated with nulls. */
1695 while ((pkt < limit) && mask && *pkt)
1697 pkt = unpack_int (pkt, &tag); /* tag */
1698 pkt = unpack_byte (pkt, &length); /* length */
1699 if (!(tag & mask)) /* Tags out of synch with mask. */
1701 warning (_("ERROR RMT: threadinfo tag mismatch."));
1705 if (tag == TAG_THREADID)
1709 warning (_("ERROR RMT: length of threadid is not 16."));
1713 pkt = unpack_threadid (pkt, &ref);
1714 mask = mask & ~TAG_THREADID;
1717 if (tag == TAG_EXISTS)
1719 info->active = stub_unpack_int (pkt, length);
1721 mask = mask & ~(TAG_EXISTS);
1724 warning (_("ERROR RMT: 'exists' length too long."));
1730 if (tag == TAG_THREADNAME)
1732 pkt = unpack_string (pkt, &info->shortname[0], length);
1733 mask = mask & ~TAG_THREADNAME;
1736 if (tag == TAG_DISPLAY)
1738 pkt = unpack_string (pkt, &info->display[0], length);
1739 mask = mask & ~TAG_DISPLAY;
1742 if (tag == TAG_MOREDISPLAY)
1744 pkt = unpack_string (pkt, &info->more_display[0], length);
1745 mask = mask & ~TAG_MOREDISPLAY;
1748 warning (_("ERROR RMT: unknown thread info tag."));
1749 break; /* Not a tag we know about. */
1755 remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
1756 struct gdb_ext_thread_info *info)
1758 struct remote_state *rs = get_remote_state ();
1761 pack_threadinfo_request (rs->buf, fieldset, threadid);
1763 getpkt (&rs->buf, &rs->buf_size, 0);
1764 result = remote_unpack_thread_info_response (rs->buf + 2,
1769 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
1772 pack_threadlist_request (char *pkt, int startflag, int threadcount,
1773 threadref *nextthread)
1775 *pkt++ = 'q'; /* info query packet */
1776 *pkt++ = 'L'; /* Process LIST or threadLIST request */
1777 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
1778 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
1779 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
1784 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
1787 parse_threadlist_response (char *pkt, int result_limit,
1788 threadref *original_echo, threadref *resultlist,
1791 struct remote_state *rs = get_remote_state ();
1793 int count, resultcount, done;
1796 /* Assume the 'q' and 'M chars have been stripped. */
1797 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
1798 /* done parse past here */
1799 pkt = unpack_byte (pkt, &count); /* count field */
1800 pkt = unpack_nibble (pkt, &done);
1801 /* The first threadid is the argument threadid. */
1802 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
1803 while ((count-- > 0) && (pkt < limit))
1805 pkt = unpack_threadid (pkt, resultlist++);
1806 if (resultcount++ >= result_limit)
1815 remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
1816 int *done, int *result_count, threadref *threadlist)
1818 struct remote_state *rs = get_remote_state ();
1819 static threadref echo_nextthread;
1822 /* Trancate result limit to be smaller than the packet size. */
1823 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10) >= get_remote_packet_size ())
1824 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
1826 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
1828 getpkt (&rs->buf, &rs->buf_size, 0);
1830 if (*rs->buf == '\0')
1834 parse_threadlist_response (rs->buf + 2, result_limit, &echo_nextthread,
1837 if (!threadmatch (&echo_nextthread, nextthread))
1839 /* FIXME: This is a good reason to drop the packet. */
1840 /* Possably, there is a duplicate response. */
1842 retransmit immediatly - race conditions
1843 retransmit after timeout - yes
1845 wait for packet, then exit
1847 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
1848 return 0; /* I choose simply exiting. */
1850 if (*result_count <= 0)
1854 warning (_("RMT ERROR : failed to get remote thread list."));
1857 return result; /* break; */
1859 if (*result_count > result_limit)
1862 warning (_("RMT ERROR: threadlist response longer than requested."));
1868 /* This is the interface between remote and threads, remotes upper
1871 /* remote_find_new_threads retrieves the thread list and for each
1872 thread in the list, looks up the thread in GDB's internal list,
1873 adding the thread if it does not already exist. This involves
1874 getting partial thread lists from the remote target so, polling the
1875 quit_flag is required. */
1878 /* About this many threadisds fit in a packet. */
1880 #define MAXTHREADLISTRESULTS 32
1883 remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
1886 int done, i, result_count;
1890 static threadref nextthread;
1891 static threadref resultthreadlist[MAXTHREADLISTRESULTS];
1896 if (loopcount++ > looplimit)
1899 warning (_("Remote fetch threadlist -infinite loop-."));
1902 if (!remote_get_threadlist (startflag, &nextthread, MAXTHREADLISTRESULTS,
1903 &done, &result_count, resultthreadlist))
1908 /* Clear for later iterations. */
1910 /* Setup to resume next batch of thread references, set nextthread. */
1911 if (result_count >= 1)
1912 copy_threadref (&nextthread, &resultthreadlist[result_count - 1]);
1914 while (result_count--)
1915 if (!(result = (*stepfunction) (&resultthreadlist[i++], context)))
1922 remote_newthread_step (threadref *ref, void *context)
1924 int pid = ptid_get_pid (inferior_ptid);
1925 ptid_t ptid = ptid_build (pid, 0, threadref_to_int (ref));
1927 if (!in_thread_list (ptid))
1929 return 1; /* continue iterator */
1932 #define CRAZY_MAX_THREADS 1000
1935 remote_current_thread (ptid_t oldpid)
1937 struct remote_state *rs = get_remote_state ();
1943 getpkt (&rs->buf, &rs->buf_size, 0);
1944 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
1946 /* Use strtoul here, so we'll correctly parse values whose
1947 highest bit is set. The protocol carries them as a simple
1948 series of hex digits; in the absence of a sign, strtol will
1949 see such values as positive numbers out of range for signed
1950 'long', and return LONG_MAX to indicate an overflow. */
1951 tid = strtoul (&rs->buf[2], NULL, 16);
1952 pid = ptid_get_pid (oldpid);
1953 return ptid_build (pid, 0, tid);
1959 /* Find new threads for info threads command.
1960 * Original version, using John Metzler's thread protocol.
1964 remote_find_new_threads (void)
1966 remote_threadlist_iterator (remote_newthread_step, 0,
1971 * Find all threads for info threads command.
1972 * Uses new thread protocol contributed by Cisco.
1973 * Falls back and attempts to use the older method (above)
1974 * if the target doesn't respond to the new method.
1978 remote_threads_info (void)
1980 struct remote_state *rs = get_remote_state ();
1986 if (remote_desc == 0) /* paranoia */
1987 error (_("Command can only be used when connected to the remote target."));
1989 if (use_threadinfo_query)
1991 putpkt ("qfThreadInfo");
1992 getpkt (&rs->buf, &rs->buf_size, 0);
1994 if (bufp[0] != '\0') /* q packet recognized */
1996 while (*bufp++ == 'm') /* reply contains one or more TID */
2000 /* Use strtoul here, so we'll correctly parse values
2001 whose highest bit is set. The protocol carries
2002 them as a simple series of hex digits; in the
2003 absence of a sign, strtol will see such values as
2004 positive numbers out of range for signed 'long',
2005 and return LONG_MAX to indicate an overflow. */
2006 tid = strtoul (bufp, &bufp, 16);
2007 pid = ptid_get_pid (inferior_ptid);
2008 new_thread = ptid_build (pid, 0, tid);
2009 if (tid != 0 && !in_thread_list (new_thread))
2010 add_thread (new_thread);
2012 while (*bufp++ == ','); /* comma-separated list */
2013 putpkt ("qsThreadInfo");
2014 getpkt (&rs->buf, &rs->buf_size, 0);
2021 /* Else fall back to old method based on jmetzler protocol. */
2022 use_threadinfo_query = 0;
2023 remote_find_new_threads ();
2028 * Collect a descriptive string about the given thread.
2029 * The target may say anything it wants to about the thread
2030 * (typically info about its blocked / runnable state, name, etc.).
2031 * This string will appear in the info threads display.
2033 * Optional: targets are not required to implement this function.
2037 remote_threads_extra_info (struct thread_info *tp)
2039 struct remote_state *rs = get_remote_state ();
2043 struct gdb_ext_thread_info threadinfo;
2044 static char display_buf[100]; /* arbitrary... */
2045 int n = 0; /* position in display_buf */
2047 if (remote_desc == 0) /* paranoia */
2048 internal_error (__FILE__, __LINE__,
2049 _("remote_threads_extra_info"));
2051 if (ptid_equal (tp->ptid, magic_null_ptid)
2052 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_tid (tp->ptid) == 0))
2053 /* This is the main thread which was added by GDB. The remote
2054 server doesn't know about it. */
2057 if (use_threadextra_query)
2059 xsnprintf (rs->buf, get_remote_packet_size (), "qThreadExtraInfo,%lx",
2060 ptid_get_tid (tp->ptid));
2062 getpkt (&rs->buf, &rs->buf_size, 0);
2063 if (rs->buf[0] != 0)
2065 n = min (strlen (rs->buf) / 2, sizeof (display_buf));
2066 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
2067 display_buf [result] = '\0';
2072 /* If the above query fails, fall back to the old method. */
2073 use_threadextra_query = 0;
2074 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
2075 | TAG_MOREDISPLAY | TAG_DISPLAY;
2076 int_to_threadref (&id, ptid_get_tid (tp->ptid));
2077 if (remote_get_threadinfo (&id, set, &threadinfo))
2078 if (threadinfo.active)
2080 if (*threadinfo.shortname)
2081 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
2082 " Name: %s,", threadinfo.shortname);
2083 if (*threadinfo.display)
2084 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
2085 " State: %s,", threadinfo.display);
2086 if (*threadinfo.more_display)
2087 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
2088 " Priority: %s", threadinfo.more_display);
2092 /* For purely cosmetic reasons, clear up trailing commas. */
2093 if (',' == display_buf[n-1])
2094 display_buf[n-1] = ' ';
2102 /* Restart the remote side; this is an extended protocol operation. */
2105 extended_remote_restart (void)
2107 struct remote_state *rs = get_remote_state ();
2109 /* Send the restart command; for reasons I don't understand the
2110 remote side really expects a number after the "R". */
2111 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
2114 remote_fileio_reset ();
2117 /* Clean up connection to a remote debugger. */
2120 remote_close (int quitting)
2123 serial_close (remote_desc);
2127 /* Query the remote side for the text, data and bss offsets. */
2132 struct remote_state *rs = get_remote_state ();
2135 int lose, num_segments = 0, do_sections, do_segments;
2136 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
2137 struct section_offsets *offs;
2138 struct symfile_segment_data *data;
2140 if (symfile_objfile == NULL)
2143 putpkt ("qOffsets");
2144 getpkt (&rs->buf, &rs->buf_size, 0);
2147 if (buf[0] == '\000')
2148 return; /* Return silently. Stub doesn't support
2152 warning (_("Remote failure reply: %s"), buf);
2156 /* Pick up each field in turn. This used to be done with scanf, but
2157 scanf will make trouble if CORE_ADDR size doesn't match
2158 conversion directives correctly. The following code will work
2159 with any size of CORE_ADDR. */
2160 text_addr = data_addr = bss_addr = 0;
2164 if (strncmp (ptr, "Text=", 5) == 0)
2167 /* Don't use strtol, could lose on big values. */
2168 while (*ptr && *ptr != ';')
2169 text_addr = (text_addr << 4) + fromhex (*ptr++);
2171 if (strncmp (ptr, ";Data=", 6) == 0)
2174 while (*ptr && *ptr != ';')
2175 data_addr = (data_addr << 4) + fromhex (*ptr++);
2180 if (!lose && strncmp (ptr, ";Bss=", 5) == 0)
2183 while (*ptr && *ptr != ';')
2184 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
2186 if (bss_addr != data_addr)
2187 warning (_("Target reported unsupported offsets: %s"), buf);
2192 else if (strncmp (ptr, "TextSeg=", 8) == 0)
2195 /* Don't use strtol, could lose on big values. */
2196 while (*ptr && *ptr != ';')
2197 text_addr = (text_addr << 4) + fromhex (*ptr++);
2200 if (strncmp (ptr, ";DataSeg=", 9) == 0)
2203 while (*ptr && *ptr != ';')
2204 data_addr = (data_addr << 4) + fromhex (*ptr++);
2212 error (_("Malformed response to offset query, %s"), buf);
2213 else if (*ptr != '\0')
2214 warning (_("Target reported unsupported offsets: %s"), buf);
2216 offs = ((struct section_offsets *)
2217 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
2218 memcpy (offs, symfile_objfile->section_offsets,
2219 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
2221 data = get_symfile_segment_data (symfile_objfile->obfd);
2222 do_segments = (data != NULL);
2223 do_sections = num_segments == 0;
2225 if (num_segments > 0)
2227 segments[0] = text_addr;
2228 segments[1] = data_addr;
2230 /* If we have two segments, we can still try to relocate everything
2231 by assuming that the .text and .data offsets apply to the whole
2232 text and data segments. Convert the offsets given in the packet
2233 to base addresses for symfile_map_offsets_to_segments. */
2234 else if (data && data->num_segments == 2)
2236 segments[0] = data->segment_bases[0] + text_addr;
2237 segments[1] = data->segment_bases[1] + data_addr;
2240 /* If the object file has only one segment, assume that it is text
2241 rather than data; main programs with no writable data are rare,
2242 but programs with no code are useless. Of course the code might
2243 have ended up in the data segment... to detect that we would need
2244 the permissions here. */
2245 else if (data && data->num_segments == 1)
2247 segments[0] = data->segment_bases[0] + text_addr;
2250 /* There's no way to relocate by segment. */
2256 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
2257 offs, num_segments, segments);
2259 if (ret == 0 && !do_sections)
2260 error (_("Can not handle qOffsets TextSeg response with this symbol file"));
2267 free_symfile_segment_data (data);
2271 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
2273 /* This is a temporary kludge to force data and bss to use the same offsets
2274 because that's what nlmconv does now. The real solution requires changes
2275 to the stub and remote.c that I don't have time to do right now. */
2277 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
2278 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
2281 objfile_relocate (symfile_objfile, offs);
2284 /* Stub for catch_exception. */
2286 struct start_remote_args
2290 /* The current target. */
2291 struct target_ops *target;
2293 /* Non-zero if this is an extended-remote target. */
2298 remote_start_remote (struct ui_out *uiout, void *opaque)
2300 struct remote_state *rs = get_remote_state ();
2301 struct start_remote_args *args = opaque;
2302 char *wait_status = NULL;
2304 immediate_quit++; /* Allow user to interrupt it. */
2306 /* Check whether the target is running now. */
2308 getpkt (&rs->buf, &rs->buf_size, 0);
2310 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
2312 if (args->extended_p)
2314 /* We're connected, but not running. Drop out before we
2315 call start_remote. */
2316 target_mark_exited (args->target);
2320 error (_("The target is not running (try extended-remote?)"));
2324 if (args->extended_p)
2325 target_mark_running (args->target);
2327 /* Save the reply for later. */
2328 wait_status = alloca (strlen (rs->buf) + 1);
2329 strcpy (wait_status, rs->buf);
2333 init_thread_list ();
2335 /* Let the stub know that we want it to return the thread. */
2336 set_continue_thread (minus_one_ptid);
2338 /* Without this, some commands which require an active target
2339 (such as kill) won't work. This variable serves (at least)
2340 double duty as both the pid of the target process (if it has
2341 such), and as a flag indicating that a target is active.
2342 These functions should be split out into seperate variables,
2343 especially since GDB will someday have a notion of debugging
2344 several processes. */
2345 inferior_ptid = magic_null_ptid;
2347 /* Now, if we have thread information, update inferior_ptid. */
2348 inferior_ptid = remote_current_thread (inferior_ptid);
2350 /* Always add the main thread. */
2351 add_thread_silent (inferior_ptid);
2353 get_offsets (); /* Get text, data & bss offsets. */
2355 /* Use the previously fetched status. */
2356 gdb_assert (wait_status != NULL);
2357 strcpy (rs->buf, wait_status);
2358 rs->cached_wait_status = 1;
2361 start_remote (args->from_tty); /* Initialize gdb process mechanisms. */
2364 /* Open a connection to a remote debugger.
2365 NAME is the filename used for communication. */
2368 remote_open (char *name, int from_tty)
2370 remote_open_1 (name, from_tty, &remote_ops, 0);
2373 /* Open a connection to a remote debugger using the extended
2374 remote gdb protocol. NAME is the filename used for communication. */
2377 extended_remote_open (char *name, int from_tty)
2379 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
2382 /* Generic code for opening a connection to a remote target. */
2385 init_all_packet_configs (void)
2388 for (i = 0; i < PACKET_MAX; i++)
2389 update_packet_config (&remote_protocol_packets[i]);
2392 /* Symbol look-up. */
2395 remote_check_symbols (struct objfile *objfile)
2397 struct remote_state *rs = get_remote_state ();
2398 char *msg, *reply, *tmp;
2399 struct minimal_symbol *sym;
2402 if (remote_protocol_packets[PACKET_qSymbol].support == PACKET_DISABLE)
2405 /* Allocate a message buffer. We can't reuse the input buffer in RS,
2406 because we need both at the same time. */
2407 msg = alloca (get_remote_packet_size ());
2409 /* Invite target to request symbol lookups. */
2411 putpkt ("qSymbol::");
2412 getpkt (&rs->buf, &rs->buf_size, 0);
2413 packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSymbol]);
2416 while (strncmp (reply, "qSymbol:", 8) == 0)
2419 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
2421 sym = lookup_minimal_symbol (msg, NULL, NULL);
2423 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
2426 CORE_ADDR sym_addr = SYMBOL_VALUE_ADDRESS (sym);
2428 /* If this is a function address, return the start of code
2429 instead of any data function descriptor. */
2430 sym_addr = gdbarch_convert_from_func_ptr_addr (current_gdbarch,
2434 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
2435 paddr_nz (sym_addr), &reply[8]);
2439 getpkt (&rs->buf, &rs->buf_size, 0);
2444 static struct serial *
2445 remote_serial_open (char *name)
2447 static int udp_warning = 0;
2449 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
2450 of in ser-tcp.c, because it is the remote protocol assuming that the
2451 serial connection is reliable and not the serial connection promising
2453 if (!udp_warning && strncmp (name, "udp:", 4) == 0)
2456 The remote protocol may be unreliable over UDP.\n\
2457 Some events may be lost, rendering further debugging impossible."));
2461 return serial_open (name);
2464 /* This type describes each known response to the qSupported
2466 struct protocol_feature
2468 /* The name of this protocol feature. */
2471 /* The default for this protocol feature. */
2472 enum packet_support default_support;
2474 /* The function to call when this feature is reported, or after
2475 qSupported processing if the feature is not supported.
2476 The first argument points to this structure. The second
2477 argument indicates whether the packet requested support be
2478 enabled, disabled, or probed (or the default, if this function
2479 is being called at the end of processing and this feature was
2480 not reported). The third argument may be NULL; if not NULL, it
2481 is a NUL-terminated string taken from the packet following
2482 this feature's name and an equals sign. */
2483 void (*func) (const struct protocol_feature *, enum packet_support,
2486 /* The corresponding packet for this feature. Only used if
2487 FUNC is remote_supported_packet. */
2492 remote_supported_packet (const struct protocol_feature *feature,
2493 enum packet_support support,
2494 const char *argument)
2498 warning (_("Remote qSupported response supplied an unexpected value for"
2499 " \"%s\"."), feature->name);
2503 if (remote_protocol_packets[feature->packet].support
2504 == PACKET_SUPPORT_UNKNOWN)
2505 remote_protocol_packets[feature->packet].support = support;
2509 remote_packet_size (const struct protocol_feature *feature,
2510 enum packet_support support, const char *value)
2512 struct remote_state *rs = get_remote_state ();
2517 if (support != PACKET_ENABLE)
2520 if (value == NULL || *value == '\0')
2522 warning (_("Remote target reported \"%s\" without a size."),
2528 packet_size = strtol (value, &value_end, 16);
2529 if (errno != 0 || *value_end != '\0' || packet_size < 0)
2531 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
2532 feature->name, value);
2536 if (packet_size > MAX_REMOTE_PACKET_SIZE)
2538 warning (_("limiting remote suggested packet size (%d bytes) to %d"),
2539 packet_size, MAX_REMOTE_PACKET_SIZE);
2540 packet_size = MAX_REMOTE_PACKET_SIZE;
2543 /* Record the new maximum packet size. */
2544 rs->explicit_packet_size = packet_size;
2547 static struct protocol_feature remote_protocol_features[] = {
2548 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
2549 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
2550 PACKET_qXfer_auxv },
2551 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
2552 PACKET_qXfer_features },
2553 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
2554 PACKET_qXfer_libraries },
2555 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
2556 PACKET_qXfer_memory_map },
2557 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
2558 PACKET_qXfer_spu_read },
2559 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
2560 PACKET_qXfer_spu_write },
2561 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
2562 PACKET_QPassSignals },
2563 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
2564 PACKET_QStartNoAckMode },
2568 remote_query_supported (void)
2570 struct remote_state *rs = get_remote_state ();
2573 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
2575 /* The packet support flags are handled differently for this packet
2576 than for most others. We treat an error, a disabled packet, and
2577 an empty response identically: any features which must be reported
2578 to be used will be automatically disabled. An empty buffer
2579 accomplishes this, since that is also the representation for a list
2580 containing no features. */
2583 if (remote_protocol_packets[PACKET_qSupported].support != PACKET_DISABLE)
2585 putpkt ("qSupported");
2586 getpkt (&rs->buf, &rs->buf_size, 0);
2588 /* If an error occured, warn, but do not return - just reset the
2589 buffer to empty and go on to disable features. */
2590 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
2593 warning (_("Remote failure reply: %s"), rs->buf);
2598 memset (seen, 0, sizeof (seen));
2603 enum packet_support is_supported;
2604 char *p, *end, *name_end, *value;
2606 /* First separate out this item from the rest of the packet. If
2607 there's another item after this, we overwrite the separator
2608 (terminated strings are much easier to work with). */
2610 end = strchr (p, ';');
2613 end = p + strlen (p);
2623 warning (_("empty item in \"qSupported\" response"));
2628 name_end = strchr (p, '=');
2631 /* This is a name=value entry. */
2632 is_supported = PACKET_ENABLE;
2633 value = name_end + 1;
2642 is_supported = PACKET_ENABLE;
2646 is_supported = PACKET_DISABLE;
2650 is_supported = PACKET_SUPPORT_UNKNOWN;
2654 warning (_("unrecognized item \"%s\" in \"qSupported\" response"), p);
2660 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
2661 if (strcmp (remote_protocol_features[i].name, p) == 0)
2663 const struct protocol_feature *feature;
2666 feature = &remote_protocol_features[i];
2667 feature->func (feature, is_supported, value);
2672 /* If we increased the packet size, make sure to increase the global
2673 buffer size also. We delay this until after parsing the entire
2674 qSupported packet, because this is the same buffer we were
2676 if (rs->buf_size < rs->explicit_packet_size)
2678 rs->buf_size = rs->explicit_packet_size;
2679 rs->buf = xrealloc (rs->buf, rs->buf_size);
2682 /* Handle the defaults for unmentioned features. */
2683 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
2686 const struct protocol_feature *feature;
2688 feature = &remote_protocol_features[i];
2689 feature->func (feature, feature->default_support, NULL);
2695 remote_open_1 (char *name, int from_tty, struct target_ops *target, int extended_p)
2697 struct remote_state *rs = get_remote_state ();
2698 struct packet_config *noack_config;
2701 error (_("To open a remote debug connection, you need to specify what\n"
2702 "serial device is attached to the remote system\n"
2703 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
2705 /* See FIXME above. */
2706 if (!remote_async_permitted)
2707 wait_forever_enabled_p = 1;
2709 /* If we're connected to a running target, target_preopen will kill it.
2710 But if we're connected to a target system with no running process,
2711 then we will still be connected when it returns. Ask this question
2712 first, before target_preopen has a chance to kill anything. */
2713 if (remote_desc != NULL && !target_has_execution)
2716 || query (_("Already connected to a remote target. Disconnect? ")))
2719 error (_("Still connected."));
2722 target_preopen (from_tty);
2724 unpush_target (target);
2726 /* This time without a query. If we were connected to an
2727 extended-remote target and target_preopen killed the running
2728 process, we may still be connected. If we are starting "target
2729 remote" now, the extended-remote target will not have been
2730 removed by unpush_target. */
2731 if (remote_desc != NULL && !target_has_execution)
2734 /* Make sure we send the passed signals list the next time we resume. */
2735 xfree (last_pass_packet);
2736 last_pass_packet = NULL;
2738 remote_fileio_reset ();
2739 reopen_exec_file ();
2742 remote_desc = remote_serial_open (name);
2744 perror_with_name (name);
2746 if (baud_rate != -1)
2748 if (serial_setbaudrate (remote_desc, baud_rate))
2750 /* The requested speed could not be set. Error out to
2751 top level after closing remote_desc. Take care to
2752 set remote_desc to NULL to avoid closing remote_desc
2754 serial_close (remote_desc);
2756 perror_with_name (name);
2760 serial_raw (remote_desc);
2762 /* If there is something sitting in the buffer we might take it as a
2763 response to a command, which would be bad. */
2764 serial_flush_input (remote_desc);
2768 puts_filtered ("Remote debugging using ");
2769 puts_filtered (name);
2770 puts_filtered ("\n");
2772 push_target (target); /* Switch to using remote target now. */
2774 /* Assume that the target is running, unless we learn otherwise. */
2775 target_mark_running (target);
2777 /* Reset the target state; these things will be queried either by
2778 remote_query_supported or as they are needed. */
2779 init_all_packet_configs ();
2780 rs->explicit_packet_size = 0;
2783 general_thread = not_sent_ptid;
2784 continue_thread = not_sent_ptid;
2786 /* Probe for ability to use "ThreadInfo" query, as required. */
2787 use_threadinfo_query = 1;
2788 use_threadextra_query = 1;
2790 /* Ack any packet which the remote side has already sent. */
2791 serial_write (remote_desc, "+", 1);
2793 /* The first packet we send to the target is the optional "supported
2794 packets" request. If the target can answer this, it will tell us
2795 which later probes to skip. */
2796 remote_query_supported ();
2798 /* Next, we possibly activate noack mode.
2800 If the QStartNoAckMode packet configuration is set to AUTO,
2801 enable noack mode if the stub reported a wish for it with
2804 If set to TRUE, then enable noack mode even if the stub didn't
2805 report it in qSupported. If the stub doesn't reply OK, the
2806 session ends with an error.
2808 If FALSE, then don't activate noack mode, regardless of what the
2809 stub claimed should be the default with qSupported. */
2811 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
2813 if (noack_config->detect == AUTO_BOOLEAN_TRUE
2814 || (noack_config->detect == AUTO_BOOLEAN_AUTO
2815 && noack_config->support == PACKET_ENABLE))
2817 putpkt ("QStartNoAckMode");
2818 getpkt (&rs->buf, &rs->buf_size, 0);
2819 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
2823 /* Next, if the target can specify a description, read it. We do
2824 this before anything involving memory or registers. */
2825 target_find_description ();
2827 if (remote_async_permitted)
2829 /* With this target we start out by owning the terminal. */
2830 remote_async_terminal_ours_p = 1;
2832 /* FIXME: cagney/1999-09-23: During the initial connection it is
2833 assumed that the target is already ready and able to respond to
2834 requests. Unfortunately remote_start_remote() eventually calls
2835 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
2836 around this. Eventually a mechanism that allows
2837 wait_for_inferior() to expect/get timeouts will be
2839 wait_forever_enabled_p = 0;
2842 /* First delete any symbols previously loaded from shared libraries. */
2843 no_shared_libraries (NULL, 0);
2845 /* Start the remote connection. If error() or QUIT, discard this
2846 target (we'd otherwise be in an inconsistent state) and then
2847 propogate the error on up the exception chain. This ensures that
2848 the caller doesn't stumble along blindly assuming that the
2849 function succeeded. The CLI doesn't have this problem but other
2850 UI's, such as MI do.
2852 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
2853 this function should return an error indication letting the
2854 caller restore the previous state. Unfortunately the command
2855 ``target remote'' is directly wired to this function making that
2856 impossible. On a positive note, the CLI side of this problem has
2857 been fixed - the function set_cmd_context() makes it possible for
2858 all the ``target ....'' commands to share a common callback
2859 function. See cli-dump.c. */
2861 struct gdb_exception ex;
2862 struct start_remote_args args;
2864 args.from_tty = from_tty;
2865 args.target = target;
2866 args.extended_p = extended_p;
2868 ex = catch_exception (uiout, remote_start_remote, &args, RETURN_MASK_ALL);
2872 if (remote_async_permitted)
2873 wait_forever_enabled_p = 1;
2874 throw_exception (ex);
2878 if (remote_async_permitted)
2879 wait_forever_enabled_p = 1;
2883 /* Tell the remote that we are using the extended protocol. */
2885 getpkt (&rs->buf, &rs->buf_size, 0);
2888 /* If we connected to a live target, do some additional setup. */
2889 if (target_has_execution)
2891 if (exec_bfd) /* No use without an exec file. */
2892 remote_check_symbols (symfile_objfile);
2896 /* This takes a program previously attached to and detaches it. After
2897 this is done, GDB can be used to debug some other program. We
2898 better not have left any breakpoints in the target program or it'll
2899 die when it hits one. */
2902 remote_detach_1 (char *args, int from_tty, int extended)
2904 struct remote_state *rs = get_remote_state ();
2907 error (_("Argument given to \"detach\" when remotely debugging."));
2909 if (!target_has_execution)
2910 error (_("No process to detach from."));
2912 /* Tell the remote target to detach. */
2913 strcpy (rs->buf, "D");
2915 getpkt (&rs->buf, &rs->buf_size, 0);
2917 if (rs->buf[0] == 'E')
2918 error (_("Can't detach process."));
2920 /* Unregister the file descriptor from the event loop. */
2921 if (target_is_async_p ())
2922 serial_async (remote_desc, NULL, 0);
2924 target_mourn_inferior ();
2928 puts_filtered ("Detached from remote process.\n");
2930 puts_filtered ("Ending remote debugging.\n");
2935 remote_detach (char *args, int from_tty)
2937 remote_detach_1 (args, from_tty, 0);
2941 extended_remote_detach (char *args, int from_tty)
2943 remote_detach_1 (args, from_tty, 1);
2946 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
2949 remote_disconnect (struct target_ops *target, char *args, int from_tty)
2952 error (_("Argument given to \"disconnect\" when remotely debugging."));
2954 /* Unregister the file descriptor from the event loop. */
2955 if (target_is_async_p ())
2956 serial_async (remote_desc, NULL, 0);
2958 /* Make sure we unpush even the extended remote targets; mourn
2959 won't do it. So call remote_mourn_1 directly instead of
2960 target_mourn_inferior. */
2961 remote_mourn_1 (target);
2964 puts_filtered ("Ending remote debugging.\n");
2967 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
2968 be chatty about it. */
2971 extended_remote_attach_1 (struct target_ops *target, char *args, int from_tty)
2973 struct remote_state *rs = get_remote_state ();
2976 char *wait_status = NULL;
2979 error_no_arg (_("process-id to attach"));
2982 pid = strtol (args, &dummy, 0);
2983 /* Some targets don't set errno on errors, grrr! */
2984 if (pid == 0 && args == dummy)
2985 error (_("Illegal process-id: %s."), args);
2987 if (remote_protocol_packets[PACKET_vAttach].support == PACKET_DISABLE)
2988 error (_("This target does not support attaching to a process"));
2990 sprintf (rs->buf, "vAttach;%x", pid);
2992 getpkt (&rs->buf, &rs->buf_size, 0);
2994 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vAttach]) == PACKET_OK)
2997 printf_unfiltered (_("Attached to %s\n"),
2998 target_pid_to_str (pid_to_ptid (pid)));
3000 /* Save the reply for later. */
3001 wait_status = alloca (strlen (rs->buf) + 1);
3002 strcpy (wait_status, rs->buf);
3004 else if (remote_protocol_packets[PACKET_vAttach].support == PACKET_DISABLE)
3005 error (_("This target does not support attaching to a process"));
3007 error (_("Attaching to %s failed"),
3008 target_pid_to_str (pid_to_ptid (pid)));
3010 target_mark_running (target);
3011 inferior_ptid = pid_to_ptid (pid);
3013 /* Now, if we have thread information, update inferior_ptid. */
3014 inferior_ptid = remote_current_thread (inferior_ptid);
3016 /* Now, add the main thread to the thread list. */
3017 add_thread_silent (inferior_ptid);
3021 /* Next, if the target can specify a description, read it. We do
3022 this before anything involving memory or registers. */
3023 target_find_description ();
3025 /* Use the previously fetched status. */
3026 gdb_assert (wait_status != NULL);
3027 strcpy (rs->buf, wait_status);
3028 rs->cached_wait_status = 1;
3032 extended_remote_attach (char *args, int from_tty)
3034 extended_remote_attach_1 (&extended_remote_ops, args, from_tty);
3037 /* Convert hex digit A to a number. */
3042 if (a >= '0' && a <= '9')
3044 else if (a >= 'a' && a <= 'f')
3045 return a - 'a' + 10;
3046 else if (a >= 'A' && a <= 'F')
3047 return a - 'A' + 10;
3049 error (_("Reply contains invalid hex digit %d"), a);
3053 hex2bin (const char *hex, gdb_byte *bin, int count)
3057 for (i = 0; i < count; i++)
3059 if (hex[0] == 0 || hex[1] == 0)
3061 /* Hex string is short, or of uneven length.
3062 Return the count that has been converted so far. */
3065 *bin++ = fromhex (hex[0]) * 16 + fromhex (hex[1]);
3071 /* Convert number NIB to a hex digit. */
3079 return 'a' + nib - 10;
3083 bin2hex (const gdb_byte *bin, char *hex, int count)
3086 /* May use a length, or a nul-terminated string as input. */
3088 count = strlen ((char *) bin);
3090 for (i = 0; i < count; i++)
3092 *hex++ = tohex ((*bin >> 4) & 0xf);
3093 *hex++ = tohex (*bin++ & 0xf);
3099 /* Check for the availability of vCont. This function should also check
3103 remote_vcont_probe (struct remote_state *rs)
3107 strcpy (rs->buf, "vCont?");
3109 getpkt (&rs->buf, &rs->buf_size, 0);
3112 /* Make sure that the features we assume are supported. */
3113 if (strncmp (buf, "vCont", 5) == 0)
3116 int support_s, support_S, support_c, support_C;
3122 while (p && *p == ';')
3125 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
3127 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
3129 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
3131 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
3134 p = strchr (p, ';');
3137 /* If s, S, c, and C are not all supported, we can't use vCont. Clearing
3138 BUF will make packet_ok disable the packet. */
3139 if (!support_s || !support_S || !support_c || !support_C)
3143 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
3146 /* Resume the remote inferior by using a "vCont" packet. The thread
3147 to be resumed is PTID; STEP and SIGGNAL indicate whether the
3148 resumed thread should be single-stepped and/or signalled. If PTID
3149 equals minus_one_ptid, then all threads are resumed; the thread to
3150 be stepped and/or signalled is given in the global INFERIOR_PTID.
3151 This function returns non-zero iff it resumes the inferior.
3153 This function issues a strict subset of all possible vCont commands at the
3157 remote_vcont_resume (ptid_t ptid, int step, enum target_signal siggnal)
3159 struct remote_state *rs = get_remote_state ();
3161 struct cleanup *old_cleanup;
3163 if (remote_protocol_packets[PACKET_vCont].support == PACKET_SUPPORT_UNKNOWN)
3164 remote_vcont_probe (rs);
3166 if (remote_protocol_packets[PACKET_vCont].support == PACKET_DISABLE)
3169 /* If we could generate a wider range of packets, we'd have to worry
3170 about overflowing BUF. Should there be a generic
3171 "multi-part-packet" packet? */
3173 if (ptid_equal (ptid, magic_null_ptid))
3175 /* MAGIC_NULL_PTID means that we don't have any active threads,
3176 so we don't have any TID numbers the inferior will
3177 understand. Make sure to only send forms that do not specify
3179 if (step && siggnal != TARGET_SIGNAL_0)
3180 outbuf = xstrprintf ("vCont;S%02x", siggnal);
3182 outbuf = xstrprintf ("vCont;s");
3183 else if (siggnal != TARGET_SIGNAL_0)
3184 outbuf = xstrprintf ("vCont;C%02x", siggnal);
3186 outbuf = xstrprintf ("vCont;c");
3188 else if (ptid_equal (ptid, minus_one_ptid))
3190 /* Resume all threads, with preference for INFERIOR_PTID. */
3191 int tid = ptid_get_tid (inferior_ptid);
3192 if (step && siggnal != TARGET_SIGNAL_0)
3193 outbuf = xstrprintf ("vCont;S%02x:%x;c", siggnal, tid);
3195 outbuf = xstrprintf ("vCont;s:%x;c", tid);
3196 else if (siggnal != TARGET_SIGNAL_0)
3197 outbuf = xstrprintf ("vCont;C%02x:%x;c", siggnal, tid);
3199 outbuf = xstrprintf ("vCont;c");
3203 /* Scheduler locking; resume only PTID. */
3204 int tid = ptid_get_tid (ptid);
3205 if (step && siggnal != TARGET_SIGNAL_0)
3206 outbuf = xstrprintf ("vCont;S%02x:%x", siggnal, tid);
3208 outbuf = xstrprintf ("vCont;s:%x", tid);
3209 else if (siggnal != TARGET_SIGNAL_0)
3210 outbuf = xstrprintf ("vCont;C%02x:%x", siggnal, tid);
3212 outbuf = xstrprintf ("vCont;c:%x", tid);
3215 gdb_assert (outbuf && strlen (outbuf) < get_remote_packet_size ());
3216 old_cleanup = make_cleanup (xfree, outbuf);
3220 do_cleanups (old_cleanup);
3225 /* Tell the remote machine to resume. */
3227 static enum target_signal last_sent_signal = TARGET_SIGNAL_0;
3229 static int last_sent_step;
3232 remote_resume (ptid_t ptid, int step, enum target_signal siggnal)
3234 struct remote_state *rs = get_remote_state ();
3237 last_sent_signal = siggnal;
3238 last_sent_step = step;
3240 /* Update the inferior on signals to silently pass, if they've changed. */
3241 remote_pass_signals ();
3243 /* The vCont packet doesn't need to specify threads via Hc. */
3244 if (remote_vcont_resume (ptid, step, siggnal))
3247 /* All other supported resume packets do use Hc, so set the continue
3249 if (ptid_equal (ptid, minus_one_ptid))
3250 set_continue_thread (any_thread_ptid);
3252 set_continue_thread (ptid);
3255 if (siggnal != TARGET_SIGNAL_0)
3257 buf[0] = step ? 'S' : 'C';
3258 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
3259 buf[2] = tohex (((int) siggnal) & 0xf);
3263 strcpy (buf, step ? "s" : "c");
3268 /* We are about to start executing the inferior, let's register it
3269 with the event loop. NOTE: this is the one place where all the
3270 execution commands end up. We could alternatively do this in each
3271 of the execution commands in infcmd.c. */
3272 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
3273 into infcmd.c in order to allow inferior function calls to work
3274 NOT asynchronously. */
3275 if (target_can_async_p ())
3276 target_async (inferior_event_handler, 0);
3280 /* Set up the signal handler for SIGINT, while the target is
3281 executing, ovewriting the 'regular' SIGINT signal handler. */
3283 initialize_sigint_signal_handler (void)
3285 signal (SIGINT, handle_remote_sigint);
3288 /* Signal handler for SIGINT, while the target is executing. */
3290 handle_remote_sigint (int sig)
3292 signal (sig, handle_remote_sigint_twice);
3293 mark_async_signal_handler_wrapper (sigint_remote_token);
3296 /* Signal handler for SIGINT, installed after SIGINT has already been
3297 sent once. It will take effect the second time that the user sends
3300 handle_remote_sigint_twice (int sig)
3302 signal (sig, handle_remote_sigint);
3303 mark_async_signal_handler_wrapper (sigint_remote_twice_token);
3306 /* Perform the real interruption of the target execution, in response
3309 async_remote_interrupt (gdb_client_data arg)
3312 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
3314 target_stop (inferior_ptid);
3317 /* Perform interrupt, if the first attempt did not succeed. Just give
3318 up on the target alltogether. */
3320 async_remote_interrupt_twice (gdb_client_data arg)
3323 fprintf_unfiltered (gdb_stdlog, "remote_interrupt_twice called\n");
3328 /* Reinstall the usual SIGINT handlers, after the target has
3331 cleanup_sigint_signal_handler (void *dummy)
3333 signal (SIGINT, handle_sigint);
3336 /* Send ^C to target to halt it. Target will respond, and send us a
3338 static void (*ofunc) (int);
3340 /* The command line interface's stop routine. This function is installed
3341 as a signal handler for SIGINT. The first time a user requests a
3342 stop, we call remote_stop to send a break or ^C. If there is no
3343 response from the target (it didn't stop when the user requested it),
3344 we ask the user if he'd like to detach from the target. */
3346 remote_interrupt (int signo)
3348 /* If this doesn't work, try more severe steps. */
3349 signal (signo, remote_interrupt_twice);
3351 gdb_call_async_signal_handler (sigint_remote_token, 1);
3354 /* The user typed ^C twice. */
3357 remote_interrupt_twice (int signo)
3359 signal (signo, ofunc);
3360 gdb_call_async_signal_handler (sigint_remote_twice_token, 1);
3361 signal (signo, remote_interrupt);
3364 /* This is the generic stop called via the target vector. When a target
3365 interrupt is requested, either by the command line or the GUI, we
3366 will eventually end up here. */
3368 remote_stop (ptid_t ptid)
3370 /* Send a break or a ^C, depending on user preference. */
3372 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
3375 serial_send_break (remote_desc);
3377 serial_write (remote_desc, "\003", 1);
3380 /* Ask the user what to do when an interrupt is received. */
3383 interrupt_query (void)
3385 target_terminal_ours ();
3387 if (query ("Interrupted while waiting for the program.\n\
3388 Give up (and stop debugging it)? "))
3390 target_mourn_inferior ();
3391 signal (SIGINT, handle_sigint);
3392 deprecated_throw_reason (RETURN_QUIT);
3395 target_terminal_inferior ();
3398 /* Enable/disable target terminal ownership. Most targets can use
3399 terminal groups to control terminal ownership. Remote targets are
3400 different in that explicit transfer of ownership to/from GDB/target
3404 remote_terminal_inferior (void)
3406 if (!remote_async_permitted)
3407 /* Nothing to do. */
3410 /* FIXME: cagney/1999-09-27: Shouldn't need to test for
3411 sync_execution here. This function should only be called when
3412 GDB is resuming the inferior in the forground. A background
3413 resume (``run&'') should leave GDB in control of the terminal and
3414 consequently should not call this code. */
3415 if (!sync_execution)
3417 /* FIXME: cagney/1999-09-27: Closely related to the above. Make
3418 calls target_terminal_*() idenpotent. The event-loop GDB talking
3419 to an asynchronous target with a synchronous command calls this
3420 function from both event-top.c and infrun.c/infcmd.c. Once GDB
3421 stops trying to transfer the terminal to the target when it
3422 shouldn't this guard can go away. */
3423 if (!remote_async_terminal_ours_p)
3425 delete_file_handler (input_fd);
3426 remote_async_terminal_ours_p = 0;
3427 initialize_sigint_signal_handler ();
3428 /* NOTE: At this point we could also register our selves as the
3429 recipient of all input. Any characters typed could then be
3430 passed on down to the target. */
3434 remote_terminal_ours (void)
3436 if (!remote_async_permitted)
3437 /* Nothing to do. */
3440 /* See FIXME in remote_terminal_inferior. */
3441 if (!sync_execution)
3443 /* See FIXME in remote_terminal_inferior. */
3444 if (remote_async_terminal_ours_p)
3446 cleanup_sigint_signal_handler (NULL);
3447 add_file_handler (input_fd, stdin_event_handler, 0);
3448 remote_async_terminal_ours_p = 1;
3452 remote_console_output (char *msg)
3456 for (p = msg; p[0] && p[1]; p += 2)
3459 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
3462 fputs_unfiltered (tb, gdb_stdtarg);
3464 gdb_flush (gdb_stdtarg);
3467 /* Wait until the remote machine stops, then return,
3468 storing status in STATUS just as `wait' would. */
3471 remote_wait (ptid_t ptid, struct target_waitstatus *status)
3473 struct remote_state *rs = get_remote_state ();
3474 struct remote_arch_state *rsa = get_remote_arch_state ();
3475 ULONGEST thread_num = -1;
3476 ULONGEST process_num = -1;
3478 int solibs_changed = 0;
3480 status->kind = TARGET_WAITKIND_EXITED;
3481 status->value.integer = 0;
3487 if (rs->cached_wait_status)
3488 /* Use the cached wait status, but only once. */
3489 rs->cached_wait_status = 0;
3492 if (!target_is_async_p ())
3494 ofunc = signal (SIGINT, remote_interrupt);
3495 /* If the user hit C-c before this packet, or between packets,
3496 pretend that it was hit right here. */
3500 remote_interrupt (SIGINT);
3503 /* FIXME: cagney/1999-09-27: If we're in async mode we should
3504 _never_ wait for ever -> test on target_is_async_p().
3505 However, before we do that we need to ensure that the caller
3506 knows how to take the target into/out of async mode. */
3507 getpkt (&rs->buf, &rs->buf_size, wait_forever_enabled_p);
3508 if (!target_is_async_p ())
3509 signal (SIGINT, ofunc);
3514 remote_stopped_by_watchpoint_p = 0;
3518 case 'E': /* Error of some sort. */
3519 /* We're out of sync with the target now. Did it continue or not?
3520 Not is more likely, so report a stop. */
3521 warning (_("Remote failure reply: %s"), buf);
3522 status->kind = TARGET_WAITKIND_STOPPED;
3523 status->value.sig = TARGET_SIGNAL_0;
3525 case 'F': /* File-I/O request. */
3526 remote_fileio_request (buf);
3528 case 'T': /* Status with PC, SP, FP, ... */
3530 gdb_byte regs[MAX_REGISTER_SIZE];
3532 /* Expedited reply, containing Signal, {regno, reg} repeat. */
3533 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
3535 n... = register number
3536 r... = register contents
3538 p = &buf[3]; /* after Txx */
3547 /* If the packet contains a register number, save it
3548 in pnum and set p1 to point to the character
3549 following it. Otherwise p1 points to p. */
3551 /* If this packet is an awatch packet, don't parse the
3552 'a' as a register number. */
3554 if (strncmp (p, "awatch", strlen("awatch")) != 0)
3556 /* Read the ``P'' register number. */
3557 pnum = strtol (p, &p_temp, 16);
3563 if (p1 == p) /* No register number present here. */
3565 p1 = strchr (p, ':');
3567 error (_("Malformed packet(a) (missing colon): %s\n\
3570 if (strncmp (p, "thread", p1 - p) == 0)
3572 p_temp = unpack_varlen_hex (++p1, &thread_num);
3575 else if ((strncmp (p, "watch", p1 - p) == 0)
3576 || (strncmp (p, "rwatch", p1 - p) == 0)
3577 || (strncmp (p, "awatch", p1 - p) == 0))
3579 remote_stopped_by_watchpoint_p = 1;
3580 p = unpack_varlen_hex (++p1, &addr);
3581 remote_watch_data_address = (CORE_ADDR)addr;
3583 else if (strncmp (p, "library", p1 - p) == 0)
3587 while (*p_temp && *p_temp != ';')
3595 /* Silently skip unknown optional info. */
3596 p_temp = strchr (p1 + 1, ';');
3603 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
3607 error (_("Malformed packet(b) (missing colon): %s\n\
3613 error (_("Remote sent bad register number %s: %s\n\
3615 phex_nz (pnum, 0), p, buf);
3617 fieldsize = hex2bin (p, regs,
3618 register_size (current_gdbarch,
3621 if (fieldsize < register_size (current_gdbarch,
3623 warning (_("Remote reply is too short: %s"), buf);
3624 regcache_raw_supply (get_current_regcache (),
3629 error (_("Remote register badly formatted: %s\nhere: %s"),
3635 case 'S': /* Old style status, just signal only. */
3637 status->kind = TARGET_WAITKIND_LOADED;
3640 status->kind = TARGET_WAITKIND_STOPPED;
3641 status->value.sig = (enum target_signal)
3642 (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
3645 case 'W': /* Target exited. */
3647 /* The remote process exited. */
3648 status->kind = TARGET_WAITKIND_EXITED;
3649 status->value.integer = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
3653 status->kind = TARGET_WAITKIND_SIGNALLED;
3654 status->value.sig = (enum target_signal)
3655 (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
3658 case 'O': /* Console output. */
3659 remote_console_output (buf + 1);
3660 if (target_can_async_p ())
3662 /* Return immediately to the event loop. The event loop
3663 will still be waiting on the inferior afterwards. */
3664 status->kind = TARGET_WAITKIND_IGNORE;
3670 if (last_sent_signal != TARGET_SIGNAL_0)
3672 /* Zero length reply means that we tried 'S' or 'C' and
3673 the remote system doesn't support it. */
3674 target_terminal_ours_for_output ();
3676 ("Can't send signals to this remote system. %s not sent.\n",
3677 target_signal_to_name (last_sent_signal));
3678 last_sent_signal = TARGET_SIGNAL_0;
3679 target_terminal_inferior ();
3681 strcpy ((char *) buf, last_sent_step ? "s" : "c");
3682 putpkt ((char *) buf);
3685 /* else fallthrough */
3687 warning (_("Invalid remote reply: %s"), buf);
3692 if (thread_num != -1)
3695 ptid = ptid_build (ptid_get_pid (inferior_ptid), 0, thread_num);
3696 record_currthread (ptid);
3700 return inferior_ptid;
3703 /* Fetch a single register using a 'p' packet. */
3706 fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
3708 struct remote_state *rs = get_remote_state ();
3710 char regp[MAX_REGISTER_SIZE];
3713 if (remote_protocol_packets[PACKET_p].support == PACKET_DISABLE)
3716 if (reg->pnum == -1)
3721 p += hexnumstr (p, reg->pnum);
3723 remote_send (&rs->buf, &rs->buf_size);
3727 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
3731 case PACKET_UNKNOWN:
3734 error (_("Could not fetch register \"%s\""),
3735 gdbarch_register_name (get_regcache_arch (regcache), reg->regnum));
3738 /* If this register is unfetchable, tell the regcache. */
3741 regcache_raw_supply (regcache, reg->regnum, NULL);
3745 /* Otherwise, parse and supply the value. */
3751 error (_("fetch_register_using_p: early buf termination"));
3753 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
3756 regcache_raw_supply (regcache, reg->regnum, regp);
3760 /* Fetch the registers included in the target's 'g' packet. */
3763 send_g_packet (void)
3765 struct remote_state *rs = get_remote_state ();
3770 sprintf (rs->buf, "g");
3771 remote_send (&rs->buf, &rs->buf_size);
3773 /* We can get out of synch in various cases. If the first character
3774 in the buffer is not a hex character, assume that has happened
3775 and try to fetch another packet to read. */
3776 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
3777 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
3778 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
3779 && rs->buf[0] != 'x') /* New: unavailable register value. */
3782 fprintf_unfiltered (gdb_stdlog,
3783 "Bad register packet; fetching a new packet\n");
3784 getpkt (&rs->buf, &rs->buf_size, 0);
3787 buf_len = strlen (rs->buf);
3789 /* Sanity check the received packet. */
3790 if (buf_len % 2 != 0)
3791 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
3797 process_g_packet (struct regcache *regcache)
3799 struct gdbarch *gdbarch = get_regcache_arch (regcache);
3800 struct remote_state *rs = get_remote_state ();
3801 struct remote_arch_state *rsa = get_remote_arch_state ();
3806 buf_len = strlen (rs->buf);
3808 /* Further sanity checks, with knowledge of the architecture. */
3809 if (buf_len > 2 * rsa->sizeof_g_packet)
3810 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
3812 /* Save the size of the packet sent to us by the target. It is used
3813 as a heuristic when determining the max size of packets that the
3814 target can safely receive. */
3815 if (rsa->actual_register_packet_size == 0)
3816 rsa->actual_register_packet_size = buf_len;
3818 /* If this is smaller than we guessed the 'g' packet would be,
3819 update our records. A 'g' reply that doesn't include a register's
3820 value implies either that the register is not available, or that
3821 the 'p' packet must be used. */
3822 if (buf_len < 2 * rsa->sizeof_g_packet)
3824 rsa->sizeof_g_packet = buf_len / 2;
3826 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
3828 if (rsa->regs[i].pnum == -1)
3831 if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
3832 rsa->regs[i].in_g_packet = 0;
3834 rsa->regs[i].in_g_packet = 1;
3838 regs = alloca (rsa->sizeof_g_packet);
3840 /* Unimplemented registers read as all bits zero. */
3841 memset (regs, 0, rsa->sizeof_g_packet);
3843 /* Reply describes registers byte by byte, each byte encoded as two
3844 hex characters. Suck them all up, then supply them to the
3845 register cacheing/storage mechanism. */
3848 for (i = 0; i < rsa->sizeof_g_packet; i++)
3850 if (p[0] == 0 || p[1] == 0)
3851 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
3852 internal_error (__FILE__, __LINE__,
3853 "unexpected end of 'g' packet reply");
3855 if (p[0] == 'x' && p[1] == 'x')
3856 regs[i] = 0; /* 'x' */
3858 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
3864 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
3866 struct packet_reg *r = &rsa->regs[i];
3869 if (r->offset * 2 >= strlen (rs->buf))
3870 /* This shouldn't happen - we adjusted in_g_packet above. */
3871 internal_error (__FILE__, __LINE__,
3872 "unexpected end of 'g' packet reply");
3873 else if (rs->buf[r->offset * 2] == 'x')
3875 gdb_assert (r->offset * 2 < strlen (rs->buf));
3876 /* The register isn't available, mark it as such (at
3877 the same time setting the value to zero). */
3878 regcache_raw_supply (regcache, r->regnum, NULL);
3881 regcache_raw_supply (regcache, r->regnum,
3889 fetch_registers_using_g (struct regcache *regcache)
3892 process_g_packet (regcache);
3896 remote_fetch_registers (struct regcache *regcache, int regnum)
3898 struct remote_state *rs = get_remote_state ();
3899 struct remote_arch_state *rsa = get_remote_arch_state ();
3902 set_general_thread (inferior_ptid);
3906 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
3907 gdb_assert (reg != NULL);
3909 /* If this register might be in the 'g' packet, try that first -
3910 we are likely to read more than one register. If this is the
3911 first 'g' packet, we might be overly optimistic about its
3912 contents, so fall back to 'p'. */
3913 if (reg->in_g_packet)
3915 fetch_registers_using_g (regcache);
3916 if (reg->in_g_packet)
3920 if (fetch_register_using_p (regcache, reg))
3923 /* This register is not available. */
3924 regcache_raw_supply (regcache, reg->regnum, NULL);
3929 fetch_registers_using_g (regcache);
3931 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
3932 if (!rsa->regs[i].in_g_packet)
3933 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
3935 /* This register is not available. */
3936 regcache_raw_supply (regcache, i, NULL);
3940 /* Prepare to store registers. Since we may send them all (using a
3941 'G' request), we have to read out the ones we don't want to change
3945 remote_prepare_to_store (struct regcache *regcache)
3947 struct remote_arch_state *rsa = get_remote_arch_state ();
3949 gdb_byte buf[MAX_REGISTER_SIZE];
3951 /* Make sure the entire registers array is valid. */
3952 switch (remote_protocol_packets[PACKET_P].support)
3954 case PACKET_DISABLE:
3955 case PACKET_SUPPORT_UNKNOWN:
3956 /* Make sure all the necessary registers are cached. */
3957 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
3958 if (rsa->regs[i].in_g_packet)
3959 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
3966 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
3967 packet was not recognized. */
3970 store_register_using_P (const struct regcache *regcache, struct packet_reg *reg)
3972 struct gdbarch *gdbarch = get_regcache_arch (regcache);
3973 struct remote_state *rs = get_remote_state ();
3974 struct remote_arch_state *rsa = get_remote_arch_state ();
3975 /* Try storing a single register. */
3976 char *buf = rs->buf;
3977 gdb_byte regp[MAX_REGISTER_SIZE];
3980 if (remote_protocol_packets[PACKET_P].support == PACKET_DISABLE)
3983 if (reg->pnum == -1)
3986 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
3987 p = buf + strlen (buf);
3988 regcache_raw_collect (regcache, reg->regnum, regp);
3989 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
3990 remote_send (&rs->buf, &rs->buf_size);
3992 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
3997 error (_("Could not write register \"%s\""),
3998 gdbarch_register_name (gdbarch, reg->regnum));
3999 case PACKET_UNKNOWN:
4002 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
4006 /* Store register REGNUM, or all registers if REGNUM == -1, from the
4007 contents of the register cache buffer. FIXME: ignores errors. */
4010 store_registers_using_G (const struct regcache *regcache)
4012 struct remote_state *rs = get_remote_state ();
4013 struct remote_arch_state *rsa = get_remote_arch_state ();
4017 /* Extract all the registers in the regcache copying them into a
4021 regs = alloca (rsa->sizeof_g_packet);
4022 memset (regs, 0, rsa->sizeof_g_packet);
4023 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
4025 struct packet_reg *r = &rsa->regs[i];
4027 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
4031 /* Command describes registers byte by byte,
4032 each byte encoded as two hex characters. */
4035 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
4037 bin2hex (regs, p, rsa->sizeof_g_packet);
4038 remote_send (&rs->buf, &rs->buf_size);
4041 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
4042 of the register cache buffer. FIXME: ignores errors. */
4045 remote_store_registers (struct regcache *regcache, int regnum)
4047 struct remote_state *rs = get_remote_state ();
4048 struct remote_arch_state *rsa = get_remote_arch_state ();
4051 set_general_thread (inferior_ptid);
4055 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
4056 gdb_assert (reg != NULL);
4058 /* Always prefer to store registers using the 'P' packet if
4059 possible; we often change only a small number of registers.
4060 Sometimes we change a larger number; we'd need help from a
4061 higher layer to know to use 'G'. */
4062 if (store_register_using_P (regcache, reg))
4065 /* For now, don't complain if we have no way to write the
4066 register. GDB loses track of unavailable registers too
4067 easily. Some day, this may be an error. We don't have
4068 any way to read the register, either... */
4069 if (!reg->in_g_packet)
4072 store_registers_using_G (regcache);
4076 store_registers_using_G (regcache);
4078 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
4079 if (!rsa->regs[i].in_g_packet)
4080 if (!store_register_using_P (regcache, &rsa->regs[i]))
4081 /* See above for why we do not issue an error here. */
4086 /* Return the number of hex digits in num. */
4089 hexnumlen (ULONGEST num)
4093 for (i = 0; num != 0; i++)
4099 /* Set BUF to the minimum number of hex digits representing NUM. */
4102 hexnumstr (char *buf, ULONGEST num)
4104 int len = hexnumlen (num);
4105 return hexnumnstr (buf, num, len);
4109 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
4112 hexnumnstr (char *buf, ULONGEST num, int width)
4118 for (i = width - 1; i >= 0; i--)
4120 buf[i] = "0123456789abcdef"[(num & 0xf)];
4127 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
4130 remote_address_masked (CORE_ADDR addr)
4132 int address_size = remote_address_size;
4133 /* If "remoteaddresssize" was not set, default to target address size. */
4135 address_size = gdbarch_addr_bit (current_gdbarch);
4137 if (address_size > 0
4138 && address_size < (sizeof (ULONGEST) * 8))
4140 /* Only create a mask when that mask can safely be constructed
4141 in a ULONGEST variable. */
4143 mask = (mask << address_size) - 1;
4149 /* Convert BUFFER, binary data at least LEN bytes long, into escaped
4150 binary data in OUT_BUF. Set *OUT_LEN to the length of the data
4151 encoded in OUT_BUF, and return the number of bytes in OUT_BUF
4152 (which may be more than *OUT_LEN due to escape characters). The
4153 total number of bytes in the output buffer will be at most
4157 remote_escape_output (const gdb_byte *buffer, int len,
4158 gdb_byte *out_buf, int *out_len,
4161 int input_index, output_index;
4164 for (input_index = 0; input_index < len; input_index++)
4166 gdb_byte b = buffer[input_index];
4168 if (b == '$' || b == '#' || b == '}')
4170 /* These must be escaped. */
4171 if (output_index + 2 > out_maxlen)
4173 out_buf[output_index++] = '}';
4174 out_buf[output_index++] = b ^ 0x20;
4178 if (output_index + 1 > out_maxlen)
4180 out_buf[output_index++] = b;
4184 *out_len = input_index;
4185 return output_index;
4188 /* Convert BUFFER, escaped data LEN bytes long, into binary data
4189 in OUT_BUF. Return the number of bytes written to OUT_BUF.
4190 Raise an error if the total number of bytes exceeds OUT_MAXLEN.
4192 This function reverses remote_escape_output. It allows more
4193 escaped characters than that function does, in particular because
4194 '*' must be escaped to avoid the run-length encoding processing
4195 in reading packets. */
4198 remote_unescape_input (const gdb_byte *buffer, int len,
4199 gdb_byte *out_buf, int out_maxlen)
4201 int input_index, output_index;
4206 for (input_index = 0; input_index < len; input_index++)
4208 gdb_byte b = buffer[input_index];
4210 if (output_index + 1 > out_maxlen)
4212 warning (_("Received too much data from remote target;"
4213 " ignoring overflow."));
4214 return output_index;
4219 out_buf[output_index++] = b ^ 0x20;
4225 out_buf[output_index++] = b;
4229 error (_("Unmatched escape character in target response."));
4231 return output_index;
4234 /* Determine whether the remote target supports binary downloading.
4235 This is accomplished by sending a no-op memory write of zero length
4236 to the target at the specified address. It does not suffice to send
4237 the whole packet, since many stubs strip the eighth bit and
4238 subsequently compute a wrong checksum, which causes real havoc with
4241 NOTE: This can still lose if the serial line is not eight-bit
4242 clean. In cases like this, the user should clear "remote
4246 check_binary_download (CORE_ADDR addr)
4248 struct remote_state *rs = get_remote_state ();
4250 switch (remote_protocol_packets[PACKET_X].support)
4252 case PACKET_DISABLE:
4256 case PACKET_SUPPORT_UNKNOWN:
4262 p += hexnumstr (p, (ULONGEST) addr);
4264 p += hexnumstr (p, (ULONGEST) 0);
4268 putpkt_binary (rs->buf, (int) (p - rs->buf));
4269 getpkt (&rs->buf, &rs->buf_size, 0);
4271 if (rs->buf[0] == '\0')
4274 fprintf_unfiltered (gdb_stdlog,
4275 "binary downloading NOT suppported by target\n");
4276 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
4281 fprintf_unfiltered (gdb_stdlog,
4282 "binary downloading suppported by target\n");
4283 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
4290 /* Write memory data directly to the remote machine.
4291 This does not inform the data cache; the data cache uses this.
4292 HEADER is the starting part of the packet.
4293 MEMADDR is the address in the remote memory space.
4294 MYADDR is the address of the buffer in our space.
4295 LEN is the number of bytes.
4296 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
4297 should send data as binary ('X'), or hex-encoded ('M').
4299 The function creates packet of the form
4300 <HEADER><ADDRESS>,<LENGTH>:<DATA>
4302 where encoding of <DATA> is termined by PACKET_FORMAT.
4304 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
4307 Returns the number of bytes transferred, or 0 (setting errno) for
4308 error. Only transfer a single packet. */
4311 remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
4312 const gdb_byte *myaddr, int len,
4313 char packet_format, int use_length)
4315 struct remote_state *rs = get_remote_state ();
4325 if (packet_format != 'X' && packet_format != 'M')
4326 internal_error (__FILE__, __LINE__,
4327 "remote_write_bytes_aux: bad packet format");
4332 payload_size = get_memory_write_packet_size ();
4334 /* The packet buffer will be large enough for the payload;
4335 get_memory_packet_size ensures this. */
4338 /* Compute the size of the actual payload by subtracting out the
4339 packet header and footer overhead: "$M<memaddr>,<len>:...#nn".
4341 payload_size -= strlen ("$,:#NN");
4343 /* The comma won't be used. */
4345 header_length = strlen (header);
4346 payload_size -= header_length;
4347 payload_size -= hexnumlen (memaddr);
4349 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
4351 strcat (rs->buf, header);
4352 p = rs->buf + strlen (header);
4354 /* Compute a best guess of the number of bytes actually transfered. */
4355 if (packet_format == 'X')
4357 /* Best guess at number of bytes that will fit. */
4358 todo = min (len, payload_size);
4360 payload_size -= hexnumlen (todo);
4361 todo = min (todo, payload_size);
4365 /* Num bytes that will fit. */
4366 todo = min (len, payload_size / 2);
4368 payload_size -= hexnumlen (todo);
4369 todo = min (todo, payload_size / 2);
4373 internal_error (__FILE__, __LINE__,
4374 _("minumum packet size too small to write data"));
4376 /* If we already need another packet, then try to align the end
4377 of this packet to a useful boundary. */
4378 if (todo > 2 * REMOTE_ALIGN_WRITES && todo < len)
4379 todo = ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
4381 /* Append "<memaddr>". */
4382 memaddr = remote_address_masked (memaddr);
4383 p += hexnumstr (p, (ULONGEST) memaddr);
4390 /* Append <len>. Retain the location/size of <len>. It may need to
4391 be adjusted once the packet body has been created. */
4393 plenlen = hexnumstr (p, (ULONGEST) todo);
4401 /* Append the packet body. */
4402 if (packet_format == 'X')
4404 /* Binary mode. Send target system values byte by byte, in
4405 increasing byte addresses. Only escape certain critical
4407 payload_length = remote_escape_output (myaddr, todo, p, &nr_bytes,
4410 /* If not all TODO bytes fit, then we'll need another packet. Make
4411 a second try to keep the end of the packet aligned. Don't do
4412 this if the packet is tiny. */
4413 if (nr_bytes < todo && nr_bytes > 2 * REMOTE_ALIGN_WRITES)
4417 new_nr_bytes = (((memaddr + nr_bytes) & ~(REMOTE_ALIGN_WRITES - 1))
4419 if (new_nr_bytes != nr_bytes)
4420 payload_length = remote_escape_output (myaddr, new_nr_bytes,
4425 p += payload_length;
4426 if (use_length && nr_bytes < todo)
4428 /* Escape chars have filled up the buffer prematurely,
4429 and we have actually sent fewer bytes than planned.
4430 Fix-up the length field of the packet. Use the same
4431 number of characters as before. */
4432 plen += hexnumnstr (plen, (ULONGEST) nr_bytes, plenlen);
4433 *plen = ':'; /* overwrite \0 from hexnumnstr() */
4438 /* Normal mode: Send target system values byte by byte, in
4439 increasing byte addresses. Each byte is encoded as a two hex
4441 nr_bytes = bin2hex (myaddr, p, todo);
4445 putpkt_binary (rs->buf, (int) (p - rs->buf));
4446 getpkt (&rs->buf, &rs->buf_size, 0);
4448 if (rs->buf[0] == 'E')
4450 /* There is no correspondance between what the remote protocol
4451 uses for errors and errno codes. We would like a cleaner way
4452 of representing errors (big enough to include errno codes,
4453 bfd_error codes, and others). But for now just return EIO. */
4458 /* Return NR_BYTES, not TODO, in case escape chars caused us to send
4459 fewer bytes than we'd planned. */
4463 /* Write memory data directly to the remote machine.
4464 This does not inform the data cache; the data cache uses this.
4465 MEMADDR is the address in the remote memory space.
4466 MYADDR is the address of the buffer in our space.
4467 LEN is the number of bytes.
4469 Returns number of bytes transferred, or 0 (setting errno) for
4470 error. Only transfer a single packet. */
4473 remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, int len)
4475 char *packet_format = 0;
4477 /* Check whether the target supports binary download. */
4478 check_binary_download (memaddr);
4480 switch (remote_protocol_packets[PACKET_X].support)
4483 packet_format = "X";
4485 case PACKET_DISABLE:
4486 packet_format = "M";
4488 case PACKET_SUPPORT_UNKNOWN:
4489 internal_error (__FILE__, __LINE__,
4490 _("remote_write_bytes: bad internal state"));
4492 internal_error (__FILE__, __LINE__, _("bad switch"));
4495 return remote_write_bytes_aux (packet_format,
4496 memaddr, myaddr, len, packet_format[0], 1);
4499 /* Read memory data directly from the remote machine.
4500 This does not use the data cache; the data cache uses this.
4501 MEMADDR is the address in the remote memory space.
4502 MYADDR is the address of the buffer in our space.
4503 LEN is the number of bytes.
4505 Returns number of bytes transferred, or 0 for error. */
4507 /* NOTE: cagney/1999-10-18: This function (and its siblings in other
4508 remote targets) shouldn't attempt to read the entire buffer.
4509 Instead it should read a single packet worth of data and then
4510 return the byte size of that packet to the caller. The caller (its
4511 caller and its callers caller ;-) already contains code for
4512 handling partial reads. */
4515 remote_read_bytes (CORE_ADDR memaddr, gdb_byte *myaddr, int len)
4517 struct remote_state *rs = get_remote_state ();
4518 int max_buf_size; /* Max size of packet output buffer. */
4524 max_buf_size = get_memory_read_packet_size ();
4525 /* The packet buffer will be large enough for the payload;
4526 get_memory_packet_size ensures this. */
4535 todo = min (len, max_buf_size / 2); /* num bytes that will fit */
4537 /* construct "m"<memaddr>","<len>" */
4538 /* sprintf (rs->buf, "m%lx,%x", (unsigned long) memaddr, todo); */
4539 memaddr = remote_address_masked (memaddr);
4542 p += hexnumstr (p, (ULONGEST) memaddr);
4544 p += hexnumstr (p, (ULONGEST) todo);
4548 getpkt (&rs->buf, &rs->buf_size, 0);
4550 if (rs->buf[0] == 'E'
4551 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
4552 && rs->buf[3] == '\0')
4554 /* There is no correspondance between what the remote
4555 protocol uses for errors and errno codes. We would like
4556 a cleaner way of representing errors (big enough to
4557 include errno codes, bfd_error codes, and others). But
4558 for now just return EIO. */
4563 /* Reply describes memory byte by byte,
4564 each byte encoded as two hex characters. */
4567 if ((i = hex2bin (p, myaddr, todo)) < todo)
4569 /* Reply is short. This means that we were able to read
4570 only part of what we wanted to. */
4571 return i + (origlen - len);
4580 /* Read or write LEN bytes from inferior memory at MEMADDR,
4581 transferring to or from debugger address BUFFER. Write to inferior
4582 if SHOULD_WRITE is nonzero. Returns length of data written or
4583 read; 0 for error. TARGET is unused. */
4586 remote_xfer_memory (CORE_ADDR mem_addr, gdb_byte *buffer, int mem_len,
4587 int should_write, struct mem_attrib *attrib,
4588 struct target_ops *target)
4593 res = remote_write_bytes (mem_addr, buffer, mem_len);
4595 res = remote_read_bytes (mem_addr, buffer, mem_len);
4600 /* Sends a packet with content determined by the printf format string
4601 FORMAT and the remaining arguments, then gets the reply. Returns
4602 whether the packet was a success, a failure, or unknown. */
4605 remote_send_printf (const char *format, ...)
4607 struct remote_state *rs = get_remote_state ();
4608 int max_size = get_remote_packet_size ();
4611 va_start (ap, format);
4614 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
4615 internal_error (__FILE__, __LINE__, "Too long remote packet.");
4617 if (putpkt (rs->buf) < 0)
4618 error (_("Communication problem with target."));
4621 getpkt (&rs->buf, &rs->buf_size, 0);
4623 return packet_check_result (rs->buf);
4627 restore_remote_timeout (void *p)
4629 int value = *(int *)p;
4630 remote_timeout = value;
4633 /* Flash writing can take quite some time. We'll set
4634 effectively infinite timeout for flash operations.
4635 In future, we'll need to decide on a better approach. */
4636 static const int remote_flash_timeout = 1000;
4639 remote_flash_erase (struct target_ops *ops,
4640 ULONGEST address, LONGEST length)
4642 int saved_remote_timeout = remote_timeout;
4643 enum packet_result ret;
4645 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
4646 &saved_remote_timeout);
4647 remote_timeout = remote_flash_timeout;
4649 ret = remote_send_printf ("vFlashErase:%s,%s",
4654 case PACKET_UNKNOWN:
4655 error (_("Remote target does not support flash erase"));
4657 error (_("Error erasing flash with vFlashErase packet"));
4662 do_cleanups (back_to);
4666 remote_flash_write (struct target_ops *ops,
4667 ULONGEST address, LONGEST length,
4668 const gdb_byte *data)
4670 int saved_remote_timeout = remote_timeout;
4672 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
4673 &saved_remote_timeout);
4675 remote_timeout = remote_flash_timeout;
4676 ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length, 'X', 0);
4677 do_cleanups (back_to);
4683 remote_flash_done (struct target_ops *ops)
4685 int saved_remote_timeout = remote_timeout;
4687 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
4688 &saved_remote_timeout);
4690 remote_timeout = remote_flash_timeout;
4691 ret = remote_send_printf ("vFlashDone");
4692 do_cleanups (back_to);
4696 case PACKET_UNKNOWN:
4697 error (_("Remote target does not support vFlashDone"));
4699 error (_("Error finishing flash operation"));
4706 remote_files_info (struct target_ops *ignore)
4708 puts_filtered ("Debugging a target over a serial line.\n");
4711 /* Stuff for dealing with the packets which are part of this protocol.
4712 See comment at top of file for details. */
4714 /* Read a single character from the remote end. */
4717 readchar (int timeout)
4721 ch = serial_readchar (remote_desc, timeout);
4726 switch ((enum serial_rc) ch)
4729 target_mourn_inferior ();
4730 error (_("Remote connection closed"));
4733 perror_with_name (_("Remote communication error"));
4735 case SERIAL_TIMEOUT:
4741 /* Send the command in *BUF to the remote machine, and read the reply
4742 into *BUF. Report an error if we get an error reply. Resize
4743 *BUF using xrealloc if necessary to hold the result, and update
4747 remote_send (char **buf,
4751 getpkt (buf, sizeof_buf, 0);
4753 if ((*buf)[0] == 'E')
4754 error (_("Remote failure reply: %s"), *buf);
4757 /* Display a null-terminated packet on stdout, for debugging, using C
4761 print_packet (char *buf)
4763 puts_filtered ("\"");
4764 fputstr_filtered (buf, '"', gdb_stdout);
4765 puts_filtered ("\"");
4771 return putpkt_binary (buf, strlen (buf));
4774 /* Send a packet to the remote machine, with error checking. The data
4775 of the packet is in BUF. The string in BUF can be at most
4776 get_remote_packet_size () - 5 to account for the $, # and checksum,
4777 and for a possible /0 if we are debugging (remote_debug) and want
4778 to print the sent packet as a string. */
4781 putpkt_binary (char *buf, int cnt)
4783 struct remote_state *rs = get_remote_state ();
4785 unsigned char csum = 0;
4786 char *buf2 = alloca (cnt + 6);
4792 /* We're sending out a new packet. Make sure we don't look at a
4793 stale cached response. */
4794 rs->cached_wait_status = 0;
4796 /* Copy the packet into buffer BUF2, encapsulating it
4797 and giving it a checksum. */
4802 for (i = 0; i < cnt; i++)
4808 *p++ = tohex ((csum >> 4) & 0xf);
4809 *p++ = tohex (csum & 0xf);
4811 /* Send it over and over until we get a positive ack. */
4815 int started_error_output = 0;
4820 fprintf_unfiltered (gdb_stdlog, "Sending packet: ");
4821 fputstrn_unfiltered (buf2, p - buf2, 0, gdb_stdlog);
4822 fprintf_unfiltered (gdb_stdlog, "...");
4823 gdb_flush (gdb_stdlog);
4825 if (serial_write (remote_desc, buf2, p - buf2))
4826 perror_with_name (_("putpkt: write failed"));
4828 /* If this is a no acks version of the remote protocol, send the
4829 packet and move on. */
4833 /* Read until either a timeout occurs (-2) or '+' is read. */
4836 ch = readchar (remote_timeout);
4844 case SERIAL_TIMEOUT:
4846 if (started_error_output)
4848 putchar_unfiltered ('\n');
4849 started_error_output = 0;
4858 fprintf_unfiltered (gdb_stdlog, "Ack\n");
4862 fprintf_unfiltered (gdb_stdlog, "Nak\n");
4863 case SERIAL_TIMEOUT:
4867 break; /* Retransmit buffer. */
4871 fprintf_unfiltered (gdb_stdlog,
4872 "Packet instead of Ack, ignoring it\n");
4873 /* It's probably an old response sent because an ACK
4874 was lost. Gobble up the packet and ack it so it
4875 doesn't get retransmitted when we resend this
4878 serial_write (remote_desc, "+", 1);
4879 continue; /* Now, go look for +. */
4884 if (!started_error_output)
4886 started_error_output = 1;
4887 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
4889 fputc_unfiltered (ch & 0177, gdb_stdlog);
4893 break; /* Here to retransmit. */
4897 /* This is wrong. If doing a long backtrace, the user should be
4898 able to get out next time we call QUIT, without anything as
4899 violent as interrupt_query. If we want to provide a way out of
4900 here without getting to the next QUIT, it should be based on
4901 hitting ^C twice as in remote_wait. */
4912 /* Come here after finding the start of a frame when we expected an
4913 ack. Do our best to discard the rest of this packet. */
4922 c = readchar (remote_timeout);
4925 case SERIAL_TIMEOUT:
4926 /* Nothing we can do. */
4929 /* Discard the two bytes of checksum and stop. */
4930 c = readchar (remote_timeout);
4932 c = readchar (remote_timeout);
4935 case '*': /* Run length encoding. */
4936 /* Discard the repeat count. */
4937 c = readchar (remote_timeout);
4942 /* A regular character. */
4948 /* Come here after finding the start of the frame. Collect the rest
4949 into *BUF, verifying the checksum, length, and handling run-length
4950 compression. NUL terminate the buffer. If there is not enough room,
4951 expand *BUF using xrealloc.
4953 Returns -1 on error, number of characters in buffer (ignoring the
4954 trailing NULL) on success. (could be extended to return one of the
4955 SERIAL status indications). */
4958 read_frame (char **buf_p,
4965 struct remote_state *rs = get_remote_state ();
4972 c = readchar (remote_timeout);
4975 case SERIAL_TIMEOUT:
4977 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
4981 fputs_filtered ("Saw new packet start in middle of old one\n",
4983 return -1; /* Start a new packet, count retries. */
4986 unsigned char pktcsum;
4992 check_0 = readchar (remote_timeout);
4994 check_1 = readchar (remote_timeout);
4996 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
4999 fputs_filtered ("Timeout in checksum, retrying\n",
5003 else if (check_0 < 0 || check_1 < 0)
5006 fputs_filtered ("Communication error in checksum\n",
5011 /* Don't recompute the checksum; with no ack packets we
5012 don't have any way to indicate a packet retransmission
5017 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
5018 if (csum == pktcsum)
5023 fprintf_filtered (gdb_stdlog,
5024 "Bad checksum, sentsum=0x%x, csum=0x%x, buf=",
5026 fputstrn_filtered (buf, bc, 0, gdb_stdlog);
5027 fputs_filtered ("\n", gdb_stdlog);
5029 /* Number of characters in buffer ignoring trailing
5033 case '*': /* Run length encoding. */
5038 c = readchar (remote_timeout);
5040 repeat = c - ' ' + 3; /* Compute repeat count. */
5042 /* The character before ``*'' is repeated. */
5044 if (repeat > 0 && repeat <= 255 && bc > 0)
5046 if (bc + repeat - 1 >= *sizeof_buf - 1)
5048 /* Make some more room in the buffer. */
5049 *sizeof_buf += repeat;
5050 *buf_p = xrealloc (*buf_p, *sizeof_buf);
5054 memset (&buf[bc], buf[bc - 1], repeat);
5060 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
5064 if (bc >= *sizeof_buf - 1)
5066 /* Make some more room in the buffer. */
5068 *buf_p = xrealloc (*buf_p, *sizeof_buf);
5079 /* Read a packet from the remote machine, with error checking, and
5080 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
5081 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
5082 rather than timing out; this is used (in synchronous mode) to wait
5083 for a target that is is executing user code to stop. */
5084 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
5085 don't have to change all the calls to getpkt to deal with the
5086 return value, because at the moment I don't know what the right
5087 thing to do it for those. */
5095 timed_out = getpkt_sane (buf, sizeof_buf, forever);
5099 /* Read a packet from the remote machine, with error checking, and
5100 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
5101 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
5102 rather than timing out; this is used (in synchronous mode) to wait
5103 for a target that is is executing user code to stop. If FOREVER ==
5104 0, this function is allowed to time out gracefully and return an
5105 indication of this to the caller. Otherwise return the number
5108 getpkt_sane (char **buf, long *sizeof_buf, int forever)
5110 struct remote_state *rs = get_remote_state ();
5116 /* We're reading a new response. Make sure we don't look at a
5117 previously cached response. */
5118 rs->cached_wait_status = 0;
5120 strcpy (*buf, "timeout");
5124 timeout = watchdog > 0 ? watchdog : -1;
5128 timeout = remote_timeout;
5132 for (tries = 1; tries <= MAX_TRIES; tries++)
5134 /* This can loop forever if the remote side sends us characters
5135 continuously, but if it pauses, we'll get a zero from
5136 readchar because of timeout. Then we'll count that as a
5139 /* Note that we will only wait forever prior to the start of a
5140 packet. After that, we expect characters to arrive at a
5141 brisk pace. They should show up within remote_timeout
5146 c = readchar (timeout);
5148 if (c == SERIAL_TIMEOUT)
5150 if (forever) /* Watchdog went off? Kill the target. */
5153 target_mourn_inferior ();
5154 error (_("Watchdog timeout has expired. Target detached."));
5157 fputs_filtered ("Timed out.\n", gdb_stdlog);
5163 /* We've found the start of a packet, now collect the data. */
5165 val = read_frame (buf, sizeof_buf);
5171 fprintf_unfiltered (gdb_stdlog, "Packet received: ");
5172 fputstrn_unfiltered (*buf, val, 0, gdb_stdlog);
5173 fprintf_unfiltered (gdb_stdlog, "\n");
5176 /* Skip the ack char if we're in no-ack mode. */
5177 if (!rs->noack_mode)
5178 serial_write (remote_desc, "+", 1);
5182 /* Try the whole thing again. */
5184 /* Skip the nack char if we're in no-ack mode. */
5185 if (!rs->noack_mode)
5186 serial_write (remote_desc, "-", 1);
5189 /* We have tried hard enough, and just can't receive the packet.
5192 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
5194 /* Skip the ack char if we're in no-ack mode. */
5195 if (!rs->noack_mode)
5196 serial_write (remote_desc, "+", 1);
5203 /* Unregister the file descriptor from the event loop. */
5204 if (target_is_async_p ())
5205 serial_async (remote_desc, NULL, 0);
5207 /* Use catch_errors so the user can quit from gdb even when we
5208 aren't on speaking terms with the remote system. */
5209 catch_errors ((catch_errors_ftype *) putpkt, "k", "", RETURN_MASK_ERROR);
5211 /* Don't wait for it to die. I'm not really sure it matters whether
5212 we do or not. For the existing stubs, kill is a noop. */
5213 target_mourn_inferior ();
5219 remote_mourn_1 (&remote_ops);
5222 /* Worker function for remote_mourn. */
5224 remote_mourn_1 (struct target_ops *target)
5226 unpush_target (target);
5227 generic_mourn_inferior ();
5231 extended_remote_mourn_1 (struct target_ops *target)
5233 struct remote_state *rs = get_remote_state ();
5235 /* Unlike "target remote", we do not want to unpush the target; then
5236 the next time the user says "run", we won't be connected. */
5238 /* Call common code to mark the inferior as not running. */
5239 generic_mourn_inferior ();
5241 /* Check whether the target is running now - some remote stubs
5242 automatically restart after kill. */
5244 getpkt (&rs->buf, &rs->buf_size, 0);
5246 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
5248 /* Assume that the target has been restarted. Set inferior_ptid
5249 so that bits of core GDB realizes there's something here, e.g.,
5250 so that the user can say "kill" again. */
5251 inferior_ptid = remote_current_thread (magic_null_ptid);
5252 add_thread_silent (inferior_ptid);
5256 /* Mark this (still pushed) target as not executable until we
5258 target_mark_exited (target);
5263 extended_remote_mourn (void)
5265 extended_remote_mourn_1 (&extended_remote_ops);
5269 extended_remote_run (char *args)
5271 struct remote_state *rs = get_remote_state ();
5275 /* If the user has disabled vRun support, or we have detected that
5276 support is not available, do not try it. */
5277 if (remote_protocol_packets[PACKET_vRun].support == PACKET_DISABLE)
5280 strcpy (rs->buf, "vRun;");
5281 len = strlen (rs->buf);
5283 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
5284 error (_("Remote file name too long for run packet"));
5285 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len, 0);
5289 struct cleanup *back_to;
5293 argv = buildargv (args);
5294 back_to = make_cleanup ((void (*) (void *)) freeargv, argv);
5295 for (i = 0; argv[i] != NULL; i++)
5297 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
5298 error (_("Argument list too long for run packet"));
5299 rs->buf[len++] = ';';
5300 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len, 0);
5302 do_cleanups (back_to);
5305 rs->buf[len++] = '\0';
5308 getpkt (&rs->buf, &rs->buf_size, 0);
5310 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]) == PACKET_OK)
5312 /* We have a wait response; we don't need it, though. All is well. */
5315 else if (remote_protocol_packets[PACKET_vRun].support == PACKET_DISABLE)
5316 /* It wasn't disabled before, but it is now. */
5320 if (remote_exec_file[0] == '\0')
5321 error (_("Running the default executable on the remote target failed; "
5322 "try \"set remote exec-file\"?"));
5324 error (_("Running \"%s\" on the remote target failed"),
5329 /* In the extended protocol we want to be able to do things like
5330 "run" and have them basically work as expected. So we need
5331 a special create_inferior function. We support changing the
5332 executable file and the command line arguments, but not the
5336 extended_remote_create_inferior_1 (char *exec_file, char *args,
5337 char **env, int from_tty)
5339 /* If running asynchronously, register the target file descriptor
5340 with the event loop. */
5341 if (target_can_async_p ())
5342 target_async (inferior_event_handler, 0);
5344 /* Now restart the remote server. */
5345 if (extended_remote_run (args) == -1)
5347 /* vRun was not supported. Fail if we need it to do what the
5349 if (remote_exec_file[0])
5350 error (_("Remote target does not support \"set remote exec-file\""));
5352 error (_("Remote target does not support \"set args\" or run <ARGS>"));
5354 /* Fall back to "R". */
5355 extended_remote_restart ();
5358 /* Clean up from the last time we ran, before we mark the target
5359 running again. This will mark breakpoints uninserted, and
5360 get_offsets may insert breakpoints. */
5361 init_thread_list ();
5362 init_wait_for_inferior ();
5364 /* Now mark the inferior as running before we do anything else. */
5366 inferior_ptid = magic_null_ptid;
5368 add_thread_silent (inferior_ptid);
5370 target_mark_running (&extended_remote_ops);
5372 /* Get updated offsets, if the stub uses qOffsets. */
5377 extended_remote_create_inferior (char *exec_file, char *args,
5378 char **env, int from_tty)
5380 extended_remote_create_inferior_1 (exec_file, args, env, from_tty);
5384 /* Insert a breakpoint. On targets that have software breakpoint
5385 support, we ask the remote target to do the work; on targets
5386 which don't, we insert a traditional memory breakpoint. */
5389 remote_insert_breakpoint (struct bp_target_info *bp_tgt)
5391 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
5392 If it succeeds, then set the support to PACKET_ENABLE. If it
5393 fails, and the user has explicitly requested the Z support then
5394 report an error, otherwise, mark it disabled and go on. */
5396 if (remote_protocol_packets[PACKET_Z0].support != PACKET_DISABLE)
5398 CORE_ADDR addr = bp_tgt->placed_address;
5399 struct remote_state *rs;
5403 gdbarch_breakpoint_from_pc
5404 (current_gdbarch, &addr, &bpsize);
5406 rs = get_remote_state ();
5412 addr = (ULONGEST) remote_address_masked (addr);
5413 p += hexnumstr (p, addr);
5414 sprintf (p, ",%d", bpsize);
5417 getpkt (&rs->buf, &rs->buf_size, 0);
5419 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
5424 bp_tgt->placed_address = addr;
5425 bp_tgt->placed_size = bpsize;
5427 case PACKET_UNKNOWN:
5432 return memory_insert_breakpoint (bp_tgt);
5436 remote_remove_breakpoint (struct bp_target_info *bp_tgt)
5438 CORE_ADDR addr = bp_tgt->placed_address;
5439 struct remote_state *rs = get_remote_state ();
5442 if (remote_protocol_packets[PACKET_Z0].support != PACKET_DISABLE)
5450 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
5451 p += hexnumstr (p, addr);
5452 sprintf (p, ",%d", bp_tgt->placed_size);
5455 getpkt (&rs->buf, &rs->buf_size, 0);
5457 return (rs->buf[0] == 'E');
5460 return memory_remove_breakpoint (bp_tgt);
5464 watchpoint_to_Z_packet (int type)
5469 return Z_PACKET_WRITE_WP;
5472 return Z_PACKET_READ_WP;
5475 return Z_PACKET_ACCESS_WP;
5478 internal_error (__FILE__, __LINE__,
5479 _("hw_bp_to_z: bad watchpoint type %d"), type);
5484 remote_insert_watchpoint (CORE_ADDR addr, int len, int type)
5486 struct remote_state *rs = get_remote_state ();
5488 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
5490 if (remote_protocol_packets[PACKET_Z0 + packet].support == PACKET_DISABLE)
5493 sprintf (rs->buf, "Z%x,", packet);
5494 p = strchr (rs->buf, '\0');
5495 addr = remote_address_masked (addr);
5496 p += hexnumstr (p, (ULONGEST) addr);
5497 sprintf (p, ",%x", len);
5500 getpkt (&rs->buf, &rs->buf_size, 0);
5502 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
5505 case PACKET_UNKNOWN:
5510 internal_error (__FILE__, __LINE__,
5511 _("remote_insert_watchpoint: reached end of function"));
5516 remote_remove_watchpoint (CORE_ADDR addr, int len, int type)
5518 struct remote_state *rs = get_remote_state ();
5520 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
5522 if (remote_protocol_packets[PACKET_Z0 + packet].support == PACKET_DISABLE)
5525 sprintf (rs->buf, "z%x,", packet);
5526 p = strchr (rs->buf, '\0');
5527 addr = remote_address_masked (addr);
5528 p += hexnumstr (p, (ULONGEST) addr);
5529 sprintf (p, ",%x", len);
5531 getpkt (&rs->buf, &rs->buf_size, 0);
5533 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
5536 case PACKET_UNKNOWN:
5541 internal_error (__FILE__, __LINE__,
5542 _("remote_remove_watchpoint: reached end of function"));
5546 int remote_hw_watchpoint_limit = -1;
5547 int remote_hw_breakpoint_limit = -1;
5550 remote_check_watch_resources (int type, int cnt, int ot)
5552 if (type == bp_hardware_breakpoint)
5554 if (remote_hw_breakpoint_limit == 0)
5556 else if (remote_hw_breakpoint_limit < 0)
5558 else if (cnt <= remote_hw_breakpoint_limit)
5563 if (remote_hw_watchpoint_limit == 0)
5565 else if (remote_hw_watchpoint_limit < 0)
5569 else if (cnt <= remote_hw_watchpoint_limit)
5576 remote_stopped_by_watchpoint (void)
5578 return remote_stopped_by_watchpoint_p;
5582 remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
5585 if (remote_stopped_by_watchpoint ())
5587 *addr_p = remote_watch_data_address;
5596 remote_insert_hw_breakpoint (struct bp_target_info *bp_tgt)
5599 struct remote_state *rs;
5602 /* The length field should be set to the size of a breakpoint
5603 instruction, even though we aren't inserting one ourselves. */
5605 gdbarch_breakpoint_from_pc
5606 (current_gdbarch, &bp_tgt->placed_address, &bp_tgt->placed_size);
5608 if (remote_protocol_packets[PACKET_Z1].support == PACKET_DISABLE)
5611 rs = get_remote_state ();
5618 addr = remote_address_masked (bp_tgt->placed_address);
5619 p += hexnumstr (p, (ULONGEST) addr);
5620 sprintf (p, ",%x", bp_tgt->placed_size);
5623 getpkt (&rs->buf, &rs->buf_size, 0);
5625 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
5628 case PACKET_UNKNOWN:
5633 internal_error (__FILE__, __LINE__,
5634 _("remote_insert_hw_breakpoint: reached end of function"));
5639 remote_remove_hw_breakpoint (struct bp_target_info *bp_tgt)
5642 struct remote_state *rs = get_remote_state ();
5645 if (remote_protocol_packets[PACKET_Z1].support == PACKET_DISABLE)
5652 addr = remote_address_masked (bp_tgt->placed_address);
5653 p += hexnumstr (p, (ULONGEST) addr);
5654 sprintf (p, ",%x", bp_tgt->placed_size);
5657 getpkt (&rs->buf, &rs->buf_size, 0);
5659 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
5662 case PACKET_UNKNOWN:
5667 internal_error (__FILE__, __LINE__,
5668 _("remote_remove_hw_breakpoint: reached end of function"));
5671 /* Some targets are only capable of doing downloads, and afterwards
5672 they switch to the remote serial protocol. This function provides
5673 a clean way to get from the download target to the remote target.
5674 It's basically just a wrapper so that we don't have to expose any
5675 of the internal workings of remote.c.
5677 Prior to calling this routine, you should shutdown the current
5678 target code, else you will get the "A program is being debugged
5679 already..." message. Usually a call to pop_target() suffices. */
5682 push_remote_target (char *name, int from_tty)
5684 printf_filtered (_("Switching to remote protocol\n"));
5685 remote_open (name, from_tty);
5688 /* Table used by the crc32 function to calcuate the checksum. */
5690 static unsigned long crc32_table[256] =
5693 static unsigned long
5694 crc32 (unsigned char *buf, int len, unsigned int crc)
5696 if (!crc32_table[1])
5698 /* Initialize the CRC table and the decoding table. */
5702 for (i = 0; i < 256; i++)
5704 for (c = i << 24, j = 8; j > 0; --j)
5705 c = c & 0x80000000 ? (c << 1) ^ 0x04c11db7 : (c << 1);
5712 crc = (crc << 8) ^ crc32_table[((crc >> 24) ^ *buf) & 255];
5718 /* compare-sections command
5720 With no arguments, compares each loadable section in the exec bfd
5721 with the same memory range on the target, and reports mismatches.
5722 Useful for verifying the image on the target against the exec file.
5723 Depends on the target understanding the new "qCRC:" request. */
5725 /* FIXME: cagney/1999-10-26: This command should be broken down into a
5726 target method (target verify memory) and generic version of the
5727 actual command. This will allow other high-level code (especially
5728 generic_load()) to make use of this target functionality. */
5731 compare_sections_command (char *args, int from_tty)
5733 struct remote_state *rs = get_remote_state ();
5735 unsigned long host_crc, target_crc;
5736 extern bfd *exec_bfd;
5737 struct cleanup *old_chain;
5740 const char *sectname;
5747 error (_("command cannot be used without an exec file"));
5748 if (!current_target.to_shortname ||
5749 strcmp (current_target.to_shortname, "remote") != 0)
5750 error (_("command can only be used with remote target"));
5752 for (s = exec_bfd->sections; s; s = s->next)
5754 if (!(s->flags & SEC_LOAD))
5755 continue; /* skip non-loadable section */
5757 size = bfd_get_section_size (s);
5759 continue; /* skip zero-length section */
5761 sectname = bfd_get_section_name (exec_bfd, s);
5762 if (args && strcmp (args, sectname) != 0)
5763 continue; /* not the section selected by user */
5765 matched = 1; /* do this section */
5767 /* FIXME: assumes lma can fit into long. */
5768 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
5769 (long) lma, (long) size);
5772 /* Be clever; compute the host_crc before waiting for target
5774 sectdata = xmalloc (size);
5775 old_chain = make_cleanup (xfree, sectdata);
5776 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
5777 host_crc = crc32 ((unsigned char *) sectdata, size, 0xffffffff);
5779 getpkt (&rs->buf, &rs->buf_size, 0);
5780 if (rs->buf[0] == 'E')
5781 error (_("target memory fault, section %s, range 0x%s -- 0x%s"),
5782 sectname, paddr (lma), paddr (lma + size));
5783 if (rs->buf[0] != 'C')
5784 error (_("remote target does not support this operation"));
5786 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
5787 target_crc = target_crc * 16 + fromhex (*tmp);
5789 printf_filtered ("Section %s, range 0x%s -- 0x%s: ",
5790 sectname, paddr (lma), paddr (lma + size));
5791 if (host_crc == target_crc)
5792 printf_filtered ("matched.\n");
5795 printf_filtered ("MIS-MATCHED!\n");
5799 do_cleanups (old_chain);
5802 warning (_("One or more sections of the remote executable does not match\n\
5803 the loaded file\n"));
5804 if (args && !matched)
5805 printf_filtered (_("No loaded section named '%s'.\n"), args);
5808 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
5809 into remote target. The number of bytes written to the remote
5810 target is returned, or -1 for error. */
5813 remote_write_qxfer (struct target_ops *ops, const char *object_name,
5814 const char *annex, const gdb_byte *writebuf,
5815 ULONGEST offset, LONGEST len,
5816 struct packet_config *packet)
5821 struct remote_state *rs = get_remote_state ();
5822 int max_size = get_memory_write_packet_size ();
5824 if (packet->support == PACKET_DISABLE)
5827 /* Insert header. */
5828 i = snprintf (rs->buf, max_size,
5829 "qXfer:%s:write:%s:%s:",
5830 object_name, annex ? annex : "",
5831 phex_nz (offset, sizeof offset));
5832 max_size -= (i + 1);
5834 /* Escape as much data as fits into rs->buf. */
5835 buf_len = remote_escape_output
5836 (writebuf, len, (rs->buf + i), &max_size, max_size);
5838 if (putpkt_binary (rs->buf, i + buf_len) < 0
5839 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
5840 || packet_ok (rs->buf, packet) != PACKET_OK)
5843 unpack_varlen_hex (rs->buf, &n);
5847 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
5848 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
5849 number of bytes read is returned, or 0 for EOF, or -1 for error.
5850 The number of bytes read may be less than LEN without indicating an
5851 EOF. PACKET is checked and updated to indicate whether the remote
5852 target supports this object. */
5855 remote_read_qxfer (struct target_ops *ops, const char *object_name,
5857 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
5858 struct packet_config *packet)
5860 static char *finished_object;
5861 static char *finished_annex;
5862 static ULONGEST finished_offset;
5864 struct remote_state *rs = get_remote_state ();
5865 unsigned int total = 0;
5866 LONGEST i, n, packet_len;
5868 if (packet->support == PACKET_DISABLE)
5871 /* Check whether we've cached an end-of-object packet that matches
5873 if (finished_object)
5875 if (strcmp (object_name, finished_object) == 0
5876 && strcmp (annex ? annex : "", finished_annex) == 0
5877 && offset == finished_offset)
5880 /* Otherwise, we're now reading something different. Discard
5882 xfree (finished_object);
5883 xfree (finished_annex);
5884 finished_object = NULL;
5885 finished_annex = NULL;
5888 /* Request only enough to fit in a single packet. The actual data
5889 may not, since we don't know how much of it will need to be escaped;
5890 the target is free to respond with slightly less data. We subtract
5891 five to account for the response type and the protocol frame. */
5892 n = min (get_remote_packet_size () - 5, len);
5893 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
5894 object_name, annex ? annex : "",
5895 phex_nz (offset, sizeof offset),
5896 phex_nz (n, sizeof n));
5897 i = putpkt (rs->buf);
5902 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
5903 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
5906 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
5907 error (_("Unknown remote qXfer reply: %s"), rs->buf);
5909 /* 'm' means there is (or at least might be) more data after this
5910 batch. That does not make sense unless there's at least one byte
5911 of data in this reply. */
5912 if (rs->buf[0] == 'm' && packet_len == 1)
5913 error (_("Remote qXfer reply contained no data."));
5915 /* Got some data. */
5916 i = remote_unescape_input (rs->buf + 1, packet_len - 1, readbuf, n);
5918 /* 'l' is an EOF marker, possibly including a final block of data,
5919 or possibly empty. If we have the final block of a non-empty
5920 object, record this fact to bypass a subsequent partial read. */
5921 if (rs->buf[0] == 'l' && offset + i > 0)
5923 finished_object = xstrdup (object_name);
5924 finished_annex = xstrdup (annex ? annex : "");
5925 finished_offset = offset + i;
5932 remote_xfer_partial (struct target_ops *ops, enum target_object object,
5933 const char *annex, gdb_byte *readbuf,
5934 const gdb_byte *writebuf, ULONGEST offset, LONGEST len)
5936 struct remote_state *rs = get_remote_state ();
5941 /* Handle memory using the standard memory routines. */
5942 if (object == TARGET_OBJECT_MEMORY)
5947 /* If the remote target is connected but not running, we should
5948 pass this request down to a lower stratum (e.g. the executable
5950 if (!target_has_execution)
5953 if (writebuf != NULL)
5954 xfered = remote_write_bytes (offset, writebuf, len);
5956 xfered = remote_read_bytes (offset, readbuf, len);
5960 else if (xfered == 0 && errno == 0)
5966 /* Handle SPU memory using qxfer packets. */
5967 if (object == TARGET_OBJECT_SPU)
5970 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
5971 &remote_protocol_packets
5972 [PACKET_qXfer_spu_read]);
5974 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
5975 &remote_protocol_packets
5976 [PACKET_qXfer_spu_write]);
5979 /* Only handle flash writes. */
5980 if (writebuf != NULL)
5986 case TARGET_OBJECT_FLASH:
5987 xfered = remote_flash_write (ops, offset, len, writebuf);
5991 else if (xfered == 0 && errno == 0)
6001 /* Map pre-existing objects onto letters. DO NOT do this for new
6002 objects!!! Instead specify new query packets. */
6005 case TARGET_OBJECT_AVR:
6009 case TARGET_OBJECT_AUXV:
6010 gdb_assert (annex == NULL);
6011 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
6012 &remote_protocol_packets[PACKET_qXfer_auxv]);
6014 case TARGET_OBJECT_AVAILABLE_FEATURES:
6015 return remote_read_qxfer
6016 (ops, "features", annex, readbuf, offset, len,
6017 &remote_protocol_packets[PACKET_qXfer_features]);
6019 case TARGET_OBJECT_LIBRARIES:
6020 return remote_read_qxfer
6021 (ops, "libraries", annex, readbuf, offset, len,
6022 &remote_protocol_packets[PACKET_qXfer_libraries]);
6024 case TARGET_OBJECT_MEMORY_MAP:
6025 gdb_assert (annex == NULL);
6026 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
6027 &remote_protocol_packets[PACKET_qXfer_memory_map]);
6033 /* Note: a zero OFFSET and LEN can be used to query the minimum
6035 if (offset == 0 && len == 0)
6036 return (get_remote_packet_size ());
6037 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
6038 large enough let the caller deal with it. */
6039 if (len < get_remote_packet_size ())
6041 len = get_remote_packet_size ();
6043 /* Except for querying the minimum buffer size, target must be open. */
6045 error (_("remote query is only available after target open"));
6047 gdb_assert (annex != NULL);
6048 gdb_assert (readbuf != NULL);
6054 /* We used one buffer char for the remote protocol q command and
6055 another for the query type. As the remote protocol encapsulation
6056 uses 4 chars plus one extra in case we are debugging
6057 (remote_debug), we have PBUFZIZ - 7 left to pack the query
6060 while (annex[i] && (i < (get_remote_packet_size () - 8)))
6062 /* Bad caller may have sent forbidden characters. */
6063 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
6068 gdb_assert (annex[i] == '\0');
6070 i = putpkt (rs->buf);
6074 getpkt (&rs->buf, &rs->buf_size, 0);
6075 strcpy ((char *) readbuf, rs->buf);
6077 return strlen ((char *) readbuf);
6081 remote_search_memory (struct target_ops* ops,
6082 CORE_ADDR start_addr, ULONGEST search_space_len,
6083 const gdb_byte *pattern, ULONGEST pattern_len,
6084 CORE_ADDR *found_addrp)
6086 struct remote_state *rs = get_remote_state ();
6087 int max_size = get_memory_write_packet_size ();
6088 struct packet_config *packet =
6089 &remote_protocol_packets[PACKET_qSearch_memory];
6090 /* number of packet bytes used to encode the pattern,
6091 this could be more than PATTERN_LEN due to escape characters */
6092 int escaped_pattern_len;
6093 /* amount of pattern that was encodable in the packet */
6094 int used_pattern_len;
6097 ULONGEST found_addr;
6099 /* Don't go to the target if we don't have to.
6100 This is done before checking packet->support to avoid the possibility that
6101 a success for this edge case means the facility works in general. */
6102 if (pattern_len > search_space_len)
6104 if (pattern_len == 0)
6106 *found_addrp = start_addr;
6110 /* If we already know the packet isn't supported, fall back to the simple
6111 way of searching memory. */
6113 if (packet->support == PACKET_DISABLE)
6115 /* Target doesn't provided special support, fall back and use the
6116 standard support (copy memory and do the search here). */
6117 return simple_search_memory (ops, start_addr, search_space_len,
6118 pattern, pattern_len, found_addrp);
6121 /* Insert header. */
6122 i = snprintf (rs->buf, max_size,
6123 "qSearch:memory:%s;%s;",
6124 paddr_nz (start_addr),
6125 phex_nz (search_space_len, sizeof (search_space_len)));
6126 max_size -= (i + 1);
6128 /* Escape as much data as fits into rs->buf. */
6129 escaped_pattern_len =
6130 remote_escape_output (pattern, pattern_len, (rs->buf + i),
6131 &used_pattern_len, max_size);
6133 /* Bail if the pattern is too large. */
6134 if (used_pattern_len != pattern_len)
6135 error ("Pattern is too large to transmit to remote target.");
6137 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
6138 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
6139 || packet_ok (rs->buf, packet) != PACKET_OK)
6141 /* The request may not have worked because the command is not
6142 supported. If so, fall back to the simple way. */
6143 if (packet->support == PACKET_DISABLE)
6145 return simple_search_memory (ops, start_addr, search_space_len,
6146 pattern, pattern_len, found_addrp);
6151 if (rs->buf[0] == '0')
6153 else if (rs->buf[0] == '1')
6156 if (rs->buf[1] != ',')
6157 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
6158 unpack_varlen_hex (rs->buf + 2, &found_addr);
6159 *found_addrp = found_addr;
6162 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
6168 remote_rcmd (char *command,
6169 struct ui_file *outbuf)
6171 struct remote_state *rs = get_remote_state ();
6175 error (_("remote rcmd is only available after target open"));
6177 /* Send a NULL command across as an empty command. */
6178 if (command == NULL)
6181 /* The query prefix. */
6182 strcpy (rs->buf, "qRcmd,");
6183 p = strchr (rs->buf, '\0');
6185 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/) > get_remote_packet_size ())
6186 error (_("\"monitor\" command ``%s'' is too long."), command);
6188 /* Encode the actual command. */
6189 bin2hex ((gdb_byte *) command, p, 0);
6191 if (putpkt (rs->buf) < 0)
6192 error (_("Communication problem with target."));
6194 /* get/display the response */
6199 /* XXX - see also tracepoint.c:remote_get_noisy_reply(). */
6201 getpkt (&rs->buf, &rs->buf_size, 0);
6204 error (_("Target does not support this command."));
6205 if (buf[0] == 'O' && buf[1] != 'K')
6207 remote_console_output (buf + 1); /* 'O' message from stub. */
6210 if (strcmp (buf, "OK") == 0)
6212 if (strlen (buf) == 3 && buf[0] == 'E'
6213 && isdigit (buf[1]) && isdigit (buf[2]))
6215 error (_("Protocol error with Rcmd"));
6217 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
6219 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
6220 fputc_unfiltered (c, outbuf);
6226 static VEC(mem_region_s) *
6227 remote_memory_map (struct target_ops *ops)
6229 VEC(mem_region_s) *result = NULL;
6230 char *text = target_read_stralloc (¤t_target,
6231 TARGET_OBJECT_MEMORY_MAP, NULL);
6235 struct cleanup *back_to = make_cleanup (xfree, text);
6236 result = parse_memory_map (text);
6237 do_cleanups (back_to);
6244 packet_command (char *args, int from_tty)
6246 struct remote_state *rs = get_remote_state ();
6249 error (_("command can only be used with remote target"));
6252 error (_("remote-packet command requires packet text as argument"));
6254 puts_filtered ("sending: ");
6255 print_packet (args);
6256 puts_filtered ("\n");
6259 getpkt (&rs->buf, &rs->buf_size, 0);
6260 puts_filtered ("received: ");
6261 print_packet (rs->buf);
6262 puts_filtered ("\n");
6266 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
6268 static void display_thread_info (struct gdb_ext_thread_info *info);
6270 static void threadset_test_cmd (char *cmd, int tty);
6272 static void threadalive_test (char *cmd, int tty);
6274 static void threadlist_test_cmd (char *cmd, int tty);
6276 int get_and_display_threadinfo (threadref *ref);
6278 static void threadinfo_test_cmd (char *cmd, int tty);
6280 static int thread_display_step (threadref *ref, void *context);
6282 static void threadlist_update_test_cmd (char *cmd, int tty);
6284 static void init_remote_threadtests (void);
6286 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
6289 threadset_test_cmd (char *cmd, int tty)
6291 int sample_thread = SAMPLE_THREAD;
6293 printf_filtered (_("Remote threadset test\n"));
6294 set_general_thread (sample_thread);
6299 threadalive_test (char *cmd, int tty)
6301 int sample_thread = SAMPLE_THREAD;
6302 int pid = ptid_get_pid (inferior_ptid);
6303 ptid_t ptid = ptid_build (pid, 0, sample_thread);
6305 if (remote_thread_alive (ptid))
6306 printf_filtered ("PASS: Thread alive test\n");
6308 printf_filtered ("FAIL: Thread alive test\n");
6311 void output_threadid (char *title, threadref *ref);
6314 output_threadid (char *title, threadref *ref)
6318 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
6320 printf_filtered ("%s %s\n", title, (&hexid[0]));
6324 threadlist_test_cmd (char *cmd, int tty)
6327 threadref nextthread;
6328 int done, result_count;
6329 threadref threadlist[3];
6331 printf_filtered ("Remote Threadlist test\n");
6332 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
6333 &result_count, &threadlist[0]))
6334 printf_filtered ("FAIL: threadlist test\n");
6337 threadref *scan = threadlist;
6338 threadref *limit = scan + result_count;
6340 while (scan < limit)
6341 output_threadid (" thread ", scan++);
6346 display_thread_info (struct gdb_ext_thread_info *info)
6348 output_threadid ("Threadid: ", &info->threadid);
6349 printf_filtered ("Name: %s\n ", info->shortname);
6350 printf_filtered ("State: %s\n", info->display);
6351 printf_filtered ("other: %s\n\n", info->more_display);
6355 get_and_display_threadinfo (threadref *ref)
6359 struct gdb_ext_thread_info threadinfo;
6361 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
6362 | TAG_MOREDISPLAY | TAG_DISPLAY;
6363 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
6364 display_thread_info (&threadinfo);
6369 threadinfo_test_cmd (char *cmd, int tty)
6371 int athread = SAMPLE_THREAD;
6375 int_to_threadref (&thread, athread);
6376 printf_filtered ("Remote Threadinfo test\n");
6377 if (!get_and_display_threadinfo (&thread))
6378 printf_filtered ("FAIL cannot get thread info\n");
6382 thread_display_step (threadref *ref, void *context)
6384 /* output_threadid(" threadstep ",ref); *//* simple test */
6385 return get_and_display_threadinfo (ref);
6389 threadlist_update_test_cmd (char *cmd, int tty)
6391 printf_filtered ("Remote Threadlist update test\n");
6392 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
6396 init_remote_threadtests (void)
6398 add_com ("tlist", class_obscure, threadlist_test_cmd, _("\
6399 Fetch and print the remote list of thread identifiers, one pkt only"));
6400 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
6401 _("Fetch and display info about one thread"));
6402 add_com ("tset", class_obscure, threadset_test_cmd,
6403 _("Test setting to a different thread"));
6404 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
6405 _("Iterate through updating all remote thread info"));
6406 add_com ("talive", class_obscure, threadalive_test,
6407 _(" Remote thread alive test "));
6412 /* Convert a thread ID to a string. Returns the string in a static
6416 remote_pid_to_str (ptid_t ptid)
6418 static char buf[64];
6420 if (ptid_equal (magic_null_ptid, ptid))
6422 xsnprintf (buf, sizeof buf, "Thread <main>");
6425 else if (ptid_get_tid (ptid) != 0)
6427 xsnprintf (buf, sizeof buf, "Thread %ld",
6428 ptid_get_tid (ptid));
6432 return normal_pid_to_str (ptid);
6435 /* Get the address of the thread local variable in OBJFILE which is
6436 stored at OFFSET within the thread local storage for thread PTID. */
6439 remote_get_thread_local_address (ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
6441 if (remote_protocol_packets[PACKET_qGetTLSAddr].support != PACKET_DISABLE)
6443 struct remote_state *rs = get_remote_state ();
6445 enum packet_result result;
6447 strcpy (p, "qGetTLSAddr:");
6449 p += hexnumstr (p, ptid_get_tid (ptid));
6451 p += hexnumstr (p, offset);
6453 p += hexnumstr (p, lm);
6457 getpkt (&rs->buf, &rs->buf_size, 0);
6458 result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_qGetTLSAddr]);
6459 if (result == PACKET_OK)
6463 unpack_varlen_hex (rs->buf, &result);
6466 else if (result == PACKET_UNKNOWN)
6467 throw_error (TLS_GENERIC_ERROR,
6468 _("Remote target doesn't support qGetTLSAddr packet"));
6470 throw_error (TLS_GENERIC_ERROR,
6471 _("Remote target failed to process qGetTLSAddr request"));
6474 throw_error (TLS_GENERIC_ERROR,
6475 _("TLS not supported or disabled on this target"));
6480 /* Support for inferring a target description based on the current
6481 architecture and the size of a 'g' packet. While the 'g' packet
6482 can have any size (since optional registers can be left off the
6483 end), some sizes are easily recognizable given knowledge of the
6484 approximate architecture. */
6486 struct remote_g_packet_guess
6489 const struct target_desc *tdesc;
6491 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
6492 DEF_VEC_O(remote_g_packet_guess_s);
6494 struct remote_g_packet_data
6496 VEC(remote_g_packet_guess_s) *guesses;
6499 static struct gdbarch_data *remote_g_packet_data_handle;
6502 remote_g_packet_data_init (struct obstack *obstack)
6504 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
6508 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
6509 const struct target_desc *tdesc)
6511 struct remote_g_packet_data *data
6512 = gdbarch_data (gdbarch, remote_g_packet_data_handle);
6513 struct remote_g_packet_guess new_guess, *guess;
6516 gdb_assert (tdesc != NULL);
6519 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
6521 if (guess->bytes == bytes)
6522 internal_error (__FILE__, __LINE__,
6523 "Duplicate g packet description added for size %d",
6526 new_guess.bytes = bytes;
6527 new_guess.tdesc = tdesc;
6528 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
6531 static const struct target_desc *
6532 remote_read_description (struct target_ops *target)
6534 struct remote_g_packet_data *data
6535 = gdbarch_data (current_gdbarch, remote_g_packet_data_handle);
6537 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
6539 struct remote_g_packet_guess *guess;
6541 int bytes = send_g_packet ();
6544 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
6546 if (guess->bytes == bytes)
6547 return guess->tdesc;
6549 /* We discard the g packet. A minor optimization would be to
6550 hold on to it, and fill the register cache once we have selected
6551 an architecture, but it's too tricky to do safely. */
6557 /* Remote file transfer support. This is host-initiated I/O, not
6558 target-initiated; for target-initiated, see remote-fileio.c. */
6560 /* If *LEFT is at least the length of STRING, copy STRING to
6561 *BUFFER, update *BUFFER to point to the new end of the buffer, and
6562 decrease *LEFT. Otherwise raise an error. */
6565 remote_buffer_add_string (char **buffer, int *left, char *string)
6567 int len = strlen (string);
6570 error (_("Packet too long for target."));
6572 memcpy (*buffer, string, len);
6576 /* NUL-terminate the buffer as a convenience, if there is
6582 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
6583 *BUFFER, update *BUFFER to point to the new end of the buffer, and
6584 decrease *LEFT. Otherwise raise an error. */
6587 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
6590 if (2 * len > *left)
6591 error (_("Packet too long for target."));
6593 bin2hex (bytes, *buffer, len);
6597 /* NUL-terminate the buffer as a convenience, if there is
6603 /* If *LEFT is large enough, convert VALUE to hex and add it to
6604 *BUFFER, update *BUFFER to point to the new end of the buffer, and
6605 decrease *LEFT. Otherwise raise an error. */
6608 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
6610 int len = hexnumlen (value);
6613 error (_("Packet too long for target."));
6615 hexnumstr (*buffer, value);
6619 /* NUL-terminate the buffer as a convenience, if there is
6625 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
6626 value, *REMOTE_ERRNO to the remote error number or zero if none
6627 was included, and *ATTACHMENT to point to the start of the annex
6628 if any. The length of the packet isn't needed here; there may
6629 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
6631 Return 0 if the packet could be parsed, -1 if it could not. If
6632 -1 is returned, the other variables may not be initialized. */
6635 remote_hostio_parse_result (char *buffer, int *retcode,
6636 int *remote_errno, char **attachment)
6643 if (buffer[0] != 'F')
6647 *retcode = strtol (&buffer[1], &p, 16);
6648 if (errno != 0 || p == &buffer[1])
6651 /* Check for ",errno". */
6655 *remote_errno = strtol (p + 1, &p2, 16);
6656 if (errno != 0 || p + 1 == p2)
6661 /* Check for ";attachment". If there is no attachment, the
6662 packet should end here. */
6665 *attachment = p + 1;
6668 else if (*p == '\0')
6674 /* Send a prepared I/O packet to the target and read its response.
6675 The prepared packet is in the global RS->BUF before this function
6676 is called, and the answer is there when we return.
6678 COMMAND_BYTES is the length of the request to send, which may include
6679 binary data. WHICH_PACKET is the packet configuration to check
6680 before attempting a packet. If an error occurs, *REMOTE_ERRNO
6681 is set to the error number and -1 is returned. Otherwise the value
6682 returned by the function is returned.
6684 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
6685 attachment is expected; an error will be reported if there's a
6686 mismatch. If one is found, *ATTACHMENT will be set to point into
6687 the packet buffer and *ATTACHMENT_LEN will be set to the
6688 attachment's length. */
6691 remote_hostio_send_command (int command_bytes, int which_packet,
6692 int *remote_errno, char **attachment,
6693 int *attachment_len)
6695 struct remote_state *rs = get_remote_state ();
6696 int ret, bytes_read;
6697 char *attachment_tmp;
6699 if (remote_protocol_packets[which_packet].support == PACKET_DISABLE)
6701 *remote_errno = FILEIO_ENOSYS;
6705 putpkt_binary (rs->buf, command_bytes);
6706 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
6708 /* If it timed out, something is wrong. Don't try to parse the
6712 *remote_errno = FILEIO_EINVAL;
6716 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
6719 *remote_errno = FILEIO_EINVAL;
6721 case PACKET_UNKNOWN:
6722 *remote_errno = FILEIO_ENOSYS;
6728 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
6731 *remote_errno = FILEIO_EINVAL;
6735 /* Make sure we saw an attachment if and only if we expected one. */
6736 if ((attachment_tmp == NULL && attachment != NULL)
6737 || (attachment_tmp != NULL && attachment == NULL))
6739 *remote_errno = FILEIO_EINVAL;
6743 /* If an attachment was found, it must point into the packet buffer;
6744 work out how many bytes there were. */
6745 if (attachment_tmp != NULL)
6747 *attachment = attachment_tmp;
6748 *attachment_len = bytes_read - (*attachment - rs->buf);
6754 /* Open FILENAME on the remote target, using FLAGS and MODE. Return a
6755 remote file descriptor, or -1 if an error occurs (and set
6759 remote_hostio_open (const char *filename, int flags, int mode,
6762 struct remote_state *rs = get_remote_state ();
6764 int left = get_remote_packet_size () - 1;
6766 remote_buffer_add_string (&p, &left, "vFile:open:");
6768 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
6770 remote_buffer_add_string (&p, &left, ",");
6772 remote_buffer_add_int (&p, &left, flags);
6773 remote_buffer_add_string (&p, &left, ",");
6775 remote_buffer_add_int (&p, &left, mode);
6777 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
6778 remote_errno, NULL, NULL);
6781 /* Write up to LEN bytes from WRITE_BUF to FD on the remote target.
6782 Return the number of bytes written, or -1 if an error occurs (and
6783 set *REMOTE_ERRNO). */
6786 remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
6787 ULONGEST offset, int *remote_errno)
6789 struct remote_state *rs = get_remote_state ();
6791 int left = get_remote_packet_size ();
6794 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
6796 remote_buffer_add_int (&p, &left, fd);
6797 remote_buffer_add_string (&p, &left, ",");
6799 remote_buffer_add_int (&p, &left, offset);
6800 remote_buffer_add_string (&p, &left, ",");
6802 p += remote_escape_output (write_buf, len, p, &out_len,
6803 get_remote_packet_size () - (p - rs->buf));
6805 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
6806 remote_errno, NULL, NULL);
6809 /* Read up to LEN bytes FD on the remote target into READ_BUF
6810 Return the number of bytes read, or -1 if an error occurs (and
6811 set *REMOTE_ERRNO). */
6814 remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
6815 ULONGEST offset, int *remote_errno)
6817 struct remote_state *rs = get_remote_state ();
6820 int left = get_remote_packet_size ();
6821 int ret, attachment_len;
6824 remote_buffer_add_string (&p, &left, "vFile:pread:");
6826 remote_buffer_add_int (&p, &left, fd);
6827 remote_buffer_add_string (&p, &left, ",");
6829 remote_buffer_add_int (&p, &left, len);
6830 remote_buffer_add_string (&p, &left, ",");
6832 remote_buffer_add_int (&p, &left, offset);
6834 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
6835 remote_errno, &attachment,
6841 read_len = remote_unescape_input (attachment, attachment_len,
6843 if (read_len != ret)
6844 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
6849 /* Close FD on the remote target. Return 0, or -1 if an error occurs
6850 (and set *REMOTE_ERRNO). */
6853 remote_hostio_close (int fd, int *remote_errno)
6855 struct remote_state *rs = get_remote_state ();
6857 int left = get_remote_packet_size () - 1;
6859 remote_buffer_add_string (&p, &left, "vFile:close:");
6861 remote_buffer_add_int (&p, &left, fd);
6863 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
6864 remote_errno, NULL, NULL);
6867 /* Unlink FILENAME on the remote target. Return 0, or -1 if an error
6868 occurs (and set *REMOTE_ERRNO). */
6871 remote_hostio_unlink (const char *filename, int *remote_errno)
6873 struct remote_state *rs = get_remote_state ();
6875 int left = get_remote_packet_size () - 1;
6877 remote_buffer_add_string (&p, &left, "vFile:unlink:");
6879 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
6882 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
6883 remote_errno, NULL, NULL);
6887 remote_fileio_errno_to_host (int errnum)
6911 case FILEIO_ENOTDIR:
6931 case FILEIO_ENAMETOOLONG:
6932 return ENAMETOOLONG;
6938 remote_hostio_error (int errnum)
6940 int host_error = remote_fileio_errno_to_host (errnum);
6942 if (host_error == -1)
6943 error (_("Unknown remote I/O error %d"), errnum);
6945 error (_("Remote I/O error: %s"), safe_strerror (host_error));
6949 fclose_cleanup (void *file)
6955 remote_hostio_close_cleanup (void *opaque)
6957 int fd = *(int *) opaque;
6960 remote_hostio_close (fd, &remote_errno);
6964 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
6966 struct cleanup *back_to, *close_cleanup;
6967 int retcode, fd, remote_errno, bytes, io_size;
6970 int bytes_in_buffer;
6975 error (_("command can only be used with remote target"));
6977 file = fopen (local_file, "rb");
6979 perror_with_name (local_file);
6980 back_to = make_cleanup (fclose_cleanup, file);
6982 fd = remote_hostio_open (remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
6984 0700, &remote_errno);
6986 remote_hostio_error (remote_errno);
6988 /* Send up to this many bytes at once. They won't all fit in the
6989 remote packet limit, so we'll transfer slightly fewer. */
6990 io_size = get_remote_packet_size ();
6991 buffer = xmalloc (io_size);
6992 make_cleanup (xfree, buffer);
6994 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
6996 bytes_in_buffer = 0;
6999 while (bytes_in_buffer || !saw_eof)
7003 bytes = fread (buffer + bytes_in_buffer, 1, io_size - bytes_in_buffer,
7008 error (_("Error reading %s."), local_file);
7011 /* EOF. Unless there is something still in the
7012 buffer from the last iteration, we are done. */
7014 if (bytes_in_buffer == 0)
7022 bytes += bytes_in_buffer;
7023 bytes_in_buffer = 0;
7025 retcode = remote_hostio_pwrite (fd, buffer, bytes, offset, &remote_errno);
7028 remote_hostio_error (remote_errno);
7029 else if (retcode == 0)
7030 error (_("Remote write of %d bytes returned 0!"), bytes);
7031 else if (retcode < bytes)
7033 /* Short write. Save the rest of the read data for the next
7035 bytes_in_buffer = bytes - retcode;
7036 memmove (buffer, buffer + retcode, bytes_in_buffer);
7042 discard_cleanups (close_cleanup);
7043 if (remote_hostio_close (fd, &remote_errno))
7044 remote_hostio_error (remote_errno);
7047 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
7048 do_cleanups (back_to);
7052 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
7054 struct cleanup *back_to, *close_cleanup;
7055 int retcode, fd, remote_errno, bytes, io_size;
7061 error (_("command can only be used with remote target"));
7063 fd = remote_hostio_open (remote_file, FILEIO_O_RDONLY, 0, &remote_errno);
7065 remote_hostio_error (remote_errno);
7067 file = fopen (local_file, "wb");
7069 perror_with_name (local_file);
7070 back_to = make_cleanup (fclose_cleanup, file);
7072 /* Send up to this many bytes at once. They won't all fit in the
7073 remote packet limit, so we'll transfer slightly fewer. */
7074 io_size = get_remote_packet_size ();
7075 buffer = xmalloc (io_size);
7076 make_cleanup (xfree, buffer);
7078 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
7083 bytes = remote_hostio_pread (fd, buffer, io_size, offset, &remote_errno);
7085 /* Success, but no bytes, means end-of-file. */
7088 remote_hostio_error (remote_errno);
7092 bytes = fwrite (buffer, 1, bytes, file);
7094 perror_with_name (local_file);
7097 discard_cleanups (close_cleanup);
7098 if (remote_hostio_close (fd, &remote_errno))
7099 remote_hostio_error (remote_errno);
7102 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
7103 do_cleanups (back_to);
7107 remote_file_delete (const char *remote_file, int from_tty)
7109 int retcode, remote_errno;
7112 error (_("command can only be used with remote target"));
7114 retcode = remote_hostio_unlink (remote_file, &remote_errno);
7116 remote_hostio_error (remote_errno);
7119 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
7123 remote_put_command (char *args, int from_tty)
7125 struct cleanup *back_to;
7128 argv = buildargv (args);
7131 back_to = make_cleanup_freeargv (argv);
7132 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
7133 error (_("Invalid parameters to remote put"));
7135 remote_file_put (argv[0], argv[1], from_tty);
7137 do_cleanups (back_to);
7141 remote_get_command (char *args, int from_tty)
7143 struct cleanup *back_to;
7146 argv = buildargv (args);
7149 back_to = make_cleanup_freeargv (argv);
7150 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
7151 error (_("Invalid parameters to remote get"));
7153 remote_file_get (argv[0], argv[1], from_tty);
7155 do_cleanups (back_to);
7159 remote_delete_command (char *args, int from_tty)
7161 struct cleanup *back_to;
7164 argv = buildargv (args);
7167 back_to = make_cleanup_freeargv (argv);
7168 if (argv[0] == NULL || argv[1] != NULL)
7169 error (_("Invalid parameters to remote delete"));
7171 remote_file_delete (argv[0], from_tty);
7173 do_cleanups (back_to);
7177 remote_command (char *args, int from_tty)
7179 help_list (remote_cmdlist, "remote ", -1, gdb_stdout);
7183 init_remote_ops (void)
7185 remote_ops.to_shortname = "remote";
7186 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
7188 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
7189 Specify the serial device it is connected to\n\
7190 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
7191 remote_ops.to_open = remote_open;
7192 remote_ops.to_close = remote_close;
7193 remote_ops.to_detach = remote_detach;
7194 remote_ops.to_disconnect = remote_disconnect;
7195 remote_ops.to_resume = remote_resume;
7196 remote_ops.to_wait = remote_wait;
7197 remote_ops.to_fetch_registers = remote_fetch_registers;
7198 remote_ops.to_store_registers = remote_store_registers;
7199 remote_ops.to_prepare_to_store = remote_prepare_to_store;
7200 remote_ops.deprecated_xfer_memory = remote_xfer_memory;
7201 remote_ops.to_files_info = remote_files_info;
7202 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
7203 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
7204 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
7205 remote_ops.to_stopped_data_address = remote_stopped_data_address;
7206 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
7207 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
7208 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
7209 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
7210 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
7211 remote_ops.to_kill = remote_kill;
7212 remote_ops.to_load = generic_load;
7213 remote_ops.to_mourn_inferior = remote_mourn;
7214 remote_ops.to_thread_alive = remote_thread_alive;
7215 remote_ops.to_find_new_threads = remote_threads_info;
7216 remote_ops.to_pid_to_str = remote_pid_to_str;
7217 remote_ops.to_extra_thread_info = remote_threads_extra_info;
7218 remote_ops.to_stop = remote_stop;
7219 remote_ops.to_xfer_partial = remote_xfer_partial;
7220 remote_ops.to_rcmd = remote_rcmd;
7221 remote_ops.to_log_command = serial_log_command;
7222 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
7223 remote_ops.to_stratum = process_stratum;
7224 remote_ops.to_has_all_memory = 1;
7225 remote_ops.to_has_memory = 1;
7226 remote_ops.to_has_stack = 1;
7227 remote_ops.to_has_registers = 1;
7228 remote_ops.to_has_execution = 1;
7229 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
7230 remote_ops.to_magic = OPS_MAGIC;
7231 remote_ops.to_memory_map = remote_memory_map;
7232 remote_ops.to_flash_erase = remote_flash_erase;
7233 remote_ops.to_flash_done = remote_flash_done;
7234 remote_ops.to_read_description = remote_read_description;
7235 remote_ops.to_search_memory = remote_search_memory;
7236 remote_ops.to_can_async_p = remote_can_async_p;
7237 remote_ops.to_is_async_p = remote_is_async_p;
7238 remote_ops.to_async = remote_async;
7239 remote_ops.to_async_mask = remote_async_mask;
7240 remote_ops.to_terminal_inferior = remote_terminal_inferior;
7241 remote_ops.to_terminal_ours = remote_terminal_ours;
7244 /* Set up the extended remote vector by making a copy of the standard
7245 remote vector and adding to it. */
7248 init_extended_remote_ops (void)
7250 extended_remote_ops = remote_ops;
7252 extended_remote_ops.to_shortname = "extended-remote";
7253 extended_remote_ops.to_longname =
7254 "Extended remote serial target in gdb-specific protocol";
7255 extended_remote_ops.to_doc =
7256 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
7257 Specify the serial device it is connected to (e.g. /dev/ttya).";
7258 extended_remote_ops.to_open = extended_remote_open;
7259 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
7260 extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
7261 extended_remote_ops.to_detach = extended_remote_detach;
7262 extended_remote_ops.to_attach = extended_remote_attach;
7266 remote_can_async_p (void)
7268 if (!remote_async_permitted)
7269 /* We only enable async when the user specifically asks for it. */
7272 /* We're async whenever the serial device is. */
7273 return remote_async_mask_value && serial_can_async_p (remote_desc);
7277 remote_is_async_p (void)
7279 if (!remote_async_permitted)
7280 /* We only enable async when the user specifically asks for it. */
7283 /* We're async whenever the serial device is. */
7284 return remote_async_mask_value && serial_is_async_p (remote_desc);
7287 /* Pass the SERIAL event on and up to the client. One day this code
7288 will be able to delay notifying the client of an event until the
7289 point where an entire packet has been received. */
7291 static void (*async_client_callback) (enum inferior_event_type event_type,
7293 static void *async_client_context;
7294 static serial_event_ftype remote_async_serial_handler;
7297 remote_async_serial_handler (struct serial *scb, void *context)
7299 /* Don't propogate error information up to the client. Instead let
7300 the client find out about the error by querying the target. */
7301 async_client_callback (INF_REG_EVENT, async_client_context);
7305 remote_async (void (*callback) (enum inferior_event_type event_type,
7306 void *context), void *context)
7308 if (remote_async_mask_value == 0)
7309 internal_error (__FILE__, __LINE__,
7310 _("Calling remote_async when async is masked"));
7312 if (callback != NULL)
7314 serial_async (remote_desc, remote_async_serial_handler, NULL);
7315 async_client_callback = callback;
7316 async_client_context = context;
7319 serial_async (remote_desc, NULL, NULL);
7323 remote_async_mask (int new_mask)
7325 int curr_mask = remote_async_mask_value;
7326 remote_async_mask_value = new_mask;
7331 set_remote_cmd (char *args, int from_tty)
7333 help_list (remote_set_cmdlist, "set remote ", -1, gdb_stdout);
7337 show_remote_cmd (char *args, int from_tty)
7339 /* We can't just use cmd_show_list here, because we want to skip
7340 the redundant "show remote Z-packet" and the legacy aliases. */
7341 struct cleanup *showlist_chain;
7342 struct cmd_list_element *list = remote_show_cmdlist;
7344 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
7345 for (; list != NULL; list = list->next)
7346 if (strcmp (list->name, "Z-packet") == 0)
7348 else if (list->type == not_set_cmd)
7349 /* Alias commands are exactly like the original, except they
7350 don't have the normal type. */
7354 struct cleanup *option_chain
7355 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
7356 ui_out_field_string (uiout, "name", list->name);
7357 ui_out_text (uiout, ": ");
7358 if (list->type == show_cmd)
7359 do_setshow_command ((char *) NULL, from_tty, list);
7361 cmd_func (list, NULL, from_tty);
7362 /* Close the tuple. */
7363 do_cleanups (option_chain);
7366 /* Close the tuple. */
7367 do_cleanups (showlist_chain);
7371 /* Function to be called whenever a new objfile (shlib) is detected. */
7373 remote_new_objfile (struct objfile *objfile)
7375 if (remote_desc != 0) /* Have a remote connection. */
7376 remote_check_symbols (objfile);
7380 _initialize_remote (void)
7382 struct remote_state *rs;
7384 /* architecture specific data */
7385 remote_gdbarch_data_handle =
7386 gdbarch_data_register_post_init (init_remote_state);
7387 remote_g_packet_data_handle =
7388 gdbarch_data_register_pre_init (remote_g_packet_data_init);
7390 /* Initialize the per-target state. At the moment there is only one
7391 of these, not one per target. Only one target is active at a
7392 time. The default buffer size is unimportant; it will be expanded
7393 whenever a larger buffer is needed. */
7394 rs = get_remote_state_raw ();
7396 rs->buf = xmalloc (rs->buf_size);
7399 add_target (&remote_ops);
7401 init_extended_remote_ops ();
7402 add_target (&extended_remote_ops);
7404 /* Hook into new objfile notification. */
7405 observer_attach_new_objfile (remote_new_objfile);
7407 /* Set up signal handlers. */
7408 sigint_remote_token =
7409 create_async_signal_handler (async_remote_interrupt, NULL);
7410 sigint_remote_twice_token =
7411 create_async_signal_handler (inferior_event_handler_wrapper, NULL);
7414 init_remote_threadtests ();
7417 /* set/show remote ... */
7419 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
7420 Remote protocol specific variables\n\
7421 Configure various remote-protocol specific variables such as\n\
7422 the packets being used"),
7423 &remote_set_cmdlist, "set remote ",
7424 0 /* allow-unknown */, &setlist);
7425 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
7426 Remote protocol specific variables\n\
7427 Configure various remote-protocol specific variables such as\n\
7428 the packets being used"),
7429 &remote_show_cmdlist, "show remote ",
7430 0 /* allow-unknown */, &showlist);
7432 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
7433 Compare section data on target to the exec file.\n\
7434 Argument is a single section name (default: all loaded sections)."),
7437 add_cmd ("packet", class_maintenance, packet_command, _("\
7438 Send an arbitrary packet to a remote target.\n\
7439 maintenance packet TEXT\n\
7440 If GDB is talking to an inferior via the GDB serial protocol, then\n\
7441 this command sends the string TEXT to the inferior, and displays the\n\
7442 response packet. GDB supplies the initial `$' character, and the\n\
7443 terminating `#' character and checksum."),
7446 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
7447 Set whether to send break if interrupted."), _("\
7448 Show whether to send break if interrupted."), _("\
7449 If set, a break, instead of a cntrl-c, is sent to the remote target."),
7450 NULL, NULL, /* FIXME: i18n: Whether to send break if interrupted is %s. */
7451 &setlist, &showlist);
7453 /* Install commands for configuring memory read/write packets. */
7455 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
7456 Set the maximum number of bytes per memory write packet (deprecated)."),
7458 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
7459 Show the maximum number of bytes per memory write packet (deprecated)."),
7461 add_cmd ("memory-write-packet-size", no_class,
7462 set_memory_write_packet_size, _("\
7463 Set the maximum number of bytes per memory-write packet.\n\
7464 Specify the number of bytes in a packet or 0 (zero) for the\n\
7465 default packet size. The actual limit is further reduced\n\
7466 dependent on the target. Specify ``fixed'' to disable the\n\
7467 further restriction and ``limit'' to enable that restriction."),
7468 &remote_set_cmdlist);
7469 add_cmd ("memory-read-packet-size", no_class,
7470 set_memory_read_packet_size, _("\
7471 Set the maximum number of bytes per memory-read packet.\n\
7472 Specify the number of bytes in a packet or 0 (zero) for the\n\
7473 default packet size. The actual limit is further reduced\n\
7474 dependent on the target. Specify ``fixed'' to disable the\n\
7475 further restriction and ``limit'' to enable that restriction."),
7476 &remote_set_cmdlist);
7477 add_cmd ("memory-write-packet-size", no_class,
7478 show_memory_write_packet_size,
7479 _("Show the maximum number of bytes per memory-write packet."),
7480 &remote_show_cmdlist);
7481 add_cmd ("memory-read-packet-size", no_class,
7482 show_memory_read_packet_size,
7483 _("Show the maximum number of bytes per memory-read packet."),
7484 &remote_show_cmdlist);
7486 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
7487 &remote_hw_watchpoint_limit, _("\
7488 Set the maximum number of target hardware watchpoints."), _("\
7489 Show the maximum number of target hardware watchpoints."), _("\
7490 Specify a negative limit for unlimited."),
7491 NULL, NULL, /* FIXME: i18n: The maximum number of target hardware watchpoints is %s. */
7492 &remote_set_cmdlist, &remote_show_cmdlist);
7493 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
7494 &remote_hw_breakpoint_limit, _("\
7495 Set the maximum number of target hardware breakpoints."), _("\
7496 Show the maximum number of target hardware breakpoints."), _("\
7497 Specify a negative limit for unlimited."),
7498 NULL, NULL, /* FIXME: i18n: The maximum number of target hardware breakpoints is %s. */
7499 &remote_set_cmdlist, &remote_show_cmdlist);
7501 add_setshow_integer_cmd ("remoteaddresssize", class_obscure,
7502 &remote_address_size, _("\
7503 Set the maximum size of the address (in bits) in a memory packet."), _("\
7504 Show the maximum size of the address (in bits) in a memory packet."), NULL,
7506 NULL, /* FIXME: i18n: */
7507 &setlist, &showlist);
7509 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
7510 "X", "binary-download", 1);
7512 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
7513 "vCont", "verbose-resume", 0);
7515 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
7516 "QPassSignals", "pass-signals", 0);
7518 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
7519 "qSymbol", "symbol-lookup", 0);
7521 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
7522 "P", "set-register", 1);
7524 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
7525 "p", "fetch-register", 1);
7527 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
7528 "Z0", "software-breakpoint", 0);
7530 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
7531 "Z1", "hardware-breakpoint", 0);
7533 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
7534 "Z2", "write-watchpoint", 0);
7536 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
7537 "Z3", "read-watchpoint", 0);
7539 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
7540 "Z4", "access-watchpoint", 0);
7542 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
7543 "qXfer:auxv:read", "read-aux-vector", 0);
7545 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
7546 "qXfer:features:read", "target-features", 0);
7548 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
7549 "qXfer:libraries:read", "library-info", 0);
7551 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
7552 "qXfer:memory-map:read", "memory-map", 0);
7554 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
7555 "qXfer:spu:read", "read-spu-object", 0);
7557 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
7558 "qXfer:spu:write", "write-spu-object", 0);
7560 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
7561 "qGetTLSAddr", "get-thread-local-storage-address",
7564 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
7565 "qSupported", "supported-packets", 0);
7567 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
7568 "qSearch:memory", "search-memory", 0);
7570 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
7571 "vFile:open", "hostio-open", 0);
7573 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
7574 "vFile:pread", "hostio-pread", 0);
7576 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
7577 "vFile:pwrite", "hostio-pwrite", 0);
7579 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
7580 "vFile:close", "hostio-close", 0);
7582 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
7583 "vFile:unlink", "hostio-unlink", 0);
7585 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
7586 "vAttach", "attach", 0);
7588 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
7591 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
7592 "QStartNoAckMode", "noack", 0);
7594 /* Keep the old ``set remote Z-packet ...'' working. Each individual
7595 Z sub-packet has its own set and show commands, but users may
7596 have sets to this variable in their .gdbinit files (or in their
7598 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
7599 &remote_Z_packet_detect, _("\
7600 Set use of remote protocol `Z' packets"), _("\
7601 Show use of remote protocol `Z' packets "), _("\
7602 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
7604 set_remote_protocol_Z_packet_cmd,
7605 show_remote_protocol_Z_packet_cmd, /* FIXME: i18n: Use of remote protocol `Z' packets is %s. */
7606 &remote_set_cmdlist, &remote_show_cmdlist);
7608 add_prefix_cmd ("remote", class_files, remote_command, _("\
7609 Manipulate files on the remote system\n\
7610 Transfer files to and from the remote target system."),
7611 &remote_cmdlist, "remote ",
7612 0 /* allow-unknown */, &cmdlist);
7614 add_cmd ("put", class_files, remote_put_command,
7615 _("Copy a local file to the remote system."),
7618 add_cmd ("get", class_files, remote_get_command,
7619 _("Copy a remote file to the local system."),
7622 add_cmd ("delete", class_files, remote_delete_command,
7623 _("Delete a remote file."),
7626 remote_exec_file = xstrdup ("");
7627 add_setshow_string_noescape_cmd ("exec-file", class_files,
7628 &remote_exec_file, _("\
7629 Set the remote pathname for \"run\""), _("\
7630 Show the remote pathname for \"run\""), NULL, NULL, NULL,
7631 &remote_set_cmdlist, &remote_show_cmdlist);
7633 add_setshow_boolean_cmd ("remote-async", class_maintenance,
7634 &remote_async_permitted_set, _("\
7635 Set whether gdb controls the remote inferior in asynchronous mode."), _("\
7636 Show whether gdb controls the remote inferior in asynchronous mode."), _("\
7637 Tells gdb whether to control the remote inferior in asynchronous mode."),
7638 set_maintenance_remote_async_permitted,
7639 show_maintenance_remote_async_permitted,
7640 &maintenance_set_cmdlist,
7641 &maintenance_show_cmdlist);
7644 /* Eventually initialize fileio. See fileio.c */
7645 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
7647 /* Take advantage of the fact that the LWP field is not used, to tag
7648 special ptids with it set to != 0. */
7649 magic_null_ptid = ptid_build (0, 1, -1);
7650 not_sent_ptid = ptid_build (0, 1, -2);
7651 any_thread_ptid = ptid_build (0, 1, 0);