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);
214 static struct cmd_list_element *remote_cmdlist;
216 /* For "set remote" and "show remote". */
218 static struct cmd_list_element *remote_set_cmdlist;
219 static struct cmd_list_element *remote_show_cmdlist;
221 /* Description of the remote protocol state for the currently
222 connected target. This is per-target state, and independent of the
223 selected architecture. */
227 /* A buffer to use for incoming packets, and its current size. The
228 buffer is grown dynamically for larger incoming packets.
229 Outgoing packets may also be constructed in this buffer.
230 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
231 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
236 /* If we negotiated packet size explicitly (and thus can bypass
237 heuristics for the largest packet size that will not overflow
238 a buffer in the stub), this will be set to that packet size.
239 Otherwise zero, meaning to use the guessed size. */
240 long explicit_packet_size;
242 /* remote_wait is normally called when the target is running and
243 waits for a stop reply packet. But sometimes we need to call it
244 when the target is already stopped. We can send a "?" packet
245 and have remote_wait read the response. Or, if we already have
246 the response, we can stash it in BUF and tell remote_wait to
247 skip calling getpkt. This flag is set when BUF contains a
248 stop reply packet and the target is not waiting. */
249 int cached_wait_status;
251 /* True, if in no ack mode. That is, neither GDB nor the stub will
252 expect acks from each other. The connection is assumed to be
257 /* This data could be associated with a target, but we do not always
258 have access to the current target when we need it, so for now it is
259 static. This will be fine for as long as only one target is in use
261 static struct remote_state remote_state;
263 static struct remote_state *
264 get_remote_state_raw (void)
266 return &remote_state;
269 /* Description of the remote protocol for a given architecture. */
273 long offset; /* Offset into G packet. */
274 long regnum; /* GDB's internal register number. */
275 LONGEST pnum; /* Remote protocol register number. */
276 int in_g_packet; /* Always part of G packet. */
277 /* long size in bytes; == register_size (target_gdbarch, regnum);
279 /* char *name; == gdbarch_register_name (target_gdbarch, regnum);
283 struct remote_arch_state
285 /* Description of the remote protocol registers. */
286 long sizeof_g_packet;
288 /* Description of the remote protocol registers indexed by REGNUM
289 (making an array gdbarch_num_regs in size). */
290 struct packet_reg *regs;
292 /* This is the size (in chars) of the first response to the ``g''
293 packet. It is used as a heuristic when determining the maximum
294 size of memory-read and memory-write packets. A target will
295 typically only reserve a buffer large enough to hold the ``g''
296 packet. The size does not include packet overhead (headers and
298 long actual_register_packet_size;
300 /* This is the maximum size (in chars) of a non read/write packet.
301 It is also used as a cap on the size of read/write packets. */
302 long remote_packet_size;
306 /* Handle for retreving the remote protocol data from gdbarch. */
307 static struct gdbarch_data *remote_gdbarch_data_handle;
309 static struct remote_arch_state *
310 get_remote_arch_state (void)
312 return gdbarch_data (target_gdbarch, remote_gdbarch_data_handle);
315 /* Fetch the global remote target state. */
317 static struct remote_state *
318 get_remote_state (void)
320 /* Make sure that the remote architecture state has been
321 initialized, because doing so might reallocate rs->buf. Any
322 function which calls getpkt also needs to be mindful of changes
323 to rs->buf, but this call limits the number of places which run
325 get_remote_arch_state ();
327 return get_remote_state_raw ();
331 compare_pnums (const void *lhs_, const void *rhs_)
333 const struct packet_reg * const *lhs = lhs_;
334 const struct packet_reg * const *rhs = rhs_;
336 if ((*lhs)->pnum < (*rhs)->pnum)
338 else if ((*lhs)->pnum == (*rhs)->pnum)
345 init_remote_state (struct gdbarch *gdbarch)
347 int regnum, num_remote_regs, offset;
348 struct remote_state *rs = get_remote_state_raw ();
349 struct remote_arch_state *rsa;
350 struct packet_reg **remote_regs;
352 rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
354 /* Use the architecture to build a regnum<->pnum table, which will be
355 1:1 unless a feature set specifies otherwise. */
356 rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
357 gdbarch_num_regs (gdbarch),
359 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
361 struct packet_reg *r = &rsa->regs[regnum];
363 if (register_size (gdbarch, regnum) == 0)
364 /* Do not try to fetch zero-sized (placeholder) registers. */
367 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
372 /* Define the g/G packet format as the contents of each register
373 with a remote protocol number, in order of ascending protocol
376 remote_regs = alloca (gdbarch_num_regs (gdbarch)
377 * sizeof (struct packet_reg *));
378 for (num_remote_regs = 0, regnum = 0;
379 regnum < gdbarch_num_regs (gdbarch);
381 if (rsa->regs[regnum].pnum != -1)
382 remote_regs[num_remote_regs++] = &rsa->regs[regnum];
384 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
387 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
389 remote_regs[regnum]->in_g_packet = 1;
390 remote_regs[regnum]->offset = offset;
391 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
394 /* Record the maximum possible size of the g packet - it may turn out
396 rsa->sizeof_g_packet = offset;
398 /* Default maximum number of characters in a packet body. Many
399 remote stubs have a hardwired buffer size of 400 bytes
400 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
401 as the maximum packet-size to ensure that the packet and an extra
402 NUL character can always fit in the buffer. This stops GDB
403 trashing stubs that try to squeeze an extra NUL into what is
404 already a full buffer (As of 1999-12-04 that was most stubs). */
405 rsa->remote_packet_size = 400 - 1;
407 /* This one is filled in when a ``g'' packet is received. */
408 rsa->actual_register_packet_size = 0;
410 /* Should rsa->sizeof_g_packet needs more space than the
411 default, adjust the size accordingly. Remember that each byte is
412 encoded as two characters. 32 is the overhead for the packet
413 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
414 (``$NN:G...#NN'') is a better guess, the below has been padded a
416 if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
417 rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
419 /* Make sure that the packet buffer is plenty big enough for
420 this architecture. */
421 if (rs->buf_size < rsa->remote_packet_size)
423 rs->buf_size = 2 * rsa->remote_packet_size;
424 rs->buf = xrealloc (rs->buf, rs->buf_size);
430 /* Return the current allowed size of a remote packet. This is
431 inferred from the current architecture, and should be used to
432 limit the length of outgoing packets. */
434 get_remote_packet_size (void)
436 struct remote_state *rs = get_remote_state ();
437 struct remote_arch_state *rsa = get_remote_arch_state ();
439 if (rs->explicit_packet_size)
440 return rs->explicit_packet_size;
442 return rsa->remote_packet_size;
445 static struct packet_reg *
446 packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
448 if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch))
452 struct packet_reg *r = &rsa->regs[regnum];
453 gdb_assert (r->regnum == regnum);
458 static struct packet_reg *
459 packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
462 for (i = 0; i < gdbarch_num_regs (target_gdbarch); i++)
464 struct packet_reg *r = &rsa->regs[i];
471 /* FIXME: graces/2002-08-08: These variables should eventually be
472 bound to an instance of the target object (as in gdbarch-tdep()),
473 when such a thing exists. */
475 /* This is set to the data address of the access causing the target
476 to stop for a watchpoint. */
477 static CORE_ADDR remote_watch_data_address;
479 /* This is non-zero if target stopped for a watchpoint. */
480 static int remote_stopped_by_watchpoint_p;
482 static struct target_ops remote_ops;
484 static struct target_ops extended_remote_ops;
486 static int remote_async_mask_value = 1;
488 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
489 ``forever'' still use the normal timeout mechanism. This is
490 currently used by the ASYNC code to guarentee that target reads
491 during the initial connect always time-out. Once getpkt has been
492 modified to return a timeout indication and, in turn
493 remote_wait()/wait_for_inferior() have gained a timeout parameter
495 static int wait_forever_enabled_p = 1;
498 /* This variable chooses whether to send a ^C or a break when the user
499 requests program interruption. Although ^C is usually what remote
500 systems expect, and that is the default here, sometimes a break is
501 preferable instead. */
503 static int remote_break;
505 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
506 remote_open knows that we don't have a file open when the program
508 static struct serial *remote_desc = NULL;
510 /* This variable sets the number of bits in an address that are to be
511 sent in a memory ("M" or "m") packet. Normally, after stripping
512 leading zeros, the entire address would be sent. This variable
513 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
514 initial implementation of remote.c restricted the address sent in
515 memory packets to ``host::sizeof long'' bytes - (typically 32
516 bits). Consequently, for 64 bit targets, the upper 32 bits of an
517 address was never sent. Since fixing this bug may cause a break in
518 some remote targets this variable is principly provided to
519 facilitate backward compatibility. */
521 static int remote_address_size;
523 /* Temporary to track who currently owns the terminal. See
524 remote_terminal_* for more details. */
526 static int remote_async_terminal_ours_p;
528 /* The executable file to use for "run" on the remote side. */
530 static char *remote_exec_file = "";
533 /* User configurable variables for the number of characters in a
534 memory read/write packet. MIN (rsa->remote_packet_size,
535 rsa->sizeof_g_packet) is the default. Some targets need smaller
536 values (fifo overruns, et.al.) and some users need larger values
537 (speed up transfers). The variables ``preferred_*'' (the user
538 request), ``current_*'' (what was actually set) and ``forced_*''
539 (Positive - a soft limit, negative - a hard limit). */
541 struct memory_packet_config
548 /* Compute the current size of a read/write packet. Since this makes
549 use of ``actual_register_packet_size'' the computation is dynamic. */
552 get_memory_packet_size (struct memory_packet_config *config)
554 struct remote_state *rs = get_remote_state ();
555 struct remote_arch_state *rsa = get_remote_arch_state ();
557 /* NOTE: The somewhat arbitrary 16k comes from the knowledge (folk
558 law?) that some hosts don't cope very well with large alloca()
559 calls. Eventually the alloca() code will be replaced by calls to
560 xmalloc() and make_cleanups() allowing this restriction to either
561 be lifted or removed. */
562 #ifndef MAX_REMOTE_PACKET_SIZE
563 #define MAX_REMOTE_PACKET_SIZE 16384
565 /* NOTE: 20 ensures we can write at least one byte. */
566 #ifndef MIN_REMOTE_PACKET_SIZE
567 #define MIN_REMOTE_PACKET_SIZE 20
572 if (config->size <= 0)
573 what_they_get = MAX_REMOTE_PACKET_SIZE;
575 what_they_get = config->size;
579 what_they_get = get_remote_packet_size ();
580 /* Limit the packet to the size specified by the user. */
582 && what_they_get > config->size)
583 what_they_get = config->size;
585 /* Limit it to the size of the targets ``g'' response unless we have
586 permission from the stub to use a larger packet size. */
587 if (rs->explicit_packet_size == 0
588 && rsa->actual_register_packet_size > 0
589 && what_they_get > rsa->actual_register_packet_size)
590 what_they_get = rsa->actual_register_packet_size;
592 if (what_they_get > MAX_REMOTE_PACKET_SIZE)
593 what_they_get = MAX_REMOTE_PACKET_SIZE;
594 if (what_they_get < MIN_REMOTE_PACKET_SIZE)
595 what_they_get = MIN_REMOTE_PACKET_SIZE;
597 /* Make sure there is room in the global buffer for this packet
598 (including its trailing NUL byte). */
599 if (rs->buf_size < what_they_get + 1)
601 rs->buf_size = 2 * what_they_get;
602 rs->buf = xrealloc (rs->buf, 2 * what_they_get);
605 return what_they_get;
608 /* Update the size of a read/write packet. If they user wants
609 something really big then do a sanity check. */
612 set_memory_packet_size (char *args, struct memory_packet_config *config)
614 int fixed_p = config->fixed_p;
615 long size = config->size;
617 error (_("Argument required (integer, `fixed' or `limited')."));
618 else if (strcmp (args, "hard") == 0
619 || strcmp (args, "fixed") == 0)
621 else if (strcmp (args, "soft") == 0
622 || strcmp (args, "limit") == 0)
627 size = strtoul (args, &end, 0);
629 error (_("Invalid %s (bad syntax)."), config->name);
631 /* Instead of explicitly capping the size of a packet to
632 MAX_REMOTE_PACKET_SIZE or dissallowing it, the user is
633 instead allowed to set the size to something arbitrarily
635 if (size > MAX_REMOTE_PACKET_SIZE)
636 error (_("Invalid %s (too large)."), config->name);
640 if (fixed_p && !config->fixed_p)
642 if (! query (_("The target may not be able to correctly handle a %s\n"
643 "of %ld bytes. Change the packet size? "),
645 error (_("Packet size not changed."));
647 /* Update the config. */
648 config->fixed_p = fixed_p;
653 show_memory_packet_size (struct memory_packet_config *config)
655 printf_filtered (_("The %s is %ld. "), config->name, config->size);
657 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
658 get_memory_packet_size (config));
660 printf_filtered (_("Packets are limited to %ld bytes.\n"),
661 get_memory_packet_size (config));
664 static struct memory_packet_config memory_write_packet_config =
666 "memory-write-packet-size",
670 set_memory_write_packet_size (char *args, int from_tty)
672 set_memory_packet_size (args, &memory_write_packet_config);
676 show_memory_write_packet_size (char *args, int from_tty)
678 show_memory_packet_size (&memory_write_packet_config);
682 get_memory_write_packet_size (void)
684 return get_memory_packet_size (&memory_write_packet_config);
687 static struct memory_packet_config memory_read_packet_config =
689 "memory-read-packet-size",
693 set_memory_read_packet_size (char *args, int from_tty)
695 set_memory_packet_size (args, &memory_read_packet_config);
699 show_memory_read_packet_size (char *args, int from_tty)
701 show_memory_packet_size (&memory_read_packet_config);
705 get_memory_read_packet_size (void)
707 long size = get_memory_packet_size (&memory_read_packet_config);
708 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
709 extra buffer size argument before the memory read size can be
710 increased beyond this. */
711 if (size > get_remote_packet_size ())
712 size = get_remote_packet_size ();
717 /* Generic configuration support for packets the stub optionally
718 supports. Allows the user to specify the use of the packet as well
719 as allowing GDB to auto-detect support in the remote stub. */
723 PACKET_SUPPORT_UNKNOWN = 0,
732 enum auto_boolean detect;
733 enum packet_support support;
736 /* Analyze a packet's return value and update the packet config
747 update_packet_config (struct packet_config *config)
749 switch (config->detect)
751 case AUTO_BOOLEAN_TRUE:
752 config->support = PACKET_ENABLE;
754 case AUTO_BOOLEAN_FALSE:
755 config->support = PACKET_DISABLE;
757 case AUTO_BOOLEAN_AUTO:
758 config->support = PACKET_SUPPORT_UNKNOWN;
764 show_packet_config_cmd (struct packet_config *config)
766 char *support = "internal-error";
767 switch (config->support)
773 support = "disabled";
775 case PACKET_SUPPORT_UNKNOWN:
779 switch (config->detect)
781 case AUTO_BOOLEAN_AUTO:
782 printf_filtered (_("Support for the `%s' packet is auto-detected, currently %s.\n"),
783 config->name, support);
785 case AUTO_BOOLEAN_TRUE:
786 case AUTO_BOOLEAN_FALSE:
787 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
788 config->name, support);
794 add_packet_config_cmd (struct packet_config *config, const char *name,
795 const char *title, int legacy)
802 config->title = title;
803 config->detect = AUTO_BOOLEAN_AUTO;
804 config->support = PACKET_SUPPORT_UNKNOWN;
805 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
807 show_doc = xstrprintf ("Show current use of remote protocol `%s' (%s) packet",
809 /* set/show TITLE-packet {auto,on,off} */
810 cmd_name = xstrprintf ("%s-packet", title);
811 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
812 &config->detect, set_doc, show_doc, NULL, /* help_doc */
813 set_remote_protocol_packet_cmd,
814 show_remote_protocol_packet_cmd,
815 &remote_set_cmdlist, &remote_show_cmdlist);
816 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
820 legacy_name = xstrprintf ("%s-packet", name);
821 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
822 &remote_set_cmdlist);
823 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
824 &remote_show_cmdlist);
828 static enum packet_result
829 packet_check_result (const char *buf)
833 /* The stub recognized the packet request. Check that the
834 operation succeeded. */
836 && isxdigit (buf[1]) && isxdigit (buf[2])
838 /* "Enn" - definitly an error. */
841 /* Always treat "E." as an error. This will be used for
842 more verbose error messages, such as E.memtypes. */
843 if (buf[0] == 'E' && buf[1] == '.')
846 /* The packet may or may not be OK. Just assume it is. */
850 /* The stub does not support the packet. */
851 return PACKET_UNKNOWN;
854 static enum packet_result
855 packet_ok (const char *buf, struct packet_config *config)
857 enum packet_result result;
859 result = packet_check_result (buf);
864 /* The stub recognized the packet request. */
865 switch (config->support)
867 case PACKET_SUPPORT_UNKNOWN:
869 fprintf_unfiltered (gdb_stdlog,
870 "Packet %s (%s) is supported\n",
871 config->name, config->title);
872 config->support = PACKET_ENABLE;
875 internal_error (__FILE__, __LINE__,
876 _("packet_ok: attempt to use a disabled packet"));
883 /* The stub does not support the packet. */
884 switch (config->support)
887 if (config->detect == AUTO_BOOLEAN_AUTO)
888 /* If the stub previously indicated that the packet was
889 supported then there is a protocol error.. */
890 error (_("Protocol error: %s (%s) conflicting enabled responses."),
891 config->name, config->title);
893 /* The user set it wrong. */
894 error (_("Enabled packet %s (%s) not recognized by stub"),
895 config->name, config->title);
897 case PACKET_SUPPORT_UNKNOWN:
899 fprintf_unfiltered (gdb_stdlog,
900 "Packet %s (%s) is NOT supported\n",
901 config->name, config->title);
902 config->support = PACKET_DISABLE;
930 PACKET_qXfer_features,
931 PACKET_qXfer_libraries,
932 PACKET_qXfer_memory_map,
933 PACKET_qXfer_spu_read,
934 PACKET_qXfer_spu_write,
938 PACKET_qSearch_memory,
941 PACKET_QStartNoAckMode,
945 static struct packet_config remote_protocol_packets[PACKET_MAX];
948 set_remote_protocol_packet_cmd (char *args, int from_tty,
949 struct cmd_list_element *c)
951 struct packet_config *packet;
953 for (packet = remote_protocol_packets;
954 packet < &remote_protocol_packets[PACKET_MAX];
957 if (&packet->detect == c->var)
959 update_packet_config (packet);
963 internal_error (__FILE__, __LINE__, "Could not find config for %s",
968 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
969 struct cmd_list_element *c,
972 struct packet_config *packet;
974 for (packet = remote_protocol_packets;
975 packet < &remote_protocol_packets[PACKET_MAX];
978 if (&packet->detect == c->var)
980 show_packet_config_cmd (packet);
984 internal_error (__FILE__, __LINE__, "Could not find config for %s",
988 /* Should we try one of the 'Z' requests? */
992 Z_PACKET_SOFTWARE_BP,
993 Z_PACKET_HARDWARE_BP,
1000 /* For compatibility with older distributions. Provide a ``set remote
1001 Z-packet ...'' command that updates all the Z packet types. */
1003 static enum auto_boolean remote_Z_packet_detect;
1006 set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1007 struct cmd_list_element *c)
1010 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1012 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
1013 update_packet_config (&remote_protocol_packets[PACKET_Z0 + i]);
1018 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1019 struct cmd_list_element *c,
1023 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1025 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
1029 /* Should we try the 'ThreadInfo' query packet?
1031 This variable (NOT available to the user: auto-detect only!)
1032 determines whether GDB will use the new, simpler "ThreadInfo"
1033 query or the older, more complex syntax for thread queries.
1034 This is an auto-detect variable (set to true at each connect,
1035 and set to false when the target fails to recognize it). */
1037 static int use_threadinfo_query;
1038 static int use_threadextra_query;
1040 /* Tokens for use by the asynchronous signal handlers for SIGINT. */
1041 static struct async_signal_handler *sigint_remote_twice_token;
1042 static struct async_signal_handler *sigint_remote_token;
1046 static ptid_t magic_null_ptid;
1047 static ptid_t not_sent_ptid;
1048 static ptid_t any_thread_ptid;
1050 /* These are the threads which we last sent to the remote system. The
1051 TID member will be -1 for all or -2 for not sent yet. */
1053 static ptid_t general_thread;
1054 static ptid_t continue_thread;
1057 /* Call this function as a result of
1058 1) A halt indication (T packet) containing a thread id
1059 2) A direct query of currthread
1060 3) Successful execution of set thread
1064 record_currthread (ptid_t currthread)
1066 general_thread = currthread;
1068 /* If this is a new thread, add it to GDB's thread list.
1069 If we leave it up to WFI to do this, bad things will happen. */
1070 if (!in_thread_list (currthread))
1072 if (ptid_equal (pid_to_ptid (ptid_get_pid (currthread)), inferior_ptid))
1074 /* inferior_ptid has no thread member yet. This can happen
1075 with the vAttach -> remote_wait,"TAAthread:" path if the
1076 stub doesn't support qC. This is the first stop reported
1077 after an attach, so this is the main thread. Update the
1078 ptid in the thread list. */
1079 struct thread_info *th = find_thread_pid (inferior_ptid);
1080 inferior_ptid = th->ptid = currthread;
1082 else if (ptid_equal (magic_null_ptid, inferior_ptid))
1084 /* inferior_ptid is not set yet. This can happen with the
1085 vRun -> remote_wait,"TAAthread:" path if the stub
1086 doesn't support qC. This is the first stop reported
1087 after an attach, so this is the main thread. Update the
1088 ptid in the thread list. */
1089 struct thread_info *th = find_thread_pid (inferior_ptid);
1090 inferior_ptid = th->ptid = currthread;
1093 /* This is really a new thread. Add it. */
1094 add_thread (currthread);
1098 static char *last_pass_packet;
1100 /* If 'QPassSignals' is supported, tell the remote stub what signals
1101 it can simply pass through to the inferior without reporting. */
1104 remote_pass_signals (void)
1106 if (remote_protocol_packets[PACKET_QPassSignals].support != PACKET_DISABLE)
1108 char *pass_packet, *p;
1109 int numsigs = (int) TARGET_SIGNAL_LAST;
1112 gdb_assert (numsigs < 256);
1113 for (i = 0; i < numsigs; i++)
1115 if (signal_stop_state (i) == 0
1116 && signal_print_state (i) == 0
1117 && signal_pass_state (i) == 1)
1120 pass_packet = xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
1121 strcpy (pass_packet, "QPassSignals:");
1122 p = pass_packet + strlen (pass_packet);
1123 for (i = 0; i < numsigs; i++)
1125 if (signal_stop_state (i) == 0
1126 && signal_print_state (i) == 0
1127 && signal_pass_state (i) == 1)
1130 *p++ = tohex (i >> 4);
1131 *p++ = tohex (i & 15);
1140 if (!last_pass_packet || strcmp (last_pass_packet, pass_packet))
1142 struct remote_state *rs = get_remote_state ();
1143 char *buf = rs->buf;
1145 putpkt (pass_packet);
1146 getpkt (&rs->buf, &rs->buf_size, 0);
1147 packet_ok (buf, &remote_protocol_packets[PACKET_QPassSignals]);
1148 if (last_pass_packet)
1149 xfree (last_pass_packet);
1150 last_pass_packet = pass_packet;
1153 xfree (pass_packet);
1157 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
1158 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
1159 thread. If GEN is set, set the general thread, if not, then set
1160 the step/continue thread. */
1162 set_thread (struct ptid ptid, int gen)
1164 struct remote_state *rs = get_remote_state ();
1165 ptid_t state = gen ? general_thread : continue_thread;
1166 char *buf = rs->buf;
1167 char *endbuf = rs->buf + get_remote_packet_size ();
1169 if (ptid_equal (state, ptid))
1173 *buf++ = gen ? 'g' : 'c';
1174 if (ptid_equal (ptid, magic_null_ptid))
1175 xsnprintf (buf, endbuf - buf, "0");
1176 else if (ptid_equal (ptid, any_thread_ptid))
1177 xsnprintf (buf, endbuf - buf, "0");
1178 else if (ptid_equal (ptid, minus_one_ptid))
1179 xsnprintf (buf, endbuf - buf, "-1");
1182 int tid = ptid_get_tid (ptid);
1184 xsnprintf (buf, endbuf - buf, "-%x", -tid);
1186 xsnprintf (buf, endbuf - buf, "%x", tid);
1189 getpkt (&rs->buf, &rs->buf_size, 0);
1191 general_thread = ptid;
1193 continue_thread = ptid;
1197 set_general_thread (struct ptid ptid)
1199 set_thread (ptid, 1);
1203 set_continue_thread (struct ptid ptid)
1205 set_thread (ptid, 0);
1209 /* Return nonzero if the thread PTID is still alive on the remote
1213 remote_thread_alive (ptid_t ptid)
1215 struct remote_state *rs = get_remote_state ();
1216 int tid = ptid_get_tid (ptid);
1218 if (ptid_equal (ptid, magic_null_ptid))
1219 /* The main thread is always alive. */
1222 if (ptid_get_pid (ptid) != 0 && ptid_get_tid (ptid) == 0)
1223 /* The main thread is always alive. This can happen after a
1224 vAttach, if the remote side doesn't support
1229 xsnprintf (rs->buf, get_remote_packet_size (), "T-%08x", -tid);
1231 xsnprintf (rs->buf, get_remote_packet_size (), "T%08x", tid);
1233 getpkt (&rs->buf, &rs->buf_size, 0);
1234 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
1237 /* About these extended threadlist and threadinfo packets. They are
1238 variable length packets but, the fields within them are often fixed
1239 length. They are redundent enough to send over UDP as is the
1240 remote protocol in general. There is a matching unit test module
1243 #define OPAQUETHREADBYTES 8
1245 /* a 64 bit opaque identifier */
1246 typedef unsigned char threadref[OPAQUETHREADBYTES];
1248 /* WARNING: This threadref data structure comes from the remote O.S.,
1249 libstub protocol encoding, and remote.c. it is not particularly
1252 /* Right now, the internal structure is int. We want it to be bigger.
1256 typedef int gdb_threadref; /* Internal GDB thread reference. */
1258 /* gdb_ext_thread_info is an internal GDB data structure which is
1259 equivalent to the reply of the remote threadinfo packet. */
1261 struct gdb_ext_thread_info
1263 threadref threadid; /* External form of thread reference. */
1264 int active; /* Has state interesting to GDB?
1266 char display[256]; /* Brief state display, name,
1267 blocked/suspended. */
1268 char shortname[32]; /* To be used to name threads. */
1269 char more_display[256]; /* Long info, statistics, queue depth,
1273 /* The volume of remote transfers can be limited by submitting
1274 a mask containing bits specifying the desired information.
1275 Use a union of these values as the 'selection' parameter to
1276 get_thread_info. FIXME: Make these TAG names more thread specific.
1279 #define TAG_THREADID 1
1280 #define TAG_EXISTS 2
1281 #define TAG_DISPLAY 4
1282 #define TAG_THREADNAME 8
1283 #define TAG_MOREDISPLAY 16
1285 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
1287 char *unpack_varlen_hex (char *buff, ULONGEST *result);
1289 static char *unpack_nibble (char *buf, int *val);
1291 static char *pack_nibble (char *buf, int nibble);
1293 static char *pack_hex_byte (char *pkt, int /* unsigned char */ byte);
1295 static char *unpack_byte (char *buf, int *value);
1297 static char *pack_int (char *buf, int value);
1299 static char *unpack_int (char *buf, int *value);
1301 static char *unpack_string (char *src, char *dest, int length);
1303 static char *pack_threadid (char *pkt, threadref *id);
1305 static char *unpack_threadid (char *inbuf, threadref *id);
1307 void int_to_threadref (threadref *id, int value);
1309 static int threadref_to_int (threadref *ref);
1311 static void copy_threadref (threadref *dest, threadref *src);
1313 static int threadmatch (threadref *dest, threadref *src);
1315 static char *pack_threadinfo_request (char *pkt, int mode,
1318 static int remote_unpack_thread_info_response (char *pkt,
1319 threadref *expectedref,
1320 struct gdb_ext_thread_info
1324 static int remote_get_threadinfo (threadref *threadid,
1325 int fieldset, /*TAG mask */
1326 struct gdb_ext_thread_info *info);
1328 static char *pack_threadlist_request (char *pkt, int startflag,
1330 threadref *nextthread);
1332 static int parse_threadlist_response (char *pkt,
1334 threadref *original_echo,
1335 threadref *resultlist,
1338 static int remote_get_threadlist (int startflag,
1339 threadref *nextthread,
1343 threadref *threadlist);
1345 typedef int (*rmt_thread_action) (threadref *ref, void *context);
1347 static int remote_threadlist_iterator (rmt_thread_action stepfunction,
1348 void *context, int looplimit);
1350 static int remote_newthread_step (threadref *ref, void *context);
1352 /* Encode 64 bits in 16 chars of hex. */
1354 static const char hexchars[] = "0123456789abcdef";
1357 ishex (int ch, int *val)
1359 if ((ch >= 'a') && (ch <= 'f'))
1361 *val = ch - 'a' + 10;
1364 if ((ch >= 'A') && (ch <= 'F'))
1366 *val = ch - 'A' + 10;
1369 if ((ch >= '0') && (ch <= '9'))
1380 if (ch >= 'a' && ch <= 'f')
1381 return ch - 'a' + 10;
1382 if (ch >= '0' && ch <= '9')
1384 if (ch >= 'A' && ch <= 'F')
1385 return ch - 'A' + 10;
1390 stub_unpack_int (char *buff, int fieldlength)
1397 nibble = stubhex (*buff++);
1401 retval = retval << 4;
1407 unpack_varlen_hex (char *buff, /* packet to parse */
1411 ULONGEST retval = 0;
1413 while (ishex (*buff, &nibble))
1416 retval = retval << 4;
1417 retval |= nibble & 0x0f;
1424 unpack_nibble (char *buf, int *val)
1426 *val = fromhex (*buf++);
1431 pack_nibble (char *buf, int nibble)
1433 *buf++ = hexchars[(nibble & 0x0f)];
1438 pack_hex_byte (char *pkt, int byte)
1440 *pkt++ = hexchars[(byte >> 4) & 0xf];
1441 *pkt++ = hexchars[(byte & 0xf)];
1446 unpack_byte (char *buf, int *value)
1448 *value = stub_unpack_int (buf, 2);
1453 pack_int (char *buf, int value)
1455 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
1456 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
1457 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
1458 buf = pack_hex_byte (buf, (value & 0xff));
1463 unpack_int (char *buf, int *value)
1465 *value = stub_unpack_int (buf, 8);
1469 #if 0 /* Currently unused, uncomment when needed. */
1470 static char *pack_string (char *pkt, char *string);
1473 pack_string (char *pkt, char *string)
1478 len = strlen (string);
1480 len = 200; /* Bigger than most GDB packets, junk??? */
1481 pkt = pack_hex_byte (pkt, len);
1485 if ((ch == '\0') || (ch == '#'))
1486 ch = '*'; /* Protect encapsulation. */
1491 #endif /* 0 (unused) */
1494 unpack_string (char *src, char *dest, int length)
1503 pack_threadid (char *pkt, threadref *id)
1506 unsigned char *altid;
1508 altid = (unsigned char *) id;
1509 limit = pkt + BUF_THREAD_ID_SIZE;
1511 pkt = pack_hex_byte (pkt, *altid++);
1517 unpack_threadid (char *inbuf, threadref *id)
1520 char *limit = inbuf + BUF_THREAD_ID_SIZE;
1523 altref = (char *) id;
1525 while (inbuf < limit)
1527 x = stubhex (*inbuf++);
1528 y = stubhex (*inbuf++);
1529 *altref++ = (x << 4) | y;
1534 /* Externally, threadrefs are 64 bits but internally, they are still
1535 ints. This is due to a mismatch of specifications. We would like
1536 to use 64bit thread references internally. This is an adapter
1540 int_to_threadref (threadref *id, int value)
1542 unsigned char *scan;
1544 scan = (unsigned char *) id;
1550 *scan++ = (value >> 24) & 0xff;
1551 *scan++ = (value >> 16) & 0xff;
1552 *scan++ = (value >> 8) & 0xff;
1553 *scan++ = (value & 0xff);
1557 threadref_to_int (threadref *ref)
1560 unsigned char *scan;
1566 value = (value << 8) | ((*scan++) & 0xff);
1571 copy_threadref (threadref *dest, threadref *src)
1574 unsigned char *csrc, *cdest;
1576 csrc = (unsigned char *) src;
1577 cdest = (unsigned char *) dest;
1584 threadmatch (threadref *dest, threadref *src)
1586 /* Things are broken right now, so just assume we got a match. */
1588 unsigned char *srcp, *destp;
1590 srcp = (char *) src;
1591 destp = (char *) dest;
1595 result &= (*srcp++ == *destp++) ? 1 : 0;
1602 threadid:1, # always request threadid
1609 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
1612 pack_threadinfo_request (char *pkt, int mode, threadref *id)
1614 *pkt++ = 'q'; /* Info Query */
1615 *pkt++ = 'P'; /* process or thread info */
1616 pkt = pack_int (pkt, mode); /* mode */
1617 pkt = pack_threadid (pkt, id); /* threadid */
1618 *pkt = '\0'; /* terminate */
1622 /* These values tag the fields in a thread info response packet. */
1623 /* Tagging the fields allows us to request specific fields and to
1624 add more fields as time goes by. */
1626 #define TAG_THREADID 1 /* Echo the thread identifier. */
1627 #define TAG_EXISTS 2 /* Is this process defined enough to
1628 fetch registers and its stack? */
1629 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
1630 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
1631 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
1635 remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
1636 struct gdb_ext_thread_info *info)
1638 struct remote_state *rs = get_remote_state ();
1642 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
1645 /* info->threadid = 0; FIXME: implement zero_threadref. */
1647 info->display[0] = '\0';
1648 info->shortname[0] = '\0';
1649 info->more_display[0] = '\0';
1651 /* Assume the characters indicating the packet type have been
1653 pkt = unpack_int (pkt, &mask); /* arg mask */
1654 pkt = unpack_threadid (pkt, &ref);
1657 warning (_("Incomplete response to threadinfo request."));
1658 if (!threadmatch (&ref, expectedref))
1659 { /* This is an answer to a different request. */
1660 warning (_("ERROR RMT Thread info mismatch."));
1663 copy_threadref (&info->threadid, &ref);
1665 /* Loop on tagged fields , try to bail if somthing goes wrong. */
1667 /* Packets are terminated with nulls. */
1668 while ((pkt < limit) && mask && *pkt)
1670 pkt = unpack_int (pkt, &tag); /* tag */
1671 pkt = unpack_byte (pkt, &length); /* length */
1672 if (!(tag & mask)) /* Tags out of synch with mask. */
1674 warning (_("ERROR RMT: threadinfo tag mismatch."));
1678 if (tag == TAG_THREADID)
1682 warning (_("ERROR RMT: length of threadid is not 16."));
1686 pkt = unpack_threadid (pkt, &ref);
1687 mask = mask & ~TAG_THREADID;
1690 if (tag == TAG_EXISTS)
1692 info->active = stub_unpack_int (pkt, length);
1694 mask = mask & ~(TAG_EXISTS);
1697 warning (_("ERROR RMT: 'exists' length too long."));
1703 if (tag == TAG_THREADNAME)
1705 pkt = unpack_string (pkt, &info->shortname[0], length);
1706 mask = mask & ~TAG_THREADNAME;
1709 if (tag == TAG_DISPLAY)
1711 pkt = unpack_string (pkt, &info->display[0], length);
1712 mask = mask & ~TAG_DISPLAY;
1715 if (tag == TAG_MOREDISPLAY)
1717 pkt = unpack_string (pkt, &info->more_display[0], length);
1718 mask = mask & ~TAG_MOREDISPLAY;
1721 warning (_("ERROR RMT: unknown thread info tag."));
1722 break; /* Not a tag we know about. */
1728 remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
1729 struct gdb_ext_thread_info *info)
1731 struct remote_state *rs = get_remote_state ();
1734 pack_threadinfo_request (rs->buf, fieldset, threadid);
1736 getpkt (&rs->buf, &rs->buf_size, 0);
1737 result = remote_unpack_thread_info_response (rs->buf + 2,
1742 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
1745 pack_threadlist_request (char *pkt, int startflag, int threadcount,
1746 threadref *nextthread)
1748 *pkt++ = 'q'; /* info query packet */
1749 *pkt++ = 'L'; /* Process LIST or threadLIST request */
1750 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
1751 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
1752 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
1757 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
1760 parse_threadlist_response (char *pkt, int result_limit,
1761 threadref *original_echo, threadref *resultlist,
1764 struct remote_state *rs = get_remote_state ();
1766 int count, resultcount, done;
1769 /* Assume the 'q' and 'M chars have been stripped. */
1770 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
1771 /* done parse past here */
1772 pkt = unpack_byte (pkt, &count); /* count field */
1773 pkt = unpack_nibble (pkt, &done);
1774 /* The first threadid is the argument threadid. */
1775 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
1776 while ((count-- > 0) && (pkt < limit))
1778 pkt = unpack_threadid (pkt, resultlist++);
1779 if (resultcount++ >= result_limit)
1788 remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
1789 int *done, int *result_count, threadref *threadlist)
1791 struct remote_state *rs = get_remote_state ();
1792 static threadref echo_nextthread;
1795 /* Trancate result limit to be smaller than the packet size. */
1796 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10) >= get_remote_packet_size ())
1797 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
1799 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
1801 getpkt (&rs->buf, &rs->buf_size, 0);
1803 if (*rs->buf == '\0')
1807 parse_threadlist_response (rs->buf + 2, result_limit, &echo_nextthread,
1810 if (!threadmatch (&echo_nextthread, nextthread))
1812 /* FIXME: This is a good reason to drop the packet. */
1813 /* Possably, there is a duplicate response. */
1815 retransmit immediatly - race conditions
1816 retransmit after timeout - yes
1818 wait for packet, then exit
1820 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
1821 return 0; /* I choose simply exiting. */
1823 if (*result_count <= 0)
1827 warning (_("RMT ERROR : failed to get remote thread list."));
1830 return result; /* break; */
1832 if (*result_count > result_limit)
1835 warning (_("RMT ERROR: threadlist response longer than requested."));
1841 /* This is the interface between remote and threads, remotes upper
1844 /* remote_find_new_threads retrieves the thread list and for each
1845 thread in the list, looks up the thread in GDB's internal list,
1846 adding the thread if it does not already exist. This involves
1847 getting partial thread lists from the remote target so, polling the
1848 quit_flag is required. */
1851 /* About this many threadisds fit in a packet. */
1853 #define MAXTHREADLISTRESULTS 32
1856 remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
1859 int done, i, result_count;
1863 static threadref nextthread;
1864 static threadref resultthreadlist[MAXTHREADLISTRESULTS];
1869 if (loopcount++ > looplimit)
1872 warning (_("Remote fetch threadlist -infinite loop-."));
1875 if (!remote_get_threadlist (startflag, &nextthread, MAXTHREADLISTRESULTS,
1876 &done, &result_count, resultthreadlist))
1881 /* Clear for later iterations. */
1883 /* Setup to resume next batch of thread references, set nextthread. */
1884 if (result_count >= 1)
1885 copy_threadref (&nextthread, &resultthreadlist[result_count - 1]);
1887 while (result_count--)
1888 if (!(result = (*stepfunction) (&resultthreadlist[i++], context)))
1895 remote_newthread_step (threadref *ref, void *context)
1897 int pid = ptid_get_pid (inferior_ptid);
1898 ptid_t ptid = ptid_build (pid, 0, threadref_to_int (ref));
1900 if (!in_thread_list (ptid))
1902 return 1; /* continue iterator */
1905 #define CRAZY_MAX_THREADS 1000
1908 remote_current_thread (ptid_t oldpid)
1910 struct remote_state *rs = get_remote_state ();
1916 getpkt (&rs->buf, &rs->buf_size, 0);
1917 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
1919 /* Use strtoul here, so we'll correctly parse values whose
1920 highest bit is set. The protocol carries them as a simple
1921 series of hex digits; in the absence of a sign, strtol will
1922 see such values as positive numbers out of range for signed
1923 'long', and return LONG_MAX to indicate an overflow. */
1924 tid = strtoul (&rs->buf[2], NULL, 16);
1925 pid = ptid_get_pid (oldpid);
1926 return ptid_build (pid, 0, tid);
1932 /* Find new threads for info threads command.
1933 * Original version, using John Metzler's thread protocol.
1937 remote_find_new_threads (void)
1939 remote_threadlist_iterator (remote_newthread_step, 0,
1944 * Find all threads for info threads command.
1945 * Uses new thread protocol contributed by Cisco.
1946 * Falls back and attempts to use the older method (above)
1947 * if the target doesn't respond to the new method.
1951 remote_threads_info (void)
1953 struct remote_state *rs = get_remote_state ();
1959 if (remote_desc == 0) /* paranoia */
1960 error (_("Command can only be used when connected to the remote target."));
1962 if (use_threadinfo_query)
1964 putpkt ("qfThreadInfo");
1965 getpkt (&rs->buf, &rs->buf_size, 0);
1967 if (bufp[0] != '\0') /* q packet recognized */
1969 while (*bufp++ == 'm') /* reply contains one or more TID */
1973 /* Use strtoul here, so we'll correctly parse values
1974 whose highest bit is set. The protocol carries
1975 them as a simple series of hex digits; in the
1976 absence of a sign, strtol will see such values as
1977 positive numbers out of range for signed 'long',
1978 and return LONG_MAX to indicate an overflow. */
1979 tid = strtoul (bufp, &bufp, 16);
1980 pid = ptid_get_pid (inferior_ptid);
1981 new_thread = ptid_build (pid, 0, tid);
1982 if (tid != 0 && !in_thread_list (new_thread))
1983 add_thread (new_thread);
1985 while (*bufp++ == ','); /* comma-separated list */
1986 putpkt ("qsThreadInfo");
1987 getpkt (&rs->buf, &rs->buf_size, 0);
1994 /* Else fall back to old method based on jmetzler protocol. */
1995 use_threadinfo_query = 0;
1996 remote_find_new_threads ();
2001 * Collect a descriptive string about the given thread.
2002 * The target may say anything it wants to about the thread
2003 * (typically info about its blocked / runnable state, name, etc.).
2004 * This string will appear in the info threads display.
2006 * Optional: targets are not required to implement this function.
2010 remote_threads_extra_info (struct thread_info *tp)
2012 struct remote_state *rs = get_remote_state ();
2016 struct gdb_ext_thread_info threadinfo;
2017 static char display_buf[100]; /* arbitrary... */
2018 int n = 0; /* position in display_buf */
2020 if (remote_desc == 0) /* paranoia */
2021 internal_error (__FILE__, __LINE__,
2022 _("remote_threads_extra_info"));
2024 if (ptid_equal (tp->ptid, magic_null_ptid)
2025 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_tid (tp->ptid) == 0))
2026 /* This is the main thread which was added by GDB. The remote
2027 server doesn't know about it. */
2030 if (use_threadextra_query)
2032 xsnprintf (rs->buf, get_remote_packet_size (), "qThreadExtraInfo,%lx",
2033 ptid_get_tid (tp->ptid));
2035 getpkt (&rs->buf, &rs->buf_size, 0);
2036 if (rs->buf[0] != 0)
2038 n = min (strlen (rs->buf) / 2, sizeof (display_buf));
2039 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
2040 display_buf [result] = '\0';
2045 /* If the above query fails, fall back to the old method. */
2046 use_threadextra_query = 0;
2047 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
2048 | TAG_MOREDISPLAY | TAG_DISPLAY;
2049 int_to_threadref (&id, ptid_get_tid (tp->ptid));
2050 if (remote_get_threadinfo (&id, set, &threadinfo))
2051 if (threadinfo.active)
2053 if (*threadinfo.shortname)
2054 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
2055 " Name: %s,", threadinfo.shortname);
2056 if (*threadinfo.display)
2057 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
2058 " State: %s,", threadinfo.display);
2059 if (*threadinfo.more_display)
2060 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
2061 " Priority: %s", threadinfo.more_display);
2065 /* For purely cosmetic reasons, clear up trailing commas. */
2066 if (',' == display_buf[n-1])
2067 display_buf[n-1] = ' ';
2075 /* Restart the remote side; this is an extended protocol operation. */
2078 extended_remote_restart (void)
2080 struct remote_state *rs = get_remote_state ();
2082 /* Send the restart command; for reasons I don't understand the
2083 remote side really expects a number after the "R". */
2084 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
2087 remote_fileio_reset ();
2090 /* Clean up connection to a remote debugger. */
2093 remote_close (int quitting)
2096 serial_close (remote_desc);
2100 /* Query the remote side for the text, data and bss offsets. */
2105 struct remote_state *rs = get_remote_state ();
2108 int lose, num_segments = 0, do_sections, do_segments;
2109 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
2110 struct section_offsets *offs;
2111 struct symfile_segment_data *data;
2113 if (symfile_objfile == NULL)
2116 putpkt ("qOffsets");
2117 getpkt (&rs->buf, &rs->buf_size, 0);
2120 if (buf[0] == '\000')
2121 return; /* Return silently. Stub doesn't support
2125 warning (_("Remote failure reply: %s"), buf);
2129 /* Pick up each field in turn. This used to be done with scanf, but
2130 scanf will make trouble if CORE_ADDR size doesn't match
2131 conversion directives correctly. The following code will work
2132 with any size of CORE_ADDR. */
2133 text_addr = data_addr = bss_addr = 0;
2137 if (strncmp (ptr, "Text=", 5) == 0)
2140 /* Don't use strtol, could lose on big values. */
2141 while (*ptr && *ptr != ';')
2142 text_addr = (text_addr << 4) + fromhex (*ptr++);
2144 if (strncmp (ptr, ";Data=", 6) == 0)
2147 while (*ptr && *ptr != ';')
2148 data_addr = (data_addr << 4) + fromhex (*ptr++);
2153 if (!lose && strncmp (ptr, ";Bss=", 5) == 0)
2156 while (*ptr && *ptr != ';')
2157 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
2159 if (bss_addr != data_addr)
2160 warning (_("Target reported unsupported offsets: %s"), buf);
2165 else if (strncmp (ptr, "TextSeg=", 8) == 0)
2168 /* Don't use strtol, could lose on big values. */
2169 while (*ptr && *ptr != ';')
2170 text_addr = (text_addr << 4) + fromhex (*ptr++);
2173 if (strncmp (ptr, ";DataSeg=", 9) == 0)
2176 while (*ptr && *ptr != ';')
2177 data_addr = (data_addr << 4) + fromhex (*ptr++);
2185 error (_("Malformed response to offset query, %s"), buf);
2186 else if (*ptr != '\0')
2187 warning (_("Target reported unsupported offsets: %s"), buf);
2189 offs = ((struct section_offsets *)
2190 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
2191 memcpy (offs, symfile_objfile->section_offsets,
2192 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
2194 data = get_symfile_segment_data (symfile_objfile->obfd);
2195 do_segments = (data != NULL);
2196 do_sections = num_segments == 0;
2198 if (num_segments > 0)
2200 segments[0] = text_addr;
2201 segments[1] = data_addr;
2203 /* If we have two segments, we can still try to relocate everything
2204 by assuming that the .text and .data offsets apply to the whole
2205 text and data segments. Convert the offsets given in the packet
2206 to base addresses for symfile_map_offsets_to_segments. */
2207 else if (data && data->num_segments == 2)
2209 segments[0] = data->segment_bases[0] + text_addr;
2210 segments[1] = data->segment_bases[1] + data_addr;
2213 /* If the object file has only one segment, assume that it is text
2214 rather than data; main programs with no writable data are rare,
2215 but programs with no code are useless. Of course the code might
2216 have ended up in the data segment... to detect that we would need
2217 the permissions here. */
2218 else if (data && data->num_segments == 1)
2220 segments[0] = data->segment_bases[0] + text_addr;
2223 /* There's no way to relocate by segment. */
2229 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
2230 offs, num_segments, segments);
2232 if (ret == 0 && !do_sections)
2233 error (_("Can not handle qOffsets TextSeg response with this symbol file"));
2240 free_symfile_segment_data (data);
2244 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
2246 /* This is a temporary kludge to force data and bss to use the same offsets
2247 because that's what nlmconv does now. The real solution requires changes
2248 to the stub and remote.c that I don't have time to do right now. */
2250 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
2251 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
2254 objfile_relocate (symfile_objfile, offs);
2257 /* Stub for catch_exception. */
2259 struct start_remote_args
2263 /* The current target. */
2264 struct target_ops *target;
2266 /* Non-zero if this is an extended-remote target. */
2271 remote_start_remote (struct ui_out *uiout, void *opaque)
2273 struct remote_state *rs = get_remote_state ();
2274 struct start_remote_args *args = opaque;
2275 char *wait_status = NULL;
2277 immediate_quit++; /* Allow user to interrupt it. */
2279 /* Check whether the target is running now. */
2281 getpkt (&rs->buf, &rs->buf_size, 0);
2283 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
2285 if (args->extended_p)
2287 /* We're connected, but not running. Drop out before we
2288 call start_remote. */
2289 target_mark_exited (args->target);
2293 error (_("The target is not running (try extended-remote?)"));
2297 if (args->extended_p)
2298 target_mark_running (args->target);
2300 /* Save the reply for later. */
2301 wait_status = alloca (strlen (rs->buf) + 1);
2302 strcpy (wait_status, rs->buf);
2306 init_thread_list ();
2308 /* Let the stub know that we want it to return the thread. */
2309 set_continue_thread (minus_one_ptid);
2311 /* Without this, some commands which require an active target
2312 (such as kill) won't work. This variable serves (at least)
2313 double duty as both the pid of the target process (if it has
2314 such), and as a flag indicating that a target is active.
2315 These functions should be split out into seperate variables,
2316 especially since GDB will someday have a notion of debugging
2317 several processes. */
2318 inferior_ptid = magic_null_ptid;
2320 /* Now, if we have thread information, update inferior_ptid. */
2321 inferior_ptid = remote_current_thread (inferior_ptid);
2323 /* Always add the main thread. */
2324 add_thread_silent (inferior_ptid);
2326 get_offsets (); /* Get text, data & bss offsets. */
2328 /* Use the previously fetched status. */
2329 gdb_assert (wait_status != NULL);
2330 strcpy (rs->buf, wait_status);
2331 rs->cached_wait_status = 1;
2334 start_remote (args->from_tty); /* Initialize gdb process mechanisms. */
2337 /* Open a connection to a remote debugger.
2338 NAME is the filename used for communication. */
2341 remote_open (char *name, int from_tty)
2343 remote_open_1 (name, from_tty, &remote_ops, 0);
2346 /* Open a connection to a remote debugger using the extended
2347 remote gdb protocol. NAME is the filename used for communication. */
2350 extended_remote_open (char *name, int from_tty)
2352 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
2355 /* Generic code for opening a connection to a remote target. */
2358 init_all_packet_configs (void)
2361 for (i = 0; i < PACKET_MAX; i++)
2362 update_packet_config (&remote_protocol_packets[i]);
2365 /* Symbol look-up. */
2368 remote_check_symbols (struct objfile *objfile)
2370 struct remote_state *rs = get_remote_state ();
2371 char *msg, *reply, *tmp;
2372 struct minimal_symbol *sym;
2375 if (remote_protocol_packets[PACKET_qSymbol].support == PACKET_DISABLE)
2378 /* Allocate a message buffer. We can't reuse the input buffer in RS,
2379 because we need both at the same time. */
2380 msg = alloca (get_remote_packet_size ());
2382 /* Invite target to request symbol lookups. */
2384 putpkt ("qSymbol::");
2385 getpkt (&rs->buf, &rs->buf_size, 0);
2386 packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSymbol]);
2389 while (strncmp (reply, "qSymbol:", 8) == 0)
2392 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
2394 sym = lookup_minimal_symbol (msg, NULL, NULL);
2396 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
2399 CORE_ADDR sym_addr = SYMBOL_VALUE_ADDRESS (sym);
2401 /* If this is a function address, return the start of code
2402 instead of any data function descriptor. */
2403 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch,
2407 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
2408 paddr_nz (sym_addr), &reply[8]);
2412 getpkt (&rs->buf, &rs->buf_size, 0);
2417 static struct serial *
2418 remote_serial_open (char *name)
2420 static int udp_warning = 0;
2422 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
2423 of in ser-tcp.c, because it is the remote protocol assuming that the
2424 serial connection is reliable and not the serial connection promising
2426 if (!udp_warning && strncmp (name, "udp:", 4) == 0)
2429 The remote protocol may be unreliable over UDP.\n\
2430 Some events may be lost, rendering further debugging impossible."));
2434 return serial_open (name);
2437 /* This type describes each known response to the qSupported
2439 struct protocol_feature
2441 /* The name of this protocol feature. */
2444 /* The default for this protocol feature. */
2445 enum packet_support default_support;
2447 /* The function to call when this feature is reported, or after
2448 qSupported processing if the feature is not supported.
2449 The first argument points to this structure. The second
2450 argument indicates whether the packet requested support be
2451 enabled, disabled, or probed (or the default, if this function
2452 is being called at the end of processing and this feature was
2453 not reported). The third argument may be NULL; if not NULL, it
2454 is a NUL-terminated string taken from the packet following
2455 this feature's name and an equals sign. */
2456 void (*func) (const struct protocol_feature *, enum packet_support,
2459 /* The corresponding packet for this feature. Only used if
2460 FUNC is remote_supported_packet. */
2465 remote_supported_packet (const struct protocol_feature *feature,
2466 enum packet_support support,
2467 const char *argument)
2471 warning (_("Remote qSupported response supplied an unexpected value for"
2472 " \"%s\"."), feature->name);
2476 if (remote_protocol_packets[feature->packet].support
2477 == PACKET_SUPPORT_UNKNOWN)
2478 remote_protocol_packets[feature->packet].support = support;
2482 remote_packet_size (const struct protocol_feature *feature,
2483 enum packet_support support, const char *value)
2485 struct remote_state *rs = get_remote_state ();
2490 if (support != PACKET_ENABLE)
2493 if (value == NULL || *value == '\0')
2495 warning (_("Remote target reported \"%s\" without a size."),
2501 packet_size = strtol (value, &value_end, 16);
2502 if (errno != 0 || *value_end != '\0' || packet_size < 0)
2504 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
2505 feature->name, value);
2509 if (packet_size > MAX_REMOTE_PACKET_SIZE)
2511 warning (_("limiting remote suggested packet size (%d bytes) to %d"),
2512 packet_size, MAX_REMOTE_PACKET_SIZE);
2513 packet_size = MAX_REMOTE_PACKET_SIZE;
2516 /* Record the new maximum packet size. */
2517 rs->explicit_packet_size = packet_size;
2520 static struct protocol_feature remote_protocol_features[] = {
2521 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
2522 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
2523 PACKET_qXfer_auxv },
2524 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
2525 PACKET_qXfer_features },
2526 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
2527 PACKET_qXfer_libraries },
2528 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
2529 PACKET_qXfer_memory_map },
2530 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
2531 PACKET_qXfer_spu_read },
2532 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
2533 PACKET_qXfer_spu_write },
2534 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
2535 PACKET_QPassSignals },
2536 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
2537 PACKET_QStartNoAckMode },
2541 remote_query_supported (void)
2543 struct remote_state *rs = get_remote_state ();
2546 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
2548 /* The packet support flags are handled differently for this packet
2549 than for most others. We treat an error, a disabled packet, and
2550 an empty response identically: any features which must be reported
2551 to be used will be automatically disabled. An empty buffer
2552 accomplishes this, since that is also the representation for a list
2553 containing no features. */
2556 if (remote_protocol_packets[PACKET_qSupported].support != PACKET_DISABLE)
2558 putpkt ("qSupported");
2559 getpkt (&rs->buf, &rs->buf_size, 0);
2561 /* If an error occured, warn, but do not return - just reset the
2562 buffer to empty and go on to disable features. */
2563 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
2566 warning (_("Remote failure reply: %s"), rs->buf);
2571 memset (seen, 0, sizeof (seen));
2576 enum packet_support is_supported;
2577 char *p, *end, *name_end, *value;
2579 /* First separate out this item from the rest of the packet. If
2580 there's another item after this, we overwrite the separator
2581 (terminated strings are much easier to work with). */
2583 end = strchr (p, ';');
2586 end = p + strlen (p);
2596 warning (_("empty item in \"qSupported\" response"));
2601 name_end = strchr (p, '=');
2604 /* This is a name=value entry. */
2605 is_supported = PACKET_ENABLE;
2606 value = name_end + 1;
2615 is_supported = PACKET_ENABLE;
2619 is_supported = PACKET_DISABLE;
2623 is_supported = PACKET_SUPPORT_UNKNOWN;
2627 warning (_("unrecognized item \"%s\" in \"qSupported\" response"), p);
2633 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
2634 if (strcmp (remote_protocol_features[i].name, p) == 0)
2636 const struct protocol_feature *feature;
2639 feature = &remote_protocol_features[i];
2640 feature->func (feature, is_supported, value);
2645 /* If we increased the packet size, make sure to increase the global
2646 buffer size also. We delay this until after parsing the entire
2647 qSupported packet, because this is the same buffer we were
2649 if (rs->buf_size < rs->explicit_packet_size)
2651 rs->buf_size = rs->explicit_packet_size;
2652 rs->buf = xrealloc (rs->buf, rs->buf_size);
2655 /* Handle the defaults for unmentioned features. */
2656 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
2659 const struct protocol_feature *feature;
2661 feature = &remote_protocol_features[i];
2662 feature->func (feature, feature->default_support, NULL);
2668 remote_open_1 (char *name, int from_tty, struct target_ops *target, int extended_p)
2670 struct remote_state *rs = get_remote_state ();
2671 struct packet_config *noack_config;
2674 error (_("To open a remote debug connection, you need to specify what\n"
2675 "serial device is attached to the remote system\n"
2676 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
2678 /* See FIXME above. */
2679 if (!target_async_permitted)
2680 wait_forever_enabled_p = 1;
2682 /* If we're connected to a running target, target_preopen will kill it.
2683 But if we're connected to a target system with no running process,
2684 then we will still be connected when it returns. Ask this question
2685 first, before target_preopen has a chance to kill anything. */
2686 if (remote_desc != NULL && !target_has_execution)
2689 || query (_("Already connected to a remote target. Disconnect? ")))
2692 error (_("Still connected."));
2695 target_preopen (from_tty);
2697 unpush_target (target);
2699 /* This time without a query. If we were connected to an
2700 extended-remote target and target_preopen killed the running
2701 process, we may still be connected. If we are starting "target
2702 remote" now, the extended-remote target will not have been
2703 removed by unpush_target. */
2704 if (remote_desc != NULL && !target_has_execution)
2707 /* Make sure we send the passed signals list the next time we resume. */
2708 xfree (last_pass_packet);
2709 last_pass_packet = NULL;
2711 remote_fileio_reset ();
2712 reopen_exec_file ();
2715 remote_desc = remote_serial_open (name);
2717 perror_with_name (name);
2719 if (baud_rate != -1)
2721 if (serial_setbaudrate (remote_desc, baud_rate))
2723 /* The requested speed could not be set. Error out to
2724 top level after closing remote_desc. Take care to
2725 set remote_desc to NULL to avoid closing remote_desc
2727 serial_close (remote_desc);
2729 perror_with_name (name);
2733 serial_raw (remote_desc);
2735 /* If there is something sitting in the buffer we might take it as a
2736 response to a command, which would be bad. */
2737 serial_flush_input (remote_desc);
2741 puts_filtered ("Remote debugging using ");
2742 puts_filtered (name);
2743 puts_filtered ("\n");
2745 push_target (target); /* Switch to using remote target now. */
2747 /* Assume that the target is running, unless we learn otherwise. */
2748 target_mark_running (target);
2750 /* Reset the target state; these things will be queried either by
2751 remote_query_supported or as they are needed. */
2752 init_all_packet_configs ();
2753 rs->explicit_packet_size = 0;
2756 general_thread = not_sent_ptid;
2757 continue_thread = not_sent_ptid;
2759 /* Probe for ability to use "ThreadInfo" query, as required. */
2760 use_threadinfo_query = 1;
2761 use_threadextra_query = 1;
2763 /* Ack any packet which the remote side has already sent. */
2764 serial_write (remote_desc, "+", 1);
2766 /* The first packet we send to the target is the optional "supported
2767 packets" request. If the target can answer this, it will tell us
2768 which later probes to skip. */
2769 remote_query_supported ();
2771 /* Next, we possibly activate noack mode.
2773 If the QStartNoAckMode packet configuration is set to AUTO,
2774 enable noack mode if the stub reported a wish for it with
2777 If set to TRUE, then enable noack mode even if the stub didn't
2778 report it in qSupported. If the stub doesn't reply OK, the
2779 session ends with an error.
2781 If FALSE, then don't activate noack mode, regardless of what the
2782 stub claimed should be the default with qSupported. */
2784 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
2786 if (noack_config->detect == AUTO_BOOLEAN_TRUE
2787 || (noack_config->detect == AUTO_BOOLEAN_AUTO
2788 && noack_config->support == PACKET_ENABLE))
2790 putpkt ("QStartNoAckMode");
2791 getpkt (&rs->buf, &rs->buf_size, 0);
2792 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
2796 /* Next, if the target can specify a description, read it. We do
2797 this before anything involving memory or registers. */
2798 target_find_description ();
2800 if (target_async_permitted)
2802 /* With this target we start out by owning the terminal. */
2803 remote_async_terminal_ours_p = 1;
2805 /* FIXME: cagney/1999-09-23: During the initial connection it is
2806 assumed that the target is already ready and able to respond to
2807 requests. Unfortunately remote_start_remote() eventually calls
2808 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
2809 around this. Eventually a mechanism that allows
2810 wait_for_inferior() to expect/get timeouts will be
2812 wait_forever_enabled_p = 0;
2815 /* First delete any symbols previously loaded from shared libraries. */
2816 no_shared_libraries (NULL, 0);
2818 /* Start the remote connection. If error() or QUIT, discard this
2819 target (we'd otherwise be in an inconsistent state) and then
2820 propogate the error on up the exception chain. This ensures that
2821 the caller doesn't stumble along blindly assuming that the
2822 function succeeded. The CLI doesn't have this problem but other
2823 UI's, such as MI do.
2825 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
2826 this function should return an error indication letting the
2827 caller restore the previous state. Unfortunately the command
2828 ``target remote'' is directly wired to this function making that
2829 impossible. On a positive note, the CLI side of this problem has
2830 been fixed - the function set_cmd_context() makes it possible for
2831 all the ``target ....'' commands to share a common callback
2832 function. See cli-dump.c. */
2834 struct gdb_exception ex;
2835 struct start_remote_args args;
2837 args.from_tty = from_tty;
2838 args.target = target;
2839 args.extended_p = extended_p;
2841 ex = catch_exception (uiout, remote_start_remote, &args, RETURN_MASK_ALL);
2845 if (target_async_permitted)
2846 wait_forever_enabled_p = 1;
2847 throw_exception (ex);
2851 if (target_async_permitted)
2852 wait_forever_enabled_p = 1;
2856 /* Tell the remote that we are using the extended protocol. */
2858 getpkt (&rs->buf, &rs->buf_size, 0);
2861 /* If we connected to a live target, do some additional setup. */
2862 if (target_has_execution)
2864 if (exec_bfd) /* No use without an exec file. */
2865 remote_check_symbols (symfile_objfile);
2869 /* This takes a program previously attached to and detaches it. After
2870 this is done, GDB can be used to debug some other program. We
2871 better not have left any breakpoints in the target program or it'll
2872 die when it hits one. */
2875 remote_detach_1 (char *args, int from_tty, int extended)
2877 struct remote_state *rs = get_remote_state ();
2880 error (_("Argument given to \"detach\" when remotely debugging."));
2882 if (!target_has_execution)
2883 error (_("No process to detach from."));
2885 /* Tell the remote target to detach. */
2886 strcpy (rs->buf, "D");
2888 getpkt (&rs->buf, &rs->buf_size, 0);
2890 if (rs->buf[0] == 'E')
2891 error (_("Can't detach process."));
2893 /* Unregister the file descriptor from the event loop. */
2894 if (target_is_async_p ())
2895 serial_async (remote_desc, NULL, 0);
2897 target_mourn_inferior ();
2901 puts_filtered ("Detached from remote process.\n");
2903 puts_filtered ("Ending remote debugging.\n");
2908 remote_detach (char *args, int from_tty)
2910 remote_detach_1 (args, from_tty, 0);
2914 extended_remote_detach (char *args, int from_tty)
2916 remote_detach_1 (args, from_tty, 1);
2919 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
2922 remote_disconnect (struct target_ops *target, char *args, int from_tty)
2925 error (_("Argument given to \"disconnect\" when remotely debugging."));
2927 /* Unregister the file descriptor from the event loop. */
2928 if (target_is_async_p ())
2929 serial_async (remote_desc, NULL, 0);
2931 /* Make sure we unpush even the extended remote targets; mourn
2932 won't do it. So call remote_mourn_1 directly instead of
2933 target_mourn_inferior. */
2934 remote_mourn_1 (target);
2937 puts_filtered ("Ending remote debugging.\n");
2940 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
2941 be chatty about it. */
2944 extended_remote_attach_1 (struct target_ops *target, char *args, int from_tty)
2946 struct remote_state *rs = get_remote_state ();
2949 char *wait_status = NULL;
2952 error_no_arg (_("process-id to attach"));
2955 pid = strtol (args, &dummy, 0);
2956 /* Some targets don't set errno on errors, grrr! */
2957 if (pid == 0 && args == dummy)
2958 error (_("Illegal process-id: %s."), args);
2960 if (remote_protocol_packets[PACKET_vAttach].support == PACKET_DISABLE)
2961 error (_("This target does not support attaching to a process"));
2963 sprintf (rs->buf, "vAttach;%x", pid);
2965 getpkt (&rs->buf, &rs->buf_size, 0);
2967 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vAttach]) == PACKET_OK)
2970 printf_unfiltered (_("Attached to %s\n"),
2971 target_pid_to_str (pid_to_ptid (pid)));
2973 /* Save the reply for later. */
2974 wait_status = alloca (strlen (rs->buf) + 1);
2975 strcpy (wait_status, rs->buf);
2977 else if (remote_protocol_packets[PACKET_vAttach].support == PACKET_DISABLE)
2978 error (_("This target does not support attaching to a process"));
2980 error (_("Attaching to %s failed"),
2981 target_pid_to_str (pid_to_ptid (pid)));
2983 target_mark_running (target);
2984 inferior_ptid = pid_to_ptid (pid);
2986 /* Now, if we have thread information, update inferior_ptid. */
2987 inferior_ptid = remote_current_thread (inferior_ptid);
2989 /* Now, add the main thread to the thread list. */
2990 add_thread_silent (inferior_ptid);
2994 /* Next, if the target can specify a description, read it. We do
2995 this before anything involving memory or registers. */
2996 target_find_description ();
2998 /* Use the previously fetched status. */
2999 gdb_assert (wait_status != NULL);
3000 strcpy (rs->buf, wait_status);
3001 rs->cached_wait_status = 1;
3005 extended_remote_attach (char *args, int from_tty)
3007 extended_remote_attach_1 (&extended_remote_ops, args, from_tty);
3010 /* Convert hex digit A to a number. */
3015 if (a >= '0' && a <= '9')
3017 else if (a >= 'a' && a <= 'f')
3018 return a - 'a' + 10;
3019 else if (a >= 'A' && a <= 'F')
3020 return a - 'A' + 10;
3022 error (_("Reply contains invalid hex digit %d"), a);
3026 hex2bin (const char *hex, gdb_byte *bin, int count)
3030 for (i = 0; i < count; i++)
3032 if (hex[0] == 0 || hex[1] == 0)
3034 /* Hex string is short, or of uneven length.
3035 Return the count that has been converted so far. */
3038 *bin++ = fromhex (hex[0]) * 16 + fromhex (hex[1]);
3044 /* Convert number NIB to a hex digit. */
3052 return 'a' + nib - 10;
3056 bin2hex (const gdb_byte *bin, char *hex, int count)
3059 /* May use a length, or a nul-terminated string as input. */
3061 count = strlen ((char *) bin);
3063 for (i = 0; i < count; i++)
3065 *hex++ = tohex ((*bin >> 4) & 0xf);
3066 *hex++ = tohex (*bin++ & 0xf);
3072 /* Check for the availability of vCont. This function should also check
3076 remote_vcont_probe (struct remote_state *rs)
3080 strcpy (rs->buf, "vCont?");
3082 getpkt (&rs->buf, &rs->buf_size, 0);
3085 /* Make sure that the features we assume are supported. */
3086 if (strncmp (buf, "vCont", 5) == 0)
3089 int support_s, support_S, support_c, support_C;
3095 while (p && *p == ';')
3098 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
3100 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
3102 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
3104 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
3107 p = strchr (p, ';');
3110 /* If s, S, c, and C are not all supported, we can't use vCont. Clearing
3111 BUF will make packet_ok disable the packet. */
3112 if (!support_s || !support_S || !support_c || !support_C)
3116 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
3119 /* Resume the remote inferior by using a "vCont" packet. The thread
3120 to be resumed is PTID; STEP and SIGGNAL indicate whether the
3121 resumed thread should be single-stepped and/or signalled. If PTID
3122 equals minus_one_ptid, then all threads are resumed; the thread to
3123 be stepped and/or signalled is given in the global INFERIOR_PTID.
3124 This function returns non-zero iff it resumes the inferior.
3126 This function issues a strict subset of all possible vCont commands at the
3130 remote_vcont_resume (ptid_t ptid, int step, enum target_signal siggnal)
3132 struct remote_state *rs = get_remote_state ();
3134 struct cleanup *old_cleanup;
3136 if (remote_protocol_packets[PACKET_vCont].support == PACKET_SUPPORT_UNKNOWN)
3137 remote_vcont_probe (rs);
3139 if (remote_protocol_packets[PACKET_vCont].support == PACKET_DISABLE)
3142 /* If we could generate a wider range of packets, we'd have to worry
3143 about overflowing BUF. Should there be a generic
3144 "multi-part-packet" packet? */
3146 if (ptid_equal (ptid, magic_null_ptid))
3148 /* MAGIC_NULL_PTID means that we don't have any active threads,
3149 so we don't have any TID numbers the inferior will
3150 understand. Make sure to only send forms that do not specify
3152 if (step && siggnal != TARGET_SIGNAL_0)
3153 outbuf = xstrprintf ("vCont;S%02x", siggnal);
3155 outbuf = xstrprintf ("vCont;s");
3156 else if (siggnal != TARGET_SIGNAL_0)
3157 outbuf = xstrprintf ("vCont;C%02x", siggnal);
3159 outbuf = xstrprintf ("vCont;c");
3161 else if (ptid_equal (ptid, minus_one_ptid))
3163 /* Resume all threads, with preference for INFERIOR_PTID. */
3164 int tid = ptid_get_tid (inferior_ptid);
3165 if (step && siggnal != TARGET_SIGNAL_0)
3166 outbuf = xstrprintf ("vCont;S%02x:%x;c", siggnal, tid);
3168 outbuf = xstrprintf ("vCont;s:%x;c", tid);
3169 else if (siggnal != TARGET_SIGNAL_0)
3170 outbuf = xstrprintf ("vCont;C%02x:%x;c", siggnal, tid);
3172 outbuf = xstrprintf ("vCont;c");
3176 /* Scheduler locking; resume only PTID. */
3177 int tid = ptid_get_tid (ptid);
3178 if (step && siggnal != TARGET_SIGNAL_0)
3179 outbuf = xstrprintf ("vCont;S%02x:%x", siggnal, tid);
3181 outbuf = xstrprintf ("vCont;s:%x", tid);
3182 else if (siggnal != TARGET_SIGNAL_0)
3183 outbuf = xstrprintf ("vCont;C%02x:%x", siggnal, tid);
3185 outbuf = xstrprintf ("vCont;c:%x", tid);
3188 gdb_assert (outbuf && strlen (outbuf) < get_remote_packet_size ());
3189 old_cleanup = make_cleanup (xfree, outbuf);
3193 do_cleanups (old_cleanup);
3198 /* Tell the remote machine to resume. */
3200 static enum target_signal last_sent_signal = TARGET_SIGNAL_0;
3202 static int last_sent_step;
3205 remote_resume (ptid_t ptid, int step, enum target_signal siggnal)
3207 struct remote_state *rs = get_remote_state ();
3210 last_sent_signal = siggnal;
3211 last_sent_step = step;
3213 /* Update the inferior on signals to silently pass, if they've changed. */
3214 remote_pass_signals ();
3216 /* The vCont packet doesn't need to specify threads via Hc. */
3217 if (remote_vcont_resume (ptid, step, siggnal))
3220 /* All other supported resume packets do use Hc, so set the continue
3222 if (ptid_equal (ptid, minus_one_ptid))
3223 set_continue_thread (any_thread_ptid);
3225 set_continue_thread (ptid);
3228 if (siggnal != TARGET_SIGNAL_0)
3230 buf[0] = step ? 'S' : 'C';
3231 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
3232 buf[2] = tohex (((int) siggnal) & 0xf);
3236 strcpy (buf, step ? "s" : "c");
3241 /* We are about to start executing the inferior, let's register it
3242 with the event loop. NOTE: this is the one place where all the
3243 execution commands end up. We could alternatively do this in each
3244 of the execution commands in infcmd.c. */
3245 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
3246 into infcmd.c in order to allow inferior function calls to work
3247 NOT asynchronously. */
3248 if (target_can_async_p ())
3249 target_async (inferior_event_handler, 0);
3253 /* Set up the signal handler for SIGINT, while the target is
3254 executing, ovewriting the 'regular' SIGINT signal handler. */
3256 initialize_sigint_signal_handler (void)
3258 signal (SIGINT, handle_remote_sigint);
3261 /* Signal handler for SIGINT, while the target is executing. */
3263 handle_remote_sigint (int sig)
3265 signal (sig, handle_remote_sigint_twice);
3266 mark_async_signal_handler_wrapper (sigint_remote_token);
3269 /* Signal handler for SIGINT, installed after SIGINT has already been
3270 sent once. It will take effect the second time that the user sends
3273 handle_remote_sigint_twice (int sig)
3275 signal (sig, handle_remote_sigint);
3276 mark_async_signal_handler_wrapper (sigint_remote_twice_token);
3279 /* Perform the real interruption of the target execution, in response
3282 async_remote_interrupt (gdb_client_data arg)
3285 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
3287 target_stop (inferior_ptid);
3290 /* Perform interrupt, if the first attempt did not succeed. Just give
3291 up on the target alltogether. */
3293 async_remote_interrupt_twice (gdb_client_data arg)
3296 fprintf_unfiltered (gdb_stdlog, "remote_interrupt_twice called\n");
3301 /* Reinstall the usual SIGINT handlers, after the target has
3304 cleanup_sigint_signal_handler (void *dummy)
3306 signal (SIGINT, handle_sigint);
3309 /* Send ^C to target to halt it. Target will respond, and send us a
3311 static void (*ofunc) (int);
3313 /* The command line interface's stop routine. This function is installed
3314 as a signal handler for SIGINT. The first time a user requests a
3315 stop, we call remote_stop to send a break or ^C. If there is no
3316 response from the target (it didn't stop when the user requested it),
3317 we ask the user if he'd like to detach from the target. */
3319 remote_interrupt (int signo)
3321 /* If this doesn't work, try more severe steps. */
3322 signal (signo, remote_interrupt_twice);
3324 gdb_call_async_signal_handler (sigint_remote_token, 1);
3327 /* The user typed ^C twice. */
3330 remote_interrupt_twice (int signo)
3332 signal (signo, ofunc);
3333 gdb_call_async_signal_handler (sigint_remote_twice_token, 1);
3334 signal (signo, remote_interrupt);
3337 /* This is the generic stop called via the target vector. When a target
3338 interrupt is requested, either by the command line or the GUI, we
3339 will eventually end up here. */
3341 remote_stop (ptid_t ptid)
3343 /* Send a break or a ^C, depending on user preference. */
3345 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
3348 serial_send_break (remote_desc);
3350 serial_write (remote_desc, "\003", 1);
3353 /* Ask the user what to do when an interrupt is received. */
3356 interrupt_query (void)
3358 target_terminal_ours ();
3360 if (query ("Interrupted while waiting for the program.\n\
3361 Give up (and stop debugging it)? "))
3363 target_mourn_inferior ();
3364 signal (SIGINT, handle_sigint);
3365 deprecated_throw_reason (RETURN_QUIT);
3368 target_terminal_inferior ();
3371 /* Enable/disable target terminal ownership. Most targets can use
3372 terminal groups to control terminal ownership. Remote targets are
3373 different in that explicit transfer of ownership to/from GDB/target
3377 remote_terminal_inferior (void)
3379 if (!target_async_permitted)
3380 /* Nothing to do. */
3383 /* FIXME: cagney/1999-09-27: Shouldn't need to test for
3384 sync_execution here. This function should only be called when
3385 GDB is resuming the inferior in the forground. A background
3386 resume (``run&'') should leave GDB in control of the terminal and
3387 consequently should not call this code. */
3388 if (!sync_execution)
3390 /* FIXME: cagney/1999-09-27: Closely related to the above. Make
3391 calls target_terminal_*() idenpotent. The event-loop GDB talking
3392 to an asynchronous target with a synchronous command calls this
3393 function from both event-top.c and infrun.c/infcmd.c. Once GDB
3394 stops trying to transfer the terminal to the target when it
3395 shouldn't this guard can go away. */
3396 if (!remote_async_terminal_ours_p)
3398 delete_file_handler (input_fd);
3399 remote_async_terminal_ours_p = 0;
3400 initialize_sigint_signal_handler ();
3401 /* NOTE: At this point we could also register our selves as the
3402 recipient of all input. Any characters typed could then be
3403 passed on down to the target. */
3407 remote_terminal_ours (void)
3409 if (!target_async_permitted)
3410 /* Nothing to do. */
3413 /* See FIXME in remote_terminal_inferior. */
3414 if (!sync_execution)
3416 /* See FIXME in remote_terminal_inferior. */
3417 if (remote_async_terminal_ours_p)
3419 cleanup_sigint_signal_handler (NULL);
3420 add_file_handler (input_fd, stdin_event_handler, 0);
3421 remote_async_terminal_ours_p = 1;
3425 remote_console_output (char *msg)
3429 for (p = msg; p[0] && p[1]; p += 2)
3432 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
3435 fputs_unfiltered (tb, gdb_stdtarg);
3437 gdb_flush (gdb_stdtarg);
3440 /* Wait until the remote machine stops, then return,
3441 storing status in STATUS just as `wait' would. */
3444 remote_wait (ptid_t ptid, struct target_waitstatus *status)
3446 struct remote_state *rs = get_remote_state ();
3447 struct remote_arch_state *rsa = get_remote_arch_state ();
3448 ULONGEST thread_num = -1;
3449 ULONGEST process_num = -1;
3451 int solibs_changed = 0;
3453 status->kind = TARGET_WAITKIND_EXITED;
3454 status->value.integer = 0;
3460 if (rs->cached_wait_status)
3461 /* Use the cached wait status, but only once. */
3462 rs->cached_wait_status = 0;
3465 if (!target_is_async_p ())
3467 ofunc = signal (SIGINT, remote_interrupt);
3468 /* If the user hit C-c before this packet, or between packets,
3469 pretend that it was hit right here. */
3473 remote_interrupt (SIGINT);
3476 /* FIXME: cagney/1999-09-27: If we're in async mode we should
3477 _never_ wait for ever -> test on target_is_async_p().
3478 However, before we do that we need to ensure that the caller
3479 knows how to take the target into/out of async mode. */
3480 getpkt (&rs->buf, &rs->buf_size, wait_forever_enabled_p);
3481 if (!target_is_async_p ())
3482 signal (SIGINT, ofunc);
3487 remote_stopped_by_watchpoint_p = 0;
3491 case 'E': /* Error of some sort. */
3492 /* We're out of sync with the target now. Did it continue or not?
3493 Not is more likely, so report a stop. */
3494 warning (_("Remote failure reply: %s"), buf);
3495 status->kind = TARGET_WAITKIND_STOPPED;
3496 status->value.sig = TARGET_SIGNAL_0;
3498 case 'F': /* File-I/O request. */
3499 remote_fileio_request (buf);
3501 case 'T': /* Status with PC, SP, FP, ... */
3503 gdb_byte regs[MAX_REGISTER_SIZE];
3505 /* Expedited reply, containing Signal, {regno, reg} repeat. */
3506 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
3508 n... = register number
3509 r... = register contents
3511 p = &buf[3]; /* after Txx */
3520 /* If the packet contains a register number, save it
3521 in pnum and set p1 to point to the character
3522 following it. Otherwise p1 points to p. */
3524 /* If this packet is an awatch packet, don't parse the
3525 'a' as a register number. */
3527 if (strncmp (p, "awatch", strlen("awatch")) != 0)
3529 /* Read the ``P'' register number. */
3530 pnum = strtol (p, &p_temp, 16);
3536 if (p1 == p) /* No register number present here. */
3538 p1 = strchr (p, ':');
3540 error (_("Malformed packet(a) (missing colon): %s\n\
3543 if (strncmp (p, "thread", p1 - p) == 0)
3545 p_temp = unpack_varlen_hex (++p1, &thread_num);
3548 else if ((strncmp (p, "watch", p1 - p) == 0)
3549 || (strncmp (p, "rwatch", p1 - p) == 0)
3550 || (strncmp (p, "awatch", p1 - p) == 0))
3552 remote_stopped_by_watchpoint_p = 1;
3553 p = unpack_varlen_hex (++p1, &addr);
3554 remote_watch_data_address = (CORE_ADDR)addr;
3556 else if (strncmp (p, "library", p1 - p) == 0)
3560 while (*p_temp && *p_temp != ';')
3568 /* Silently skip unknown optional info. */
3569 p_temp = strchr (p1 + 1, ';');
3576 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
3580 error (_("Malformed packet(b) (missing colon): %s\n\
3586 error (_("Remote sent bad register number %s: %s\n\
3588 phex_nz (pnum, 0), p, buf);
3590 fieldsize = hex2bin (p, regs,
3591 register_size (target_gdbarch,
3594 if (fieldsize < register_size (target_gdbarch,
3596 warning (_("Remote reply is too short: %s"), buf);
3597 regcache_raw_supply (get_current_regcache (),
3602 error (_("Remote register badly formatted: %s\nhere: %s"),
3608 case 'S': /* Old style status, just signal only. */
3610 status->kind = TARGET_WAITKIND_LOADED;
3613 status->kind = TARGET_WAITKIND_STOPPED;
3614 status->value.sig = (enum target_signal)
3615 (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
3618 case 'W': /* Target exited. */
3620 /* The remote process exited. */
3621 status->kind = TARGET_WAITKIND_EXITED;
3622 status->value.integer = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
3626 status->kind = TARGET_WAITKIND_SIGNALLED;
3627 status->value.sig = (enum target_signal)
3628 (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
3631 case 'O': /* Console output. */
3632 remote_console_output (buf + 1);
3633 if (target_can_async_p ())
3635 /* Return immediately to the event loop. The event loop
3636 will still be waiting on the inferior afterwards. */
3637 status->kind = TARGET_WAITKIND_IGNORE;
3643 if (last_sent_signal != TARGET_SIGNAL_0)
3645 /* Zero length reply means that we tried 'S' or 'C' and
3646 the remote system doesn't support it. */
3647 target_terminal_ours_for_output ();
3649 ("Can't send signals to this remote system. %s not sent.\n",
3650 target_signal_to_name (last_sent_signal));
3651 last_sent_signal = TARGET_SIGNAL_0;
3652 target_terminal_inferior ();
3654 strcpy ((char *) buf, last_sent_step ? "s" : "c");
3655 putpkt ((char *) buf);
3658 /* else fallthrough */
3660 warning (_("Invalid remote reply: %s"), buf);
3665 if (thread_num != -1)
3668 ptid = ptid_build (ptid_get_pid (inferior_ptid), 0, thread_num);
3669 record_currthread (ptid);
3673 return inferior_ptid;
3676 /* Fetch a single register using a 'p' packet. */
3679 fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
3681 struct remote_state *rs = get_remote_state ();
3683 char regp[MAX_REGISTER_SIZE];
3686 if (remote_protocol_packets[PACKET_p].support == PACKET_DISABLE)
3689 if (reg->pnum == -1)
3694 p += hexnumstr (p, reg->pnum);
3696 remote_send (&rs->buf, &rs->buf_size);
3700 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
3704 case PACKET_UNKNOWN:
3707 error (_("Could not fetch register \"%s\""),
3708 gdbarch_register_name (get_regcache_arch (regcache), reg->regnum));
3711 /* If this register is unfetchable, tell the regcache. */
3714 regcache_raw_supply (regcache, reg->regnum, NULL);
3718 /* Otherwise, parse and supply the value. */
3724 error (_("fetch_register_using_p: early buf termination"));
3726 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
3729 regcache_raw_supply (regcache, reg->regnum, regp);
3733 /* Fetch the registers included in the target's 'g' packet. */
3736 send_g_packet (void)
3738 struct remote_state *rs = get_remote_state ();
3743 sprintf (rs->buf, "g");
3744 remote_send (&rs->buf, &rs->buf_size);
3746 /* We can get out of synch in various cases. If the first character
3747 in the buffer is not a hex character, assume that has happened
3748 and try to fetch another packet to read. */
3749 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
3750 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
3751 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
3752 && rs->buf[0] != 'x') /* New: unavailable register value. */
3755 fprintf_unfiltered (gdb_stdlog,
3756 "Bad register packet; fetching a new packet\n");
3757 getpkt (&rs->buf, &rs->buf_size, 0);
3760 buf_len = strlen (rs->buf);
3762 /* Sanity check the received packet. */
3763 if (buf_len % 2 != 0)
3764 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
3770 process_g_packet (struct regcache *regcache)
3772 struct gdbarch *gdbarch = get_regcache_arch (regcache);
3773 struct remote_state *rs = get_remote_state ();
3774 struct remote_arch_state *rsa = get_remote_arch_state ();
3779 buf_len = strlen (rs->buf);
3781 /* Further sanity checks, with knowledge of the architecture. */
3782 if (buf_len > 2 * rsa->sizeof_g_packet)
3783 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
3785 /* Save the size of the packet sent to us by the target. It is used
3786 as a heuristic when determining the max size of packets that the
3787 target can safely receive. */
3788 if (rsa->actual_register_packet_size == 0)
3789 rsa->actual_register_packet_size = buf_len;
3791 /* If this is smaller than we guessed the 'g' packet would be,
3792 update our records. A 'g' reply that doesn't include a register's
3793 value implies either that the register is not available, or that
3794 the 'p' packet must be used. */
3795 if (buf_len < 2 * rsa->sizeof_g_packet)
3797 rsa->sizeof_g_packet = buf_len / 2;
3799 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
3801 if (rsa->regs[i].pnum == -1)
3804 if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
3805 rsa->regs[i].in_g_packet = 0;
3807 rsa->regs[i].in_g_packet = 1;
3811 regs = alloca (rsa->sizeof_g_packet);
3813 /* Unimplemented registers read as all bits zero. */
3814 memset (regs, 0, rsa->sizeof_g_packet);
3816 /* Reply describes registers byte by byte, each byte encoded as two
3817 hex characters. Suck them all up, then supply them to the
3818 register cacheing/storage mechanism. */
3821 for (i = 0; i < rsa->sizeof_g_packet; i++)
3823 if (p[0] == 0 || p[1] == 0)
3824 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
3825 internal_error (__FILE__, __LINE__,
3826 "unexpected end of 'g' packet reply");
3828 if (p[0] == 'x' && p[1] == 'x')
3829 regs[i] = 0; /* 'x' */
3831 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
3837 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
3839 struct packet_reg *r = &rsa->regs[i];
3842 if (r->offset * 2 >= strlen (rs->buf))
3843 /* This shouldn't happen - we adjusted in_g_packet above. */
3844 internal_error (__FILE__, __LINE__,
3845 "unexpected end of 'g' packet reply");
3846 else if (rs->buf[r->offset * 2] == 'x')
3848 gdb_assert (r->offset * 2 < strlen (rs->buf));
3849 /* The register isn't available, mark it as such (at
3850 the same time setting the value to zero). */
3851 regcache_raw_supply (regcache, r->regnum, NULL);
3854 regcache_raw_supply (regcache, r->regnum,
3862 fetch_registers_using_g (struct regcache *regcache)
3865 process_g_packet (regcache);
3869 remote_fetch_registers (struct regcache *regcache, int regnum)
3871 struct remote_state *rs = get_remote_state ();
3872 struct remote_arch_state *rsa = get_remote_arch_state ();
3875 set_general_thread (inferior_ptid);
3879 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
3880 gdb_assert (reg != NULL);
3882 /* If this register might be in the 'g' packet, try that first -
3883 we are likely to read more than one register. If this is the
3884 first 'g' packet, we might be overly optimistic about its
3885 contents, so fall back to 'p'. */
3886 if (reg->in_g_packet)
3888 fetch_registers_using_g (regcache);
3889 if (reg->in_g_packet)
3893 if (fetch_register_using_p (regcache, reg))
3896 /* This register is not available. */
3897 regcache_raw_supply (regcache, reg->regnum, NULL);
3902 fetch_registers_using_g (regcache);
3904 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
3905 if (!rsa->regs[i].in_g_packet)
3906 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
3908 /* This register is not available. */
3909 regcache_raw_supply (regcache, i, NULL);
3913 /* Prepare to store registers. Since we may send them all (using a
3914 'G' request), we have to read out the ones we don't want to change
3918 remote_prepare_to_store (struct regcache *regcache)
3920 struct remote_arch_state *rsa = get_remote_arch_state ();
3922 gdb_byte buf[MAX_REGISTER_SIZE];
3924 /* Make sure the entire registers array is valid. */
3925 switch (remote_protocol_packets[PACKET_P].support)
3927 case PACKET_DISABLE:
3928 case PACKET_SUPPORT_UNKNOWN:
3929 /* Make sure all the necessary registers are cached. */
3930 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
3931 if (rsa->regs[i].in_g_packet)
3932 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
3939 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
3940 packet was not recognized. */
3943 store_register_using_P (const struct regcache *regcache, struct packet_reg *reg)
3945 struct gdbarch *gdbarch = get_regcache_arch (regcache);
3946 struct remote_state *rs = get_remote_state ();
3947 struct remote_arch_state *rsa = get_remote_arch_state ();
3948 /* Try storing a single register. */
3949 char *buf = rs->buf;
3950 gdb_byte regp[MAX_REGISTER_SIZE];
3953 if (remote_protocol_packets[PACKET_P].support == PACKET_DISABLE)
3956 if (reg->pnum == -1)
3959 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
3960 p = buf + strlen (buf);
3961 regcache_raw_collect (regcache, reg->regnum, regp);
3962 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
3963 remote_send (&rs->buf, &rs->buf_size);
3965 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
3970 error (_("Could not write register \"%s\""),
3971 gdbarch_register_name (gdbarch, reg->regnum));
3972 case PACKET_UNKNOWN:
3975 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
3979 /* Store register REGNUM, or all registers if REGNUM == -1, from the
3980 contents of the register cache buffer. FIXME: ignores errors. */
3983 store_registers_using_G (const struct regcache *regcache)
3985 struct remote_state *rs = get_remote_state ();
3986 struct remote_arch_state *rsa = get_remote_arch_state ();
3990 /* Extract all the registers in the regcache copying them into a
3994 regs = alloca (rsa->sizeof_g_packet);
3995 memset (regs, 0, rsa->sizeof_g_packet);
3996 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
3998 struct packet_reg *r = &rsa->regs[i];
4000 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
4004 /* Command describes registers byte by byte,
4005 each byte encoded as two hex characters. */
4008 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
4010 bin2hex (regs, p, rsa->sizeof_g_packet);
4011 remote_send (&rs->buf, &rs->buf_size);
4014 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
4015 of the register cache buffer. FIXME: ignores errors. */
4018 remote_store_registers (struct regcache *regcache, int regnum)
4020 struct remote_state *rs = get_remote_state ();
4021 struct remote_arch_state *rsa = get_remote_arch_state ();
4024 set_general_thread (inferior_ptid);
4028 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
4029 gdb_assert (reg != NULL);
4031 /* Always prefer to store registers using the 'P' packet if
4032 possible; we often change only a small number of registers.
4033 Sometimes we change a larger number; we'd need help from a
4034 higher layer to know to use 'G'. */
4035 if (store_register_using_P (regcache, reg))
4038 /* For now, don't complain if we have no way to write the
4039 register. GDB loses track of unavailable registers too
4040 easily. Some day, this may be an error. We don't have
4041 any way to read the register, either... */
4042 if (!reg->in_g_packet)
4045 store_registers_using_G (regcache);
4049 store_registers_using_G (regcache);
4051 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
4052 if (!rsa->regs[i].in_g_packet)
4053 if (!store_register_using_P (regcache, &rsa->regs[i]))
4054 /* See above for why we do not issue an error here. */
4059 /* Return the number of hex digits in num. */
4062 hexnumlen (ULONGEST num)
4066 for (i = 0; num != 0; i++)
4072 /* Set BUF to the minimum number of hex digits representing NUM. */
4075 hexnumstr (char *buf, ULONGEST num)
4077 int len = hexnumlen (num);
4078 return hexnumnstr (buf, num, len);
4082 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
4085 hexnumnstr (char *buf, ULONGEST num, int width)
4091 for (i = width - 1; i >= 0; i--)
4093 buf[i] = "0123456789abcdef"[(num & 0xf)];
4100 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
4103 remote_address_masked (CORE_ADDR addr)
4105 int address_size = remote_address_size;
4106 /* If "remoteaddresssize" was not set, default to target address size. */
4108 address_size = gdbarch_addr_bit (target_gdbarch);
4110 if (address_size > 0
4111 && address_size < (sizeof (ULONGEST) * 8))
4113 /* Only create a mask when that mask can safely be constructed
4114 in a ULONGEST variable. */
4116 mask = (mask << address_size) - 1;
4122 /* Convert BUFFER, binary data at least LEN bytes long, into escaped
4123 binary data in OUT_BUF. Set *OUT_LEN to the length of the data
4124 encoded in OUT_BUF, and return the number of bytes in OUT_BUF
4125 (which may be more than *OUT_LEN due to escape characters). The
4126 total number of bytes in the output buffer will be at most
4130 remote_escape_output (const gdb_byte *buffer, int len,
4131 gdb_byte *out_buf, int *out_len,
4134 int input_index, output_index;
4137 for (input_index = 0; input_index < len; input_index++)
4139 gdb_byte b = buffer[input_index];
4141 if (b == '$' || b == '#' || b == '}')
4143 /* These must be escaped. */
4144 if (output_index + 2 > out_maxlen)
4146 out_buf[output_index++] = '}';
4147 out_buf[output_index++] = b ^ 0x20;
4151 if (output_index + 1 > out_maxlen)
4153 out_buf[output_index++] = b;
4157 *out_len = input_index;
4158 return output_index;
4161 /* Convert BUFFER, escaped data LEN bytes long, into binary data
4162 in OUT_BUF. Return the number of bytes written to OUT_BUF.
4163 Raise an error if the total number of bytes exceeds OUT_MAXLEN.
4165 This function reverses remote_escape_output. It allows more
4166 escaped characters than that function does, in particular because
4167 '*' must be escaped to avoid the run-length encoding processing
4168 in reading packets. */
4171 remote_unescape_input (const gdb_byte *buffer, int len,
4172 gdb_byte *out_buf, int out_maxlen)
4174 int input_index, output_index;
4179 for (input_index = 0; input_index < len; input_index++)
4181 gdb_byte b = buffer[input_index];
4183 if (output_index + 1 > out_maxlen)
4185 warning (_("Received too much data from remote target;"
4186 " ignoring overflow."));
4187 return output_index;
4192 out_buf[output_index++] = b ^ 0x20;
4198 out_buf[output_index++] = b;
4202 error (_("Unmatched escape character in target response."));
4204 return output_index;
4207 /* Determine whether the remote target supports binary downloading.
4208 This is accomplished by sending a no-op memory write of zero length
4209 to the target at the specified address. It does not suffice to send
4210 the whole packet, since many stubs strip the eighth bit and
4211 subsequently compute a wrong checksum, which causes real havoc with
4214 NOTE: This can still lose if the serial line is not eight-bit
4215 clean. In cases like this, the user should clear "remote
4219 check_binary_download (CORE_ADDR addr)
4221 struct remote_state *rs = get_remote_state ();
4223 switch (remote_protocol_packets[PACKET_X].support)
4225 case PACKET_DISABLE:
4229 case PACKET_SUPPORT_UNKNOWN:
4235 p += hexnumstr (p, (ULONGEST) addr);
4237 p += hexnumstr (p, (ULONGEST) 0);
4241 putpkt_binary (rs->buf, (int) (p - rs->buf));
4242 getpkt (&rs->buf, &rs->buf_size, 0);
4244 if (rs->buf[0] == '\0')
4247 fprintf_unfiltered (gdb_stdlog,
4248 "binary downloading NOT suppported by target\n");
4249 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
4254 fprintf_unfiltered (gdb_stdlog,
4255 "binary downloading suppported by target\n");
4256 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
4263 /* Write memory data directly to the remote machine.
4264 This does not inform the data cache; the data cache uses this.
4265 HEADER is the starting part of the packet.
4266 MEMADDR is the address in the remote memory space.
4267 MYADDR is the address of the buffer in our space.
4268 LEN is the number of bytes.
4269 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
4270 should send data as binary ('X'), or hex-encoded ('M').
4272 The function creates packet of the form
4273 <HEADER><ADDRESS>,<LENGTH>:<DATA>
4275 where encoding of <DATA> is termined by PACKET_FORMAT.
4277 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
4280 Returns the number of bytes transferred, or 0 (setting errno) for
4281 error. Only transfer a single packet. */
4284 remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
4285 const gdb_byte *myaddr, int len,
4286 char packet_format, int use_length)
4288 struct remote_state *rs = get_remote_state ();
4298 if (packet_format != 'X' && packet_format != 'M')
4299 internal_error (__FILE__, __LINE__,
4300 "remote_write_bytes_aux: bad packet format");
4305 payload_size = get_memory_write_packet_size ();
4307 /* The packet buffer will be large enough for the payload;
4308 get_memory_packet_size ensures this. */
4311 /* Compute the size of the actual payload by subtracting out the
4312 packet header and footer overhead: "$M<memaddr>,<len>:...#nn".
4314 payload_size -= strlen ("$,:#NN");
4316 /* The comma won't be used. */
4318 header_length = strlen (header);
4319 payload_size -= header_length;
4320 payload_size -= hexnumlen (memaddr);
4322 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
4324 strcat (rs->buf, header);
4325 p = rs->buf + strlen (header);
4327 /* Compute a best guess of the number of bytes actually transfered. */
4328 if (packet_format == 'X')
4330 /* Best guess at number of bytes that will fit. */
4331 todo = min (len, payload_size);
4333 payload_size -= hexnumlen (todo);
4334 todo = min (todo, payload_size);
4338 /* Num bytes that will fit. */
4339 todo = min (len, payload_size / 2);
4341 payload_size -= hexnumlen (todo);
4342 todo = min (todo, payload_size / 2);
4346 internal_error (__FILE__, __LINE__,
4347 _("minumum packet size too small to write data"));
4349 /* If we already need another packet, then try to align the end
4350 of this packet to a useful boundary. */
4351 if (todo > 2 * REMOTE_ALIGN_WRITES && todo < len)
4352 todo = ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
4354 /* Append "<memaddr>". */
4355 memaddr = remote_address_masked (memaddr);
4356 p += hexnumstr (p, (ULONGEST) memaddr);
4363 /* Append <len>. Retain the location/size of <len>. It may need to
4364 be adjusted once the packet body has been created. */
4366 plenlen = hexnumstr (p, (ULONGEST) todo);
4374 /* Append the packet body. */
4375 if (packet_format == 'X')
4377 /* Binary mode. Send target system values byte by byte, in
4378 increasing byte addresses. Only escape certain critical
4380 payload_length = remote_escape_output (myaddr, todo, p, &nr_bytes,
4383 /* If not all TODO bytes fit, then we'll need another packet. Make
4384 a second try to keep the end of the packet aligned. Don't do
4385 this if the packet is tiny. */
4386 if (nr_bytes < todo && nr_bytes > 2 * REMOTE_ALIGN_WRITES)
4390 new_nr_bytes = (((memaddr + nr_bytes) & ~(REMOTE_ALIGN_WRITES - 1))
4392 if (new_nr_bytes != nr_bytes)
4393 payload_length = remote_escape_output (myaddr, new_nr_bytes,
4398 p += payload_length;
4399 if (use_length && nr_bytes < todo)
4401 /* Escape chars have filled up the buffer prematurely,
4402 and we have actually sent fewer bytes than planned.
4403 Fix-up the length field of the packet. Use the same
4404 number of characters as before. */
4405 plen += hexnumnstr (plen, (ULONGEST) nr_bytes, plenlen);
4406 *plen = ':'; /* overwrite \0 from hexnumnstr() */
4411 /* Normal mode: Send target system values byte by byte, in
4412 increasing byte addresses. Each byte is encoded as a two hex
4414 nr_bytes = bin2hex (myaddr, p, todo);
4418 putpkt_binary (rs->buf, (int) (p - rs->buf));
4419 getpkt (&rs->buf, &rs->buf_size, 0);
4421 if (rs->buf[0] == 'E')
4423 /* There is no correspondance between what the remote protocol
4424 uses for errors and errno codes. We would like a cleaner way
4425 of representing errors (big enough to include errno codes,
4426 bfd_error codes, and others). But for now just return EIO. */
4431 /* Return NR_BYTES, not TODO, in case escape chars caused us to send
4432 fewer bytes than we'd planned. */
4436 /* Write memory data directly to the remote machine.
4437 This does not inform the data cache; the data cache uses this.
4438 MEMADDR is the address in the remote memory space.
4439 MYADDR is the address of the buffer in our space.
4440 LEN is the number of bytes.
4442 Returns number of bytes transferred, or 0 (setting errno) for
4443 error. Only transfer a single packet. */
4446 remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, int len)
4448 char *packet_format = 0;
4450 /* Check whether the target supports binary download. */
4451 check_binary_download (memaddr);
4453 switch (remote_protocol_packets[PACKET_X].support)
4456 packet_format = "X";
4458 case PACKET_DISABLE:
4459 packet_format = "M";
4461 case PACKET_SUPPORT_UNKNOWN:
4462 internal_error (__FILE__, __LINE__,
4463 _("remote_write_bytes: bad internal state"));
4465 internal_error (__FILE__, __LINE__, _("bad switch"));
4468 return remote_write_bytes_aux (packet_format,
4469 memaddr, myaddr, len, packet_format[0], 1);
4472 /* Read memory data directly from the remote machine.
4473 This does not use the data cache; the data cache uses this.
4474 MEMADDR is the address in the remote memory space.
4475 MYADDR is the address of the buffer in our space.
4476 LEN is the number of bytes.
4478 Returns number of bytes transferred, or 0 for error. */
4480 /* NOTE: cagney/1999-10-18: This function (and its siblings in other
4481 remote targets) shouldn't attempt to read the entire buffer.
4482 Instead it should read a single packet worth of data and then
4483 return the byte size of that packet to the caller. The caller (its
4484 caller and its callers caller ;-) already contains code for
4485 handling partial reads. */
4488 remote_read_bytes (CORE_ADDR memaddr, gdb_byte *myaddr, int len)
4490 struct remote_state *rs = get_remote_state ();
4491 int max_buf_size; /* Max size of packet output buffer. */
4497 max_buf_size = get_memory_read_packet_size ();
4498 /* The packet buffer will be large enough for the payload;
4499 get_memory_packet_size ensures this. */
4508 todo = min (len, max_buf_size / 2); /* num bytes that will fit */
4510 /* construct "m"<memaddr>","<len>" */
4511 /* sprintf (rs->buf, "m%lx,%x", (unsigned long) memaddr, todo); */
4512 memaddr = remote_address_masked (memaddr);
4515 p += hexnumstr (p, (ULONGEST) memaddr);
4517 p += hexnumstr (p, (ULONGEST) todo);
4521 getpkt (&rs->buf, &rs->buf_size, 0);
4523 if (rs->buf[0] == 'E'
4524 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
4525 && rs->buf[3] == '\0')
4527 /* There is no correspondance between what the remote
4528 protocol uses for errors and errno codes. We would like
4529 a cleaner way of representing errors (big enough to
4530 include errno codes, bfd_error codes, and others). But
4531 for now just return EIO. */
4536 /* Reply describes memory byte by byte,
4537 each byte encoded as two hex characters. */
4540 if ((i = hex2bin (p, myaddr, todo)) < todo)
4542 /* Reply is short. This means that we were able to read
4543 only part of what we wanted to. */
4544 return i + (origlen - len);
4553 /* Read or write LEN bytes from inferior memory at MEMADDR,
4554 transferring to or from debugger address BUFFER. Write to inferior
4555 if SHOULD_WRITE is nonzero. Returns length of data written or
4556 read; 0 for error. TARGET is unused. */
4559 remote_xfer_memory (CORE_ADDR mem_addr, gdb_byte *buffer, int mem_len,
4560 int should_write, struct mem_attrib *attrib,
4561 struct target_ops *target)
4566 res = remote_write_bytes (mem_addr, buffer, mem_len);
4568 res = remote_read_bytes (mem_addr, buffer, mem_len);
4573 /* Sends a packet with content determined by the printf format string
4574 FORMAT and the remaining arguments, then gets the reply. Returns
4575 whether the packet was a success, a failure, or unknown. */
4578 remote_send_printf (const char *format, ...)
4580 struct remote_state *rs = get_remote_state ();
4581 int max_size = get_remote_packet_size ();
4584 va_start (ap, format);
4587 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
4588 internal_error (__FILE__, __LINE__, "Too long remote packet.");
4590 if (putpkt (rs->buf) < 0)
4591 error (_("Communication problem with target."));
4594 getpkt (&rs->buf, &rs->buf_size, 0);
4596 return packet_check_result (rs->buf);
4600 restore_remote_timeout (void *p)
4602 int value = *(int *)p;
4603 remote_timeout = value;
4606 /* Flash writing can take quite some time. We'll set
4607 effectively infinite timeout for flash operations.
4608 In future, we'll need to decide on a better approach. */
4609 static const int remote_flash_timeout = 1000;
4612 remote_flash_erase (struct target_ops *ops,
4613 ULONGEST address, LONGEST length)
4615 int saved_remote_timeout = remote_timeout;
4616 enum packet_result ret;
4618 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
4619 &saved_remote_timeout);
4620 remote_timeout = remote_flash_timeout;
4622 ret = remote_send_printf ("vFlashErase:%s,%s",
4627 case PACKET_UNKNOWN:
4628 error (_("Remote target does not support flash erase"));
4630 error (_("Error erasing flash with vFlashErase packet"));
4635 do_cleanups (back_to);
4639 remote_flash_write (struct target_ops *ops,
4640 ULONGEST address, LONGEST length,
4641 const gdb_byte *data)
4643 int saved_remote_timeout = remote_timeout;
4645 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
4646 &saved_remote_timeout);
4648 remote_timeout = remote_flash_timeout;
4649 ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length, 'X', 0);
4650 do_cleanups (back_to);
4656 remote_flash_done (struct target_ops *ops)
4658 int saved_remote_timeout = remote_timeout;
4660 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
4661 &saved_remote_timeout);
4663 remote_timeout = remote_flash_timeout;
4664 ret = remote_send_printf ("vFlashDone");
4665 do_cleanups (back_to);
4669 case PACKET_UNKNOWN:
4670 error (_("Remote target does not support vFlashDone"));
4672 error (_("Error finishing flash operation"));
4679 remote_files_info (struct target_ops *ignore)
4681 puts_filtered ("Debugging a target over a serial line.\n");
4684 /* Stuff for dealing with the packets which are part of this protocol.
4685 See comment at top of file for details. */
4687 /* Read a single character from the remote end. */
4690 readchar (int timeout)
4694 ch = serial_readchar (remote_desc, timeout);
4699 switch ((enum serial_rc) ch)
4702 target_mourn_inferior ();
4703 error (_("Remote connection closed"));
4706 perror_with_name (_("Remote communication error"));
4708 case SERIAL_TIMEOUT:
4714 /* Send the command in *BUF to the remote machine, and read the reply
4715 into *BUF. Report an error if we get an error reply. Resize
4716 *BUF using xrealloc if necessary to hold the result, and update
4720 remote_send (char **buf,
4724 getpkt (buf, sizeof_buf, 0);
4726 if ((*buf)[0] == 'E')
4727 error (_("Remote failure reply: %s"), *buf);
4730 /* Display a null-terminated packet on stdout, for debugging, using C
4734 print_packet (char *buf)
4736 puts_filtered ("\"");
4737 fputstr_filtered (buf, '"', gdb_stdout);
4738 puts_filtered ("\"");
4744 return putpkt_binary (buf, strlen (buf));
4747 /* Send a packet to the remote machine, with error checking. The data
4748 of the packet is in BUF. The string in BUF can be at most
4749 get_remote_packet_size () - 5 to account for the $, # and checksum,
4750 and for a possible /0 if we are debugging (remote_debug) and want
4751 to print the sent packet as a string. */
4754 putpkt_binary (char *buf, int cnt)
4756 struct remote_state *rs = get_remote_state ();
4758 unsigned char csum = 0;
4759 char *buf2 = alloca (cnt + 6);
4765 /* We're sending out a new packet. Make sure we don't look at a
4766 stale cached response. */
4767 rs->cached_wait_status = 0;
4769 /* Copy the packet into buffer BUF2, encapsulating it
4770 and giving it a checksum. */
4775 for (i = 0; i < cnt; i++)
4781 *p++ = tohex ((csum >> 4) & 0xf);
4782 *p++ = tohex (csum & 0xf);
4784 /* Send it over and over until we get a positive ack. */
4788 int started_error_output = 0;
4793 fprintf_unfiltered (gdb_stdlog, "Sending packet: ");
4794 fputstrn_unfiltered (buf2, p - buf2, 0, gdb_stdlog);
4795 fprintf_unfiltered (gdb_stdlog, "...");
4796 gdb_flush (gdb_stdlog);
4798 if (serial_write (remote_desc, buf2, p - buf2))
4799 perror_with_name (_("putpkt: write failed"));
4801 /* If this is a no acks version of the remote protocol, send the
4802 packet and move on. */
4806 /* Read until either a timeout occurs (-2) or '+' is read. */
4809 ch = readchar (remote_timeout);
4817 case SERIAL_TIMEOUT:
4819 if (started_error_output)
4821 putchar_unfiltered ('\n');
4822 started_error_output = 0;
4831 fprintf_unfiltered (gdb_stdlog, "Ack\n");
4835 fprintf_unfiltered (gdb_stdlog, "Nak\n");
4836 case SERIAL_TIMEOUT:
4840 break; /* Retransmit buffer. */
4844 fprintf_unfiltered (gdb_stdlog,
4845 "Packet instead of Ack, ignoring it\n");
4846 /* It's probably an old response sent because an ACK
4847 was lost. Gobble up the packet and ack it so it
4848 doesn't get retransmitted when we resend this
4851 serial_write (remote_desc, "+", 1);
4852 continue; /* Now, go look for +. */
4857 if (!started_error_output)
4859 started_error_output = 1;
4860 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
4862 fputc_unfiltered (ch & 0177, gdb_stdlog);
4866 break; /* Here to retransmit. */
4870 /* This is wrong. If doing a long backtrace, the user should be
4871 able to get out next time we call QUIT, without anything as
4872 violent as interrupt_query. If we want to provide a way out of
4873 here without getting to the next QUIT, it should be based on
4874 hitting ^C twice as in remote_wait. */
4885 /* Come here after finding the start of a frame when we expected an
4886 ack. Do our best to discard the rest of this packet. */
4895 c = readchar (remote_timeout);
4898 case SERIAL_TIMEOUT:
4899 /* Nothing we can do. */
4902 /* Discard the two bytes of checksum and stop. */
4903 c = readchar (remote_timeout);
4905 c = readchar (remote_timeout);
4908 case '*': /* Run length encoding. */
4909 /* Discard the repeat count. */
4910 c = readchar (remote_timeout);
4915 /* A regular character. */
4921 /* Come here after finding the start of the frame. Collect the rest
4922 into *BUF, verifying the checksum, length, and handling run-length
4923 compression. NUL terminate the buffer. If there is not enough room,
4924 expand *BUF using xrealloc.
4926 Returns -1 on error, number of characters in buffer (ignoring the
4927 trailing NULL) on success. (could be extended to return one of the
4928 SERIAL status indications). */
4931 read_frame (char **buf_p,
4938 struct remote_state *rs = get_remote_state ();
4945 c = readchar (remote_timeout);
4948 case SERIAL_TIMEOUT:
4950 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
4954 fputs_filtered ("Saw new packet start in middle of old one\n",
4956 return -1; /* Start a new packet, count retries. */
4959 unsigned char pktcsum;
4965 check_0 = readchar (remote_timeout);
4967 check_1 = readchar (remote_timeout);
4969 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
4972 fputs_filtered ("Timeout in checksum, retrying\n",
4976 else if (check_0 < 0 || check_1 < 0)
4979 fputs_filtered ("Communication error in checksum\n",
4984 /* Don't recompute the checksum; with no ack packets we
4985 don't have any way to indicate a packet retransmission
4990 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
4991 if (csum == pktcsum)
4996 fprintf_filtered (gdb_stdlog,
4997 "Bad checksum, sentsum=0x%x, csum=0x%x, buf=",
4999 fputstrn_filtered (buf, bc, 0, gdb_stdlog);
5000 fputs_filtered ("\n", gdb_stdlog);
5002 /* Number of characters in buffer ignoring trailing
5006 case '*': /* Run length encoding. */
5011 c = readchar (remote_timeout);
5013 repeat = c - ' ' + 3; /* Compute repeat count. */
5015 /* The character before ``*'' is repeated. */
5017 if (repeat > 0 && repeat <= 255 && bc > 0)
5019 if (bc + repeat - 1 >= *sizeof_buf - 1)
5021 /* Make some more room in the buffer. */
5022 *sizeof_buf += repeat;
5023 *buf_p = xrealloc (*buf_p, *sizeof_buf);
5027 memset (&buf[bc], buf[bc - 1], repeat);
5033 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
5037 if (bc >= *sizeof_buf - 1)
5039 /* Make some more room in the buffer. */
5041 *buf_p = xrealloc (*buf_p, *sizeof_buf);
5052 /* Read a packet from the remote machine, with error checking, and
5053 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
5054 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
5055 rather than timing out; this is used (in synchronous mode) to wait
5056 for a target that is is executing user code to stop. */
5057 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
5058 don't have to change all the calls to getpkt to deal with the
5059 return value, because at the moment I don't know what the right
5060 thing to do it for those. */
5068 timed_out = getpkt_sane (buf, sizeof_buf, forever);
5072 /* Read a packet from the remote machine, with error checking, and
5073 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
5074 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
5075 rather than timing out; this is used (in synchronous mode) to wait
5076 for a target that is is executing user code to stop. If FOREVER ==
5077 0, this function is allowed to time out gracefully and return an
5078 indication of this to the caller. Otherwise return the number
5081 getpkt_sane (char **buf, long *sizeof_buf, int forever)
5083 struct remote_state *rs = get_remote_state ();
5089 /* We're reading a new response. Make sure we don't look at a
5090 previously cached response. */
5091 rs->cached_wait_status = 0;
5093 strcpy (*buf, "timeout");
5097 timeout = watchdog > 0 ? watchdog : -1;
5101 timeout = remote_timeout;
5105 for (tries = 1; tries <= MAX_TRIES; tries++)
5107 /* This can loop forever if the remote side sends us characters
5108 continuously, but if it pauses, we'll get a zero from
5109 readchar because of timeout. Then we'll count that as a
5112 /* Note that we will only wait forever prior to the start of a
5113 packet. After that, we expect characters to arrive at a
5114 brisk pace. They should show up within remote_timeout
5119 c = readchar (timeout);
5121 if (c == SERIAL_TIMEOUT)
5123 if (forever) /* Watchdog went off? Kill the target. */
5126 target_mourn_inferior ();
5127 error (_("Watchdog timeout has expired. Target detached."));
5130 fputs_filtered ("Timed out.\n", gdb_stdlog);
5136 /* We've found the start of a packet, now collect the data. */
5138 val = read_frame (buf, sizeof_buf);
5144 fprintf_unfiltered (gdb_stdlog, "Packet received: ");
5145 fputstrn_unfiltered (*buf, val, 0, gdb_stdlog);
5146 fprintf_unfiltered (gdb_stdlog, "\n");
5149 /* Skip the ack char if we're in no-ack mode. */
5150 if (!rs->noack_mode)
5151 serial_write (remote_desc, "+", 1);
5155 /* Try the whole thing again. */
5157 /* Skip the nack char if we're in no-ack mode. */
5158 if (!rs->noack_mode)
5159 serial_write (remote_desc, "-", 1);
5162 /* We have tried hard enough, and just can't receive the packet.
5165 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
5167 /* Skip the ack char if we're in no-ack mode. */
5168 if (!rs->noack_mode)
5169 serial_write (remote_desc, "+", 1);
5176 /* Unregister the file descriptor from the event loop. */
5177 if (target_is_async_p ())
5178 serial_async (remote_desc, NULL, 0);
5180 /* Use catch_errors so the user can quit from gdb even when we
5181 aren't on speaking terms with the remote system. */
5182 catch_errors ((catch_errors_ftype *) putpkt, "k", "", RETURN_MASK_ERROR);
5184 /* Don't wait for it to die. I'm not really sure it matters whether
5185 we do or not. For the existing stubs, kill is a noop. */
5186 target_mourn_inferior ();
5192 remote_mourn_1 (&remote_ops);
5195 /* Worker function for remote_mourn. */
5197 remote_mourn_1 (struct target_ops *target)
5199 unpush_target (target);
5200 generic_mourn_inferior ();
5204 extended_remote_mourn_1 (struct target_ops *target)
5206 struct remote_state *rs = get_remote_state ();
5208 /* Unlike "target remote", we do not want to unpush the target; then
5209 the next time the user says "run", we won't be connected. */
5211 /* Call common code to mark the inferior as not running. */
5212 generic_mourn_inferior ();
5214 /* Check whether the target is running now - some remote stubs
5215 automatically restart after kill. */
5217 getpkt (&rs->buf, &rs->buf_size, 0);
5219 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
5221 /* Assume that the target has been restarted. Set inferior_ptid
5222 so that bits of core GDB realizes there's something here, e.g.,
5223 so that the user can say "kill" again. */
5224 inferior_ptid = remote_current_thread (magic_null_ptid);
5225 add_thread_silent (inferior_ptid);
5229 /* Mark this (still pushed) target as not executable until we
5231 target_mark_exited (target);
5236 extended_remote_mourn (void)
5238 extended_remote_mourn_1 (&extended_remote_ops);
5242 extended_remote_run (char *args)
5244 struct remote_state *rs = get_remote_state ();
5248 /* If the user has disabled vRun support, or we have detected that
5249 support is not available, do not try it. */
5250 if (remote_protocol_packets[PACKET_vRun].support == PACKET_DISABLE)
5253 strcpy (rs->buf, "vRun;");
5254 len = strlen (rs->buf);
5256 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
5257 error (_("Remote file name too long for run packet"));
5258 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len, 0);
5262 struct cleanup *back_to;
5266 argv = buildargv (args);
5267 back_to = make_cleanup ((void (*) (void *)) freeargv, argv);
5268 for (i = 0; argv[i] != NULL; i++)
5270 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
5271 error (_("Argument list too long for run packet"));
5272 rs->buf[len++] = ';';
5273 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len, 0);
5275 do_cleanups (back_to);
5278 rs->buf[len++] = '\0';
5281 getpkt (&rs->buf, &rs->buf_size, 0);
5283 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]) == PACKET_OK)
5285 /* We have a wait response; we don't need it, though. All is well. */
5288 else if (remote_protocol_packets[PACKET_vRun].support == PACKET_DISABLE)
5289 /* It wasn't disabled before, but it is now. */
5293 if (remote_exec_file[0] == '\0')
5294 error (_("Running the default executable on the remote target failed; "
5295 "try \"set remote exec-file\"?"));
5297 error (_("Running \"%s\" on the remote target failed"),
5302 /* In the extended protocol we want to be able to do things like
5303 "run" and have them basically work as expected. So we need
5304 a special create_inferior function. We support changing the
5305 executable file and the command line arguments, but not the
5309 extended_remote_create_inferior_1 (char *exec_file, char *args,
5310 char **env, int from_tty)
5312 /* If running asynchronously, register the target file descriptor
5313 with the event loop. */
5314 if (target_can_async_p ())
5315 target_async (inferior_event_handler, 0);
5317 /* Now restart the remote server. */
5318 if (extended_remote_run (args) == -1)
5320 /* vRun was not supported. Fail if we need it to do what the
5322 if (remote_exec_file[0])
5323 error (_("Remote target does not support \"set remote exec-file\""));
5325 error (_("Remote target does not support \"set args\" or run <ARGS>"));
5327 /* Fall back to "R". */
5328 extended_remote_restart ();
5331 /* Clean up from the last time we ran, before we mark the target
5332 running again. This will mark breakpoints uninserted, and
5333 get_offsets may insert breakpoints. */
5334 init_thread_list ();
5335 init_wait_for_inferior ();
5337 /* Now mark the inferior as running before we do anything else. */
5339 inferior_ptid = magic_null_ptid;
5341 add_thread_silent (inferior_ptid);
5343 target_mark_running (&extended_remote_ops);
5345 /* Get updated offsets, if the stub uses qOffsets. */
5350 extended_remote_create_inferior (char *exec_file, char *args,
5351 char **env, int from_tty)
5353 extended_remote_create_inferior_1 (exec_file, args, env, from_tty);
5357 /* Insert a breakpoint. On targets that have software breakpoint
5358 support, we ask the remote target to do the work; on targets
5359 which don't, we insert a traditional memory breakpoint. */
5362 remote_insert_breakpoint (struct bp_target_info *bp_tgt)
5364 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
5365 If it succeeds, then set the support to PACKET_ENABLE. If it
5366 fails, and the user has explicitly requested the Z support then
5367 report an error, otherwise, mark it disabled and go on. */
5369 if (remote_protocol_packets[PACKET_Z0].support != PACKET_DISABLE)
5371 CORE_ADDR addr = bp_tgt->placed_address;
5372 struct remote_state *rs;
5376 gdbarch_breakpoint_from_pc (target_gdbarch, &addr, &bpsize);
5378 rs = get_remote_state ();
5384 addr = (ULONGEST) remote_address_masked (addr);
5385 p += hexnumstr (p, addr);
5386 sprintf (p, ",%d", bpsize);
5389 getpkt (&rs->buf, &rs->buf_size, 0);
5391 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
5396 bp_tgt->placed_address = addr;
5397 bp_tgt->placed_size = bpsize;
5399 case PACKET_UNKNOWN:
5404 return memory_insert_breakpoint (bp_tgt);
5408 remote_remove_breakpoint (struct bp_target_info *bp_tgt)
5410 CORE_ADDR addr = bp_tgt->placed_address;
5411 struct remote_state *rs = get_remote_state ();
5414 if (remote_protocol_packets[PACKET_Z0].support != PACKET_DISABLE)
5422 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
5423 p += hexnumstr (p, addr);
5424 sprintf (p, ",%d", bp_tgt->placed_size);
5427 getpkt (&rs->buf, &rs->buf_size, 0);
5429 return (rs->buf[0] == 'E');
5432 return memory_remove_breakpoint (bp_tgt);
5436 watchpoint_to_Z_packet (int type)
5441 return Z_PACKET_WRITE_WP;
5444 return Z_PACKET_READ_WP;
5447 return Z_PACKET_ACCESS_WP;
5450 internal_error (__FILE__, __LINE__,
5451 _("hw_bp_to_z: bad watchpoint type %d"), type);
5456 remote_insert_watchpoint (CORE_ADDR addr, int len, int type)
5458 struct remote_state *rs = get_remote_state ();
5460 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
5462 if (remote_protocol_packets[PACKET_Z0 + packet].support == PACKET_DISABLE)
5465 sprintf (rs->buf, "Z%x,", packet);
5466 p = strchr (rs->buf, '\0');
5467 addr = remote_address_masked (addr);
5468 p += hexnumstr (p, (ULONGEST) addr);
5469 sprintf (p, ",%x", len);
5472 getpkt (&rs->buf, &rs->buf_size, 0);
5474 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
5477 case PACKET_UNKNOWN:
5482 internal_error (__FILE__, __LINE__,
5483 _("remote_insert_watchpoint: reached end of function"));
5488 remote_remove_watchpoint (CORE_ADDR addr, int len, int type)
5490 struct remote_state *rs = get_remote_state ();
5492 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
5494 if (remote_protocol_packets[PACKET_Z0 + packet].support == PACKET_DISABLE)
5497 sprintf (rs->buf, "z%x,", packet);
5498 p = strchr (rs->buf, '\0');
5499 addr = remote_address_masked (addr);
5500 p += hexnumstr (p, (ULONGEST) addr);
5501 sprintf (p, ",%x", len);
5503 getpkt (&rs->buf, &rs->buf_size, 0);
5505 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
5508 case PACKET_UNKNOWN:
5513 internal_error (__FILE__, __LINE__,
5514 _("remote_remove_watchpoint: reached end of function"));
5518 int remote_hw_watchpoint_limit = -1;
5519 int remote_hw_breakpoint_limit = -1;
5522 remote_check_watch_resources (int type, int cnt, int ot)
5524 if (type == bp_hardware_breakpoint)
5526 if (remote_hw_breakpoint_limit == 0)
5528 else if (remote_hw_breakpoint_limit < 0)
5530 else if (cnt <= remote_hw_breakpoint_limit)
5535 if (remote_hw_watchpoint_limit == 0)
5537 else if (remote_hw_watchpoint_limit < 0)
5541 else if (cnt <= remote_hw_watchpoint_limit)
5548 remote_stopped_by_watchpoint (void)
5550 return remote_stopped_by_watchpoint_p;
5554 remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
5557 if (remote_stopped_by_watchpoint ())
5559 *addr_p = remote_watch_data_address;
5568 remote_insert_hw_breakpoint (struct bp_target_info *bp_tgt)
5571 struct remote_state *rs;
5574 /* The length field should be set to the size of a breakpoint
5575 instruction, even though we aren't inserting one ourselves. */
5577 gdbarch_breakpoint_from_pc
5578 (target_gdbarch, &bp_tgt->placed_address, &bp_tgt->placed_size);
5580 if (remote_protocol_packets[PACKET_Z1].support == PACKET_DISABLE)
5583 rs = get_remote_state ();
5590 addr = remote_address_masked (bp_tgt->placed_address);
5591 p += hexnumstr (p, (ULONGEST) addr);
5592 sprintf (p, ",%x", bp_tgt->placed_size);
5595 getpkt (&rs->buf, &rs->buf_size, 0);
5597 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
5600 case PACKET_UNKNOWN:
5605 internal_error (__FILE__, __LINE__,
5606 _("remote_insert_hw_breakpoint: reached end of function"));
5611 remote_remove_hw_breakpoint (struct bp_target_info *bp_tgt)
5614 struct remote_state *rs = get_remote_state ();
5617 if (remote_protocol_packets[PACKET_Z1].support == PACKET_DISABLE)
5624 addr = remote_address_masked (bp_tgt->placed_address);
5625 p += hexnumstr (p, (ULONGEST) addr);
5626 sprintf (p, ",%x", bp_tgt->placed_size);
5629 getpkt (&rs->buf, &rs->buf_size, 0);
5631 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
5634 case PACKET_UNKNOWN:
5639 internal_error (__FILE__, __LINE__,
5640 _("remote_remove_hw_breakpoint: reached end of function"));
5643 /* Some targets are only capable of doing downloads, and afterwards
5644 they switch to the remote serial protocol. This function provides
5645 a clean way to get from the download target to the remote target.
5646 It's basically just a wrapper so that we don't have to expose any
5647 of the internal workings of remote.c.
5649 Prior to calling this routine, you should shutdown the current
5650 target code, else you will get the "A program is being debugged
5651 already..." message. Usually a call to pop_target() suffices. */
5654 push_remote_target (char *name, int from_tty)
5656 printf_filtered (_("Switching to remote protocol\n"));
5657 remote_open (name, from_tty);
5660 /* Table used by the crc32 function to calcuate the checksum. */
5662 static unsigned long crc32_table[256] =
5665 static unsigned long
5666 crc32 (unsigned char *buf, int len, unsigned int crc)
5668 if (!crc32_table[1])
5670 /* Initialize the CRC table and the decoding table. */
5674 for (i = 0; i < 256; i++)
5676 for (c = i << 24, j = 8; j > 0; --j)
5677 c = c & 0x80000000 ? (c << 1) ^ 0x04c11db7 : (c << 1);
5684 crc = (crc << 8) ^ crc32_table[((crc >> 24) ^ *buf) & 255];
5690 /* compare-sections command
5692 With no arguments, compares each loadable section in the exec bfd
5693 with the same memory range on the target, and reports mismatches.
5694 Useful for verifying the image on the target against the exec file.
5695 Depends on the target understanding the new "qCRC:" request. */
5697 /* FIXME: cagney/1999-10-26: This command should be broken down into a
5698 target method (target verify memory) and generic version of the
5699 actual command. This will allow other high-level code (especially
5700 generic_load()) to make use of this target functionality. */
5703 compare_sections_command (char *args, int from_tty)
5705 struct remote_state *rs = get_remote_state ();
5707 unsigned long host_crc, target_crc;
5708 extern bfd *exec_bfd;
5709 struct cleanup *old_chain;
5712 const char *sectname;
5719 error (_("command cannot be used without an exec file"));
5720 if (!current_target.to_shortname ||
5721 strcmp (current_target.to_shortname, "remote") != 0)
5722 error (_("command can only be used with remote target"));
5724 for (s = exec_bfd->sections; s; s = s->next)
5726 if (!(s->flags & SEC_LOAD))
5727 continue; /* skip non-loadable section */
5729 size = bfd_get_section_size (s);
5731 continue; /* skip zero-length section */
5733 sectname = bfd_get_section_name (exec_bfd, s);
5734 if (args && strcmp (args, sectname) != 0)
5735 continue; /* not the section selected by user */
5737 matched = 1; /* do this section */
5739 /* FIXME: assumes lma can fit into long. */
5740 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
5741 (long) lma, (long) size);
5744 /* Be clever; compute the host_crc before waiting for target
5746 sectdata = xmalloc (size);
5747 old_chain = make_cleanup (xfree, sectdata);
5748 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
5749 host_crc = crc32 ((unsigned char *) sectdata, size, 0xffffffff);
5751 getpkt (&rs->buf, &rs->buf_size, 0);
5752 if (rs->buf[0] == 'E')
5753 error (_("target memory fault, section %s, range 0x%s -- 0x%s"),
5754 sectname, paddr (lma), paddr (lma + size));
5755 if (rs->buf[0] != 'C')
5756 error (_("remote target does not support this operation"));
5758 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
5759 target_crc = target_crc * 16 + fromhex (*tmp);
5761 printf_filtered ("Section %s, range 0x%s -- 0x%s: ",
5762 sectname, paddr (lma), paddr (lma + size));
5763 if (host_crc == target_crc)
5764 printf_filtered ("matched.\n");
5767 printf_filtered ("MIS-MATCHED!\n");
5771 do_cleanups (old_chain);
5774 warning (_("One or more sections of the remote executable does not match\n\
5775 the loaded file\n"));
5776 if (args && !matched)
5777 printf_filtered (_("No loaded section named '%s'.\n"), args);
5780 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
5781 into remote target. The number of bytes written to the remote
5782 target is returned, or -1 for error. */
5785 remote_write_qxfer (struct target_ops *ops, const char *object_name,
5786 const char *annex, const gdb_byte *writebuf,
5787 ULONGEST offset, LONGEST len,
5788 struct packet_config *packet)
5793 struct remote_state *rs = get_remote_state ();
5794 int max_size = get_memory_write_packet_size ();
5796 if (packet->support == PACKET_DISABLE)
5799 /* Insert header. */
5800 i = snprintf (rs->buf, max_size,
5801 "qXfer:%s:write:%s:%s:",
5802 object_name, annex ? annex : "",
5803 phex_nz (offset, sizeof offset));
5804 max_size -= (i + 1);
5806 /* Escape as much data as fits into rs->buf. */
5807 buf_len = remote_escape_output
5808 (writebuf, len, (rs->buf + i), &max_size, max_size);
5810 if (putpkt_binary (rs->buf, i + buf_len) < 0
5811 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
5812 || packet_ok (rs->buf, packet) != PACKET_OK)
5815 unpack_varlen_hex (rs->buf, &n);
5819 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
5820 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
5821 number of bytes read is returned, or 0 for EOF, or -1 for error.
5822 The number of bytes read may be less than LEN without indicating an
5823 EOF. PACKET is checked and updated to indicate whether the remote
5824 target supports this object. */
5827 remote_read_qxfer (struct target_ops *ops, const char *object_name,
5829 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
5830 struct packet_config *packet)
5832 static char *finished_object;
5833 static char *finished_annex;
5834 static ULONGEST finished_offset;
5836 struct remote_state *rs = get_remote_state ();
5837 unsigned int total = 0;
5838 LONGEST i, n, packet_len;
5840 if (packet->support == PACKET_DISABLE)
5843 /* Check whether we've cached an end-of-object packet that matches
5845 if (finished_object)
5847 if (strcmp (object_name, finished_object) == 0
5848 && strcmp (annex ? annex : "", finished_annex) == 0
5849 && offset == finished_offset)
5852 /* Otherwise, we're now reading something different. Discard
5854 xfree (finished_object);
5855 xfree (finished_annex);
5856 finished_object = NULL;
5857 finished_annex = NULL;
5860 /* Request only enough to fit in a single packet. The actual data
5861 may not, since we don't know how much of it will need to be escaped;
5862 the target is free to respond with slightly less data. We subtract
5863 five to account for the response type and the protocol frame. */
5864 n = min (get_remote_packet_size () - 5, len);
5865 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
5866 object_name, annex ? annex : "",
5867 phex_nz (offset, sizeof offset),
5868 phex_nz (n, sizeof n));
5869 i = putpkt (rs->buf);
5874 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
5875 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
5878 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
5879 error (_("Unknown remote qXfer reply: %s"), rs->buf);
5881 /* 'm' means there is (or at least might be) more data after this
5882 batch. That does not make sense unless there's at least one byte
5883 of data in this reply. */
5884 if (rs->buf[0] == 'm' && packet_len == 1)
5885 error (_("Remote qXfer reply contained no data."));
5887 /* Got some data. */
5888 i = remote_unescape_input (rs->buf + 1, packet_len - 1, readbuf, n);
5890 /* 'l' is an EOF marker, possibly including a final block of data,
5891 or possibly empty. If we have the final block of a non-empty
5892 object, record this fact to bypass a subsequent partial read. */
5893 if (rs->buf[0] == 'l' && offset + i > 0)
5895 finished_object = xstrdup (object_name);
5896 finished_annex = xstrdup (annex ? annex : "");
5897 finished_offset = offset + i;
5904 remote_xfer_partial (struct target_ops *ops, enum target_object object,
5905 const char *annex, gdb_byte *readbuf,
5906 const gdb_byte *writebuf, ULONGEST offset, LONGEST len)
5908 struct remote_state *rs = get_remote_state ();
5913 /* Handle memory using the standard memory routines. */
5914 if (object == TARGET_OBJECT_MEMORY)
5919 /* If the remote target is connected but not running, we should
5920 pass this request down to a lower stratum (e.g. the executable
5922 if (!target_has_execution)
5925 if (writebuf != NULL)
5926 xfered = remote_write_bytes (offset, writebuf, len);
5928 xfered = remote_read_bytes (offset, readbuf, len);
5932 else if (xfered == 0 && errno == 0)
5938 /* Handle SPU memory using qxfer packets. */
5939 if (object == TARGET_OBJECT_SPU)
5942 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
5943 &remote_protocol_packets
5944 [PACKET_qXfer_spu_read]);
5946 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
5947 &remote_protocol_packets
5948 [PACKET_qXfer_spu_write]);
5951 /* Only handle flash writes. */
5952 if (writebuf != NULL)
5958 case TARGET_OBJECT_FLASH:
5959 xfered = remote_flash_write (ops, offset, len, writebuf);
5963 else if (xfered == 0 && errno == 0)
5973 /* Map pre-existing objects onto letters. DO NOT do this for new
5974 objects!!! Instead specify new query packets. */
5977 case TARGET_OBJECT_AVR:
5981 case TARGET_OBJECT_AUXV:
5982 gdb_assert (annex == NULL);
5983 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
5984 &remote_protocol_packets[PACKET_qXfer_auxv]);
5986 case TARGET_OBJECT_AVAILABLE_FEATURES:
5987 return remote_read_qxfer
5988 (ops, "features", annex, readbuf, offset, len,
5989 &remote_protocol_packets[PACKET_qXfer_features]);
5991 case TARGET_OBJECT_LIBRARIES:
5992 return remote_read_qxfer
5993 (ops, "libraries", annex, readbuf, offset, len,
5994 &remote_protocol_packets[PACKET_qXfer_libraries]);
5996 case TARGET_OBJECT_MEMORY_MAP:
5997 gdb_assert (annex == NULL);
5998 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
5999 &remote_protocol_packets[PACKET_qXfer_memory_map]);
6005 /* Note: a zero OFFSET and LEN can be used to query the minimum
6007 if (offset == 0 && len == 0)
6008 return (get_remote_packet_size ());
6009 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
6010 large enough let the caller deal with it. */
6011 if (len < get_remote_packet_size ())
6013 len = get_remote_packet_size ();
6015 /* Except for querying the minimum buffer size, target must be open. */
6017 error (_("remote query is only available after target open"));
6019 gdb_assert (annex != NULL);
6020 gdb_assert (readbuf != NULL);
6026 /* We used one buffer char for the remote protocol q command and
6027 another for the query type. As the remote protocol encapsulation
6028 uses 4 chars plus one extra in case we are debugging
6029 (remote_debug), we have PBUFZIZ - 7 left to pack the query
6032 while (annex[i] && (i < (get_remote_packet_size () - 8)))
6034 /* Bad caller may have sent forbidden characters. */
6035 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
6040 gdb_assert (annex[i] == '\0');
6042 i = putpkt (rs->buf);
6046 getpkt (&rs->buf, &rs->buf_size, 0);
6047 strcpy ((char *) readbuf, rs->buf);
6049 return strlen ((char *) readbuf);
6053 remote_search_memory (struct target_ops* ops,
6054 CORE_ADDR start_addr, ULONGEST search_space_len,
6055 const gdb_byte *pattern, ULONGEST pattern_len,
6056 CORE_ADDR *found_addrp)
6058 struct remote_state *rs = get_remote_state ();
6059 int max_size = get_memory_write_packet_size ();
6060 struct packet_config *packet =
6061 &remote_protocol_packets[PACKET_qSearch_memory];
6062 /* number of packet bytes used to encode the pattern,
6063 this could be more than PATTERN_LEN due to escape characters */
6064 int escaped_pattern_len;
6065 /* amount of pattern that was encodable in the packet */
6066 int used_pattern_len;
6069 ULONGEST found_addr;
6071 /* Don't go to the target if we don't have to.
6072 This is done before checking packet->support to avoid the possibility that
6073 a success for this edge case means the facility works in general. */
6074 if (pattern_len > search_space_len)
6076 if (pattern_len == 0)
6078 *found_addrp = start_addr;
6082 /* If we already know the packet isn't supported, fall back to the simple
6083 way of searching memory. */
6085 if (packet->support == PACKET_DISABLE)
6087 /* Target doesn't provided special support, fall back and use the
6088 standard support (copy memory and do the search here). */
6089 return simple_search_memory (ops, start_addr, search_space_len,
6090 pattern, pattern_len, found_addrp);
6093 /* Insert header. */
6094 i = snprintf (rs->buf, max_size,
6095 "qSearch:memory:%s;%s;",
6096 paddr_nz (start_addr),
6097 phex_nz (search_space_len, sizeof (search_space_len)));
6098 max_size -= (i + 1);
6100 /* Escape as much data as fits into rs->buf. */
6101 escaped_pattern_len =
6102 remote_escape_output (pattern, pattern_len, (rs->buf + i),
6103 &used_pattern_len, max_size);
6105 /* Bail if the pattern is too large. */
6106 if (used_pattern_len != pattern_len)
6107 error ("Pattern is too large to transmit to remote target.");
6109 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
6110 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
6111 || packet_ok (rs->buf, packet) != PACKET_OK)
6113 /* The request may not have worked because the command is not
6114 supported. If so, fall back to the simple way. */
6115 if (packet->support == PACKET_DISABLE)
6117 return simple_search_memory (ops, start_addr, search_space_len,
6118 pattern, pattern_len, found_addrp);
6123 if (rs->buf[0] == '0')
6125 else if (rs->buf[0] == '1')
6128 if (rs->buf[1] != ',')
6129 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
6130 unpack_varlen_hex (rs->buf + 2, &found_addr);
6131 *found_addrp = found_addr;
6134 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
6140 remote_rcmd (char *command,
6141 struct ui_file *outbuf)
6143 struct remote_state *rs = get_remote_state ();
6147 error (_("remote rcmd is only available after target open"));
6149 /* Send a NULL command across as an empty command. */
6150 if (command == NULL)
6153 /* The query prefix. */
6154 strcpy (rs->buf, "qRcmd,");
6155 p = strchr (rs->buf, '\0');
6157 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/) > get_remote_packet_size ())
6158 error (_("\"monitor\" command ``%s'' is too long."), command);
6160 /* Encode the actual command. */
6161 bin2hex ((gdb_byte *) command, p, 0);
6163 if (putpkt (rs->buf) < 0)
6164 error (_("Communication problem with target."));
6166 /* get/display the response */
6171 /* XXX - see also tracepoint.c:remote_get_noisy_reply(). */
6173 getpkt (&rs->buf, &rs->buf_size, 0);
6176 error (_("Target does not support this command."));
6177 if (buf[0] == 'O' && buf[1] != 'K')
6179 remote_console_output (buf + 1); /* 'O' message from stub. */
6182 if (strcmp (buf, "OK") == 0)
6184 if (strlen (buf) == 3 && buf[0] == 'E'
6185 && isdigit (buf[1]) && isdigit (buf[2]))
6187 error (_("Protocol error with Rcmd"));
6189 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
6191 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
6192 fputc_unfiltered (c, outbuf);
6198 static VEC(mem_region_s) *
6199 remote_memory_map (struct target_ops *ops)
6201 VEC(mem_region_s) *result = NULL;
6202 char *text = target_read_stralloc (¤t_target,
6203 TARGET_OBJECT_MEMORY_MAP, NULL);
6207 struct cleanup *back_to = make_cleanup (xfree, text);
6208 result = parse_memory_map (text);
6209 do_cleanups (back_to);
6216 packet_command (char *args, int from_tty)
6218 struct remote_state *rs = get_remote_state ();
6221 error (_("command can only be used with remote target"));
6224 error (_("remote-packet command requires packet text as argument"));
6226 puts_filtered ("sending: ");
6227 print_packet (args);
6228 puts_filtered ("\n");
6231 getpkt (&rs->buf, &rs->buf_size, 0);
6232 puts_filtered ("received: ");
6233 print_packet (rs->buf);
6234 puts_filtered ("\n");
6238 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
6240 static void display_thread_info (struct gdb_ext_thread_info *info);
6242 static void threadset_test_cmd (char *cmd, int tty);
6244 static void threadalive_test (char *cmd, int tty);
6246 static void threadlist_test_cmd (char *cmd, int tty);
6248 int get_and_display_threadinfo (threadref *ref);
6250 static void threadinfo_test_cmd (char *cmd, int tty);
6252 static int thread_display_step (threadref *ref, void *context);
6254 static void threadlist_update_test_cmd (char *cmd, int tty);
6256 static void init_remote_threadtests (void);
6258 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
6261 threadset_test_cmd (char *cmd, int tty)
6263 int sample_thread = SAMPLE_THREAD;
6265 printf_filtered (_("Remote threadset test\n"));
6266 set_general_thread (sample_thread);
6271 threadalive_test (char *cmd, int tty)
6273 int sample_thread = SAMPLE_THREAD;
6274 int pid = ptid_get_pid (inferior_ptid);
6275 ptid_t ptid = ptid_build (pid, 0, sample_thread);
6277 if (remote_thread_alive (ptid))
6278 printf_filtered ("PASS: Thread alive test\n");
6280 printf_filtered ("FAIL: Thread alive test\n");
6283 void output_threadid (char *title, threadref *ref);
6286 output_threadid (char *title, threadref *ref)
6290 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
6292 printf_filtered ("%s %s\n", title, (&hexid[0]));
6296 threadlist_test_cmd (char *cmd, int tty)
6299 threadref nextthread;
6300 int done, result_count;
6301 threadref threadlist[3];
6303 printf_filtered ("Remote Threadlist test\n");
6304 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
6305 &result_count, &threadlist[0]))
6306 printf_filtered ("FAIL: threadlist test\n");
6309 threadref *scan = threadlist;
6310 threadref *limit = scan + result_count;
6312 while (scan < limit)
6313 output_threadid (" thread ", scan++);
6318 display_thread_info (struct gdb_ext_thread_info *info)
6320 output_threadid ("Threadid: ", &info->threadid);
6321 printf_filtered ("Name: %s\n ", info->shortname);
6322 printf_filtered ("State: %s\n", info->display);
6323 printf_filtered ("other: %s\n\n", info->more_display);
6327 get_and_display_threadinfo (threadref *ref)
6331 struct gdb_ext_thread_info threadinfo;
6333 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
6334 | TAG_MOREDISPLAY | TAG_DISPLAY;
6335 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
6336 display_thread_info (&threadinfo);
6341 threadinfo_test_cmd (char *cmd, int tty)
6343 int athread = SAMPLE_THREAD;
6347 int_to_threadref (&thread, athread);
6348 printf_filtered ("Remote Threadinfo test\n");
6349 if (!get_and_display_threadinfo (&thread))
6350 printf_filtered ("FAIL cannot get thread info\n");
6354 thread_display_step (threadref *ref, void *context)
6356 /* output_threadid(" threadstep ",ref); *//* simple test */
6357 return get_and_display_threadinfo (ref);
6361 threadlist_update_test_cmd (char *cmd, int tty)
6363 printf_filtered ("Remote Threadlist update test\n");
6364 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
6368 init_remote_threadtests (void)
6370 add_com ("tlist", class_obscure, threadlist_test_cmd, _("\
6371 Fetch and print the remote list of thread identifiers, one pkt only"));
6372 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
6373 _("Fetch and display info about one thread"));
6374 add_com ("tset", class_obscure, threadset_test_cmd,
6375 _("Test setting to a different thread"));
6376 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
6377 _("Iterate through updating all remote thread info"));
6378 add_com ("talive", class_obscure, threadalive_test,
6379 _(" Remote thread alive test "));
6384 /* Convert a thread ID to a string. Returns the string in a static
6388 remote_pid_to_str (ptid_t ptid)
6390 static char buf[64];
6392 if (ptid_equal (magic_null_ptid, ptid))
6394 xsnprintf (buf, sizeof buf, "Thread <main>");
6397 else if (ptid_get_tid (ptid) != 0)
6399 xsnprintf (buf, sizeof buf, "Thread %ld",
6400 ptid_get_tid (ptid));
6404 return normal_pid_to_str (ptid);
6407 /* Get the address of the thread local variable in OBJFILE which is
6408 stored at OFFSET within the thread local storage for thread PTID. */
6411 remote_get_thread_local_address (ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
6413 if (remote_protocol_packets[PACKET_qGetTLSAddr].support != PACKET_DISABLE)
6415 struct remote_state *rs = get_remote_state ();
6417 enum packet_result result;
6419 strcpy (p, "qGetTLSAddr:");
6421 p += hexnumstr (p, ptid_get_tid (ptid));
6423 p += hexnumstr (p, offset);
6425 p += hexnumstr (p, lm);
6429 getpkt (&rs->buf, &rs->buf_size, 0);
6430 result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_qGetTLSAddr]);
6431 if (result == PACKET_OK)
6435 unpack_varlen_hex (rs->buf, &result);
6438 else if (result == PACKET_UNKNOWN)
6439 throw_error (TLS_GENERIC_ERROR,
6440 _("Remote target doesn't support qGetTLSAddr packet"));
6442 throw_error (TLS_GENERIC_ERROR,
6443 _("Remote target failed to process qGetTLSAddr request"));
6446 throw_error (TLS_GENERIC_ERROR,
6447 _("TLS not supported or disabled on this target"));
6452 /* Support for inferring a target description based on the current
6453 architecture and the size of a 'g' packet. While the 'g' packet
6454 can have any size (since optional registers can be left off the
6455 end), some sizes are easily recognizable given knowledge of the
6456 approximate architecture. */
6458 struct remote_g_packet_guess
6461 const struct target_desc *tdesc;
6463 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
6464 DEF_VEC_O(remote_g_packet_guess_s);
6466 struct remote_g_packet_data
6468 VEC(remote_g_packet_guess_s) *guesses;
6471 static struct gdbarch_data *remote_g_packet_data_handle;
6474 remote_g_packet_data_init (struct obstack *obstack)
6476 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
6480 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
6481 const struct target_desc *tdesc)
6483 struct remote_g_packet_data *data
6484 = gdbarch_data (gdbarch, remote_g_packet_data_handle);
6485 struct remote_g_packet_guess new_guess, *guess;
6488 gdb_assert (tdesc != NULL);
6491 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
6493 if (guess->bytes == bytes)
6494 internal_error (__FILE__, __LINE__,
6495 "Duplicate g packet description added for size %d",
6498 new_guess.bytes = bytes;
6499 new_guess.tdesc = tdesc;
6500 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
6503 static const struct target_desc *
6504 remote_read_description (struct target_ops *target)
6506 struct remote_g_packet_data *data
6507 = gdbarch_data (target_gdbarch, remote_g_packet_data_handle);
6509 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
6511 struct remote_g_packet_guess *guess;
6513 int bytes = send_g_packet ();
6516 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
6518 if (guess->bytes == bytes)
6519 return guess->tdesc;
6521 /* We discard the g packet. A minor optimization would be to
6522 hold on to it, and fill the register cache once we have selected
6523 an architecture, but it's too tricky to do safely. */
6529 /* Remote file transfer support. This is host-initiated I/O, not
6530 target-initiated; for target-initiated, see remote-fileio.c. */
6532 /* If *LEFT is at least the length of STRING, copy STRING to
6533 *BUFFER, update *BUFFER to point to the new end of the buffer, and
6534 decrease *LEFT. Otherwise raise an error. */
6537 remote_buffer_add_string (char **buffer, int *left, char *string)
6539 int len = strlen (string);
6542 error (_("Packet too long for target."));
6544 memcpy (*buffer, string, len);
6548 /* NUL-terminate the buffer as a convenience, if there is
6554 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
6555 *BUFFER, update *BUFFER to point to the new end of the buffer, and
6556 decrease *LEFT. Otherwise raise an error. */
6559 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
6562 if (2 * len > *left)
6563 error (_("Packet too long for target."));
6565 bin2hex (bytes, *buffer, len);
6569 /* NUL-terminate the buffer as a convenience, if there is
6575 /* If *LEFT is large enough, convert VALUE to hex and add it to
6576 *BUFFER, update *BUFFER to point to the new end of the buffer, and
6577 decrease *LEFT. Otherwise raise an error. */
6580 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
6582 int len = hexnumlen (value);
6585 error (_("Packet too long for target."));
6587 hexnumstr (*buffer, value);
6591 /* NUL-terminate the buffer as a convenience, if there is
6597 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
6598 value, *REMOTE_ERRNO to the remote error number or zero if none
6599 was included, and *ATTACHMENT to point to the start of the annex
6600 if any. The length of the packet isn't needed here; there may
6601 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
6603 Return 0 if the packet could be parsed, -1 if it could not. If
6604 -1 is returned, the other variables may not be initialized. */
6607 remote_hostio_parse_result (char *buffer, int *retcode,
6608 int *remote_errno, char **attachment)
6615 if (buffer[0] != 'F')
6619 *retcode = strtol (&buffer[1], &p, 16);
6620 if (errno != 0 || p == &buffer[1])
6623 /* Check for ",errno". */
6627 *remote_errno = strtol (p + 1, &p2, 16);
6628 if (errno != 0 || p + 1 == p2)
6633 /* Check for ";attachment". If there is no attachment, the
6634 packet should end here. */
6637 *attachment = p + 1;
6640 else if (*p == '\0')
6646 /* Send a prepared I/O packet to the target and read its response.
6647 The prepared packet is in the global RS->BUF before this function
6648 is called, and the answer is there when we return.
6650 COMMAND_BYTES is the length of the request to send, which may include
6651 binary data. WHICH_PACKET is the packet configuration to check
6652 before attempting a packet. If an error occurs, *REMOTE_ERRNO
6653 is set to the error number and -1 is returned. Otherwise the value
6654 returned by the function is returned.
6656 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
6657 attachment is expected; an error will be reported if there's a
6658 mismatch. If one is found, *ATTACHMENT will be set to point into
6659 the packet buffer and *ATTACHMENT_LEN will be set to the
6660 attachment's length. */
6663 remote_hostio_send_command (int command_bytes, int which_packet,
6664 int *remote_errno, char **attachment,
6665 int *attachment_len)
6667 struct remote_state *rs = get_remote_state ();
6668 int ret, bytes_read;
6669 char *attachment_tmp;
6672 || remote_protocol_packets[which_packet].support == PACKET_DISABLE)
6674 *remote_errno = FILEIO_ENOSYS;
6678 putpkt_binary (rs->buf, command_bytes);
6679 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
6681 /* If it timed out, something is wrong. Don't try to parse the
6685 *remote_errno = FILEIO_EINVAL;
6689 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
6692 *remote_errno = FILEIO_EINVAL;
6694 case PACKET_UNKNOWN:
6695 *remote_errno = FILEIO_ENOSYS;
6701 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
6704 *remote_errno = FILEIO_EINVAL;
6708 /* Make sure we saw an attachment if and only if we expected one. */
6709 if ((attachment_tmp == NULL && attachment != NULL)
6710 || (attachment_tmp != NULL && attachment == NULL))
6712 *remote_errno = FILEIO_EINVAL;
6716 /* If an attachment was found, it must point into the packet buffer;
6717 work out how many bytes there were. */
6718 if (attachment_tmp != NULL)
6720 *attachment = attachment_tmp;
6721 *attachment_len = bytes_read - (*attachment - rs->buf);
6727 /* Open FILENAME on the remote target, using FLAGS and MODE. Return a
6728 remote file descriptor, or -1 if an error occurs (and set
6732 remote_hostio_open (const char *filename, int flags, int mode,
6735 struct remote_state *rs = get_remote_state ();
6737 int left = get_remote_packet_size () - 1;
6739 remote_buffer_add_string (&p, &left, "vFile:open:");
6741 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
6743 remote_buffer_add_string (&p, &left, ",");
6745 remote_buffer_add_int (&p, &left, flags);
6746 remote_buffer_add_string (&p, &left, ",");
6748 remote_buffer_add_int (&p, &left, mode);
6750 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
6751 remote_errno, NULL, NULL);
6754 /* Write up to LEN bytes from WRITE_BUF to FD on the remote target.
6755 Return the number of bytes written, or -1 if an error occurs (and
6756 set *REMOTE_ERRNO). */
6759 remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
6760 ULONGEST offset, int *remote_errno)
6762 struct remote_state *rs = get_remote_state ();
6764 int left = get_remote_packet_size ();
6767 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
6769 remote_buffer_add_int (&p, &left, fd);
6770 remote_buffer_add_string (&p, &left, ",");
6772 remote_buffer_add_int (&p, &left, offset);
6773 remote_buffer_add_string (&p, &left, ",");
6775 p += remote_escape_output (write_buf, len, p, &out_len,
6776 get_remote_packet_size () - (p - rs->buf));
6778 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
6779 remote_errno, NULL, NULL);
6782 /* Read up to LEN bytes FD on the remote target into READ_BUF
6783 Return the number of bytes read, or -1 if an error occurs (and
6784 set *REMOTE_ERRNO). */
6787 remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
6788 ULONGEST offset, int *remote_errno)
6790 struct remote_state *rs = get_remote_state ();
6793 int left = get_remote_packet_size ();
6794 int ret, attachment_len;
6797 remote_buffer_add_string (&p, &left, "vFile:pread:");
6799 remote_buffer_add_int (&p, &left, fd);
6800 remote_buffer_add_string (&p, &left, ",");
6802 remote_buffer_add_int (&p, &left, len);
6803 remote_buffer_add_string (&p, &left, ",");
6805 remote_buffer_add_int (&p, &left, offset);
6807 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
6808 remote_errno, &attachment,
6814 read_len = remote_unescape_input (attachment, attachment_len,
6816 if (read_len != ret)
6817 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
6822 /* Close FD on the remote target. Return 0, or -1 if an error occurs
6823 (and set *REMOTE_ERRNO). */
6826 remote_hostio_close (int fd, int *remote_errno)
6828 struct remote_state *rs = get_remote_state ();
6830 int left = get_remote_packet_size () - 1;
6832 remote_buffer_add_string (&p, &left, "vFile:close:");
6834 remote_buffer_add_int (&p, &left, fd);
6836 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
6837 remote_errno, NULL, NULL);
6840 /* Unlink FILENAME on the remote target. Return 0, or -1 if an error
6841 occurs (and set *REMOTE_ERRNO). */
6844 remote_hostio_unlink (const char *filename, int *remote_errno)
6846 struct remote_state *rs = get_remote_state ();
6848 int left = get_remote_packet_size () - 1;
6850 remote_buffer_add_string (&p, &left, "vFile:unlink:");
6852 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
6855 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
6856 remote_errno, NULL, NULL);
6860 remote_fileio_errno_to_host (int errnum)
6884 case FILEIO_ENOTDIR:
6904 case FILEIO_ENAMETOOLONG:
6905 return ENAMETOOLONG;
6911 remote_hostio_error (int errnum)
6913 int host_error = remote_fileio_errno_to_host (errnum);
6915 if (host_error == -1)
6916 error (_("Unknown remote I/O error %d"), errnum);
6918 error (_("Remote I/O error: %s"), safe_strerror (host_error));
6922 fclose_cleanup (void *file)
6928 remote_hostio_close_cleanup (void *opaque)
6930 int fd = *(int *) opaque;
6933 remote_hostio_close (fd, &remote_errno);
6938 remote_bfd_iovec_open (struct bfd *abfd, void *open_closure)
6940 const char *filename = bfd_get_filename (abfd);
6941 int fd, remote_errno;
6944 gdb_assert (remote_filename_p (filename));
6946 fd = remote_hostio_open (filename + 7, FILEIO_O_RDONLY, 0, &remote_errno);
6949 errno = remote_fileio_errno_to_host (remote_errno);
6950 bfd_set_error (bfd_error_system_call);
6954 stream = xmalloc (sizeof (int));
6960 remote_bfd_iovec_close (struct bfd *abfd, void *stream)
6962 int fd = *(int *)stream;
6967 /* Ignore errors on close; these may happen if the remote
6968 connection was already torn down. */
6969 remote_hostio_close (fd, &remote_errno);
6975 remote_bfd_iovec_pread (struct bfd *abfd, void *stream, void *buf,
6976 file_ptr nbytes, file_ptr offset)
6978 int fd = *(int *)stream;
6980 file_ptr pos, bytes;
6983 while (nbytes > pos)
6985 bytes = remote_hostio_pread (fd, (char *)buf + pos, nbytes - pos,
6986 offset + pos, &remote_errno);
6988 /* Success, but no bytes, means end-of-file. */
6992 errno = remote_fileio_errno_to_host (remote_errno);
6993 bfd_set_error (bfd_error_system_call);
7004 remote_bfd_iovec_stat (struct bfd *abfd, void *stream, struct stat *sb)
7006 /* FIXME: We should probably implement remote_hostio_stat. */
7007 sb->st_size = INT_MAX;
7012 remote_filename_p (const char *filename)
7014 return strncmp (filename, "remote:", 7) == 0;
7018 remote_bfd_open (const char *remote_file, const char *target)
7020 return bfd_openr_iovec (remote_file, target,
7021 remote_bfd_iovec_open, NULL,
7022 remote_bfd_iovec_pread,
7023 remote_bfd_iovec_close,
7024 remote_bfd_iovec_stat);
7028 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
7030 struct cleanup *back_to, *close_cleanup;
7031 int retcode, fd, remote_errno, bytes, io_size;
7034 int bytes_in_buffer;
7039 error (_("command can only be used with remote target"));
7041 file = fopen (local_file, "rb");
7043 perror_with_name (local_file);
7044 back_to = make_cleanup (fclose_cleanup, file);
7046 fd = remote_hostio_open (remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
7048 0700, &remote_errno);
7050 remote_hostio_error (remote_errno);
7052 /* Send up to this many bytes at once. They won't all fit in the
7053 remote packet limit, so we'll transfer slightly fewer. */
7054 io_size = get_remote_packet_size ();
7055 buffer = xmalloc (io_size);
7056 make_cleanup (xfree, buffer);
7058 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
7060 bytes_in_buffer = 0;
7063 while (bytes_in_buffer || !saw_eof)
7067 bytes = fread (buffer + bytes_in_buffer, 1, io_size - bytes_in_buffer,
7072 error (_("Error reading %s."), local_file);
7075 /* EOF. Unless there is something still in the
7076 buffer from the last iteration, we are done. */
7078 if (bytes_in_buffer == 0)
7086 bytes += bytes_in_buffer;
7087 bytes_in_buffer = 0;
7089 retcode = remote_hostio_pwrite (fd, buffer, bytes, offset, &remote_errno);
7092 remote_hostio_error (remote_errno);
7093 else if (retcode == 0)
7094 error (_("Remote write of %d bytes returned 0!"), bytes);
7095 else if (retcode < bytes)
7097 /* Short write. Save the rest of the read data for the next
7099 bytes_in_buffer = bytes - retcode;
7100 memmove (buffer, buffer + retcode, bytes_in_buffer);
7106 discard_cleanups (close_cleanup);
7107 if (remote_hostio_close (fd, &remote_errno))
7108 remote_hostio_error (remote_errno);
7111 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
7112 do_cleanups (back_to);
7116 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
7118 struct cleanup *back_to, *close_cleanup;
7119 int retcode, fd, remote_errno, bytes, io_size;
7125 error (_("command can only be used with remote target"));
7127 fd = remote_hostio_open (remote_file, FILEIO_O_RDONLY, 0, &remote_errno);
7129 remote_hostio_error (remote_errno);
7131 file = fopen (local_file, "wb");
7133 perror_with_name (local_file);
7134 back_to = make_cleanup (fclose_cleanup, file);
7136 /* Send up to this many bytes at once. They won't all fit in the
7137 remote packet limit, so we'll transfer slightly fewer. */
7138 io_size = get_remote_packet_size ();
7139 buffer = xmalloc (io_size);
7140 make_cleanup (xfree, buffer);
7142 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
7147 bytes = remote_hostio_pread (fd, buffer, io_size, offset, &remote_errno);
7149 /* Success, but no bytes, means end-of-file. */
7152 remote_hostio_error (remote_errno);
7156 bytes = fwrite (buffer, 1, bytes, file);
7158 perror_with_name (local_file);
7161 discard_cleanups (close_cleanup);
7162 if (remote_hostio_close (fd, &remote_errno))
7163 remote_hostio_error (remote_errno);
7166 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
7167 do_cleanups (back_to);
7171 remote_file_delete (const char *remote_file, int from_tty)
7173 int retcode, remote_errno;
7176 error (_("command can only be used with remote target"));
7178 retcode = remote_hostio_unlink (remote_file, &remote_errno);
7180 remote_hostio_error (remote_errno);
7183 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
7187 remote_put_command (char *args, int from_tty)
7189 struct cleanup *back_to;
7192 argv = buildargv (args);
7195 back_to = make_cleanup_freeargv (argv);
7196 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
7197 error (_("Invalid parameters to remote put"));
7199 remote_file_put (argv[0], argv[1], from_tty);
7201 do_cleanups (back_to);
7205 remote_get_command (char *args, int from_tty)
7207 struct cleanup *back_to;
7210 argv = buildargv (args);
7213 back_to = make_cleanup_freeargv (argv);
7214 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
7215 error (_("Invalid parameters to remote get"));
7217 remote_file_get (argv[0], argv[1], from_tty);
7219 do_cleanups (back_to);
7223 remote_delete_command (char *args, int from_tty)
7225 struct cleanup *back_to;
7228 argv = buildargv (args);
7231 back_to = make_cleanup_freeargv (argv);
7232 if (argv[0] == NULL || argv[1] != NULL)
7233 error (_("Invalid parameters to remote delete"));
7235 remote_file_delete (argv[0], from_tty);
7237 do_cleanups (back_to);
7241 remote_command (char *args, int from_tty)
7243 help_list (remote_cmdlist, "remote ", -1, gdb_stdout);
7247 init_remote_ops (void)
7249 remote_ops.to_shortname = "remote";
7250 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
7252 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
7253 Specify the serial device it is connected to\n\
7254 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
7255 remote_ops.to_open = remote_open;
7256 remote_ops.to_close = remote_close;
7257 remote_ops.to_detach = remote_detach;
7258 remote_ops.to_disconnect = remote_disconnect;
7259 remote_ops.to_resume = remote_resume;
7260 remote_ops.to_wait = remote_wait;
7261 remote_ops.to_fetch_registers = remote_fetch_registers;
7262 remote_ops.to_store_registers = remote_store_registers;
7263 remote_ops.to_prepare_to_store = remote_prepare_to_store;
7264 remote_ops.deprecated_xfer_memory = remote_xfer_memory;
7265 remote_ops.to_files_info = remote_files_info;
7266 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
7267 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
7268 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
7269 remote_ops.to_stopped_data_address = remote_stopped_data_address;
7270 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
7271 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
7272 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
7273 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
7274 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
7275 remote_ops.to_kill = remote_kill;
7276 remote_ops.to_load = generic_load;
7277 remote_ops.to_mourn_inferior = remote_mourn;
7278 remote_ops.to_thread_alive = remote_thread_alive;
7279 remote_ops.to_find_new_threads = remote_threads_info;
7280 remote_ops.to_pid_to_str = remote_pid_to_str;
7281 remote_ops.to_extra_thread_info = remote_threads_extra_info;
7282 remote_ops.to_stop = remote_stop;
7283 remote_ops.to_xfer_partial = remote_xfer_partial;
7284 remote_ops.to_rcmd = remote_rcmd;
7285 remote_ops.to_log_command = serial_log_command;
7286 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
7287 remote_ops.to_stratum = process_stratum;
7288 remote_ops.to_has_all_memory = 1;
7289 remote_ops.to_has_memory = 1;
7290 remote_ops.to_has_stack = 1;
7291 remote_ops.to_has_registers = 1;
7292 remote_ops.to_has_execution = 1;
7293 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
7294 remote_ops.to_magic = OPS_MAGIC;
7295 remote_ops.to_memory_map = remote_memory_map;
7296 remote_ops.to_flash_erase = remote_flash_erase;
7297 remote_ops.to_flash_done = remote_flash_done;
7298 remote_ops.to_read_description = remote_read_description;
7299 remote_ops.to_search_memory = remote_search_memory;
7300 remote_ops.to_can_async_p = remote_can_async_p;
7301 remote_ops.to_is_async_p = remote_is_async_p;
7302 remote_ops.to_async = remote_async;
7303 remote_ops.to_async_mask = remote_async_mask;
7304 remote_ops.to_terminal_inferior = remote_terminal_inferior;
7305 remote_ops.to_terminal_ours = remote_terminal_ours;
7308 /* Set up the extended remote vector by making a copy of the standard
7309 remote vector and adding to it. */
7312 init_extended_remote_ops (void)
7314 extended_remote_ops = remote_ops;
7316 extended_remote_ops.to_shortname = "extended-remote";
7317 extended_remote_ops.to_longname =
7318 "Extended remote serial target in gdb-specific protocol";
7319 extended_remote_ops.to_doc =
7320 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
7321 Specify the serial device it is connected to (e.g. /dev/ttya).";
7322 extended_remote_ops.to_open = extended_remote_open;
7323 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
7324 extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
7325 extended_remote_ops.to_detach = extended_remote_detach;
7326 extended_remote_ops.to_attach = extended_remote_attach;
7330 remote_can_async_p (void)
7332 if (!target_async_permitted)
7333 /* We only enable async when the user specifically asks for it. */
7336 /* We're async whenever the serial device is. */
7337 return remote_async_mask_value && serial_can_async_p (remote_desc);
7341 remote_is_async_p (void)
7343 if (!target_async_permitted)
7344 /* We only enable async when the user specifically asks for it. */
7347 /* We're async whenever the serial device is. */
7348 return remote_async_mask_value && serial_is_async_p (remote_desc);
7351 /* Pass the SERIAL event on and up to the client. One day this code
7352 will be able to delay notifying the client of an event until the
7353 point where an entire packet has been received. */
7355 static void (*async_client_callback) (enum inferior_event_type event_type,
7357 static void *async_client_context;
7358 static serial_event_ftype remote_async_serial_handler;
7361 remote_async_serial_handler (struct serial *scb, void *context)
7363 /* Don't propogate error information up to the client. Instead let
7364 the client find out about the error by querying the target. */
7365 async_client_callback (INF_REG_EVENT, async_client_context);
7369 remote_async (void (*callback) (enum inferior_event_type event_type,
7370 void *context), void *context)
7372 if (remote_async_mask_value == 0)
7373 internal_error (__FILE__, __LINE__,
7374 _("Calling remote_async when async is masked"));
7376 if (callback != NULL)
7378 serial_async (remote_desc, remote_async_serial_handler, NULL);
7379 async_client_callback = callback;
7380 async_client_context = context;
7383 serial_async (remote_desc, NULL, NULL);
7387 remote_async_mask (int new_mask)
7389 int curr_mask = remote_async_mask_value;
7390 remote_async_mask_value = new_mask;
7395 set_remote_cmd (char *args, int from_tty)
7397 help_list (remote_set_cmdlist, "set remote ", -1, gdb_stdout);
7401 show_remote_cmd (char *args, int from_tty)
7403 /* We can't just use cmd_show_list here, because we want to skip
7404 the redundant "show remote Z-packet" and the legacy aliases. */
7405 struct cleanup *showlist_chain;
7406 struct cmd_list_element *list = remote_show_cmdlist;
7408 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
7409 for (; list != NULL; list = list->next)
7410 if (strcmp (list->name, "Z-packet") == 0)
7412 else if (list->type == not_set_cmd)
7413 /* Alias commands are exactly like the original, except they
7414 don't have the normal type. */
7418 struct cleanup *option_chain
7419 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
7420 ui_out_field_string (uiout, "name", list->name);
7421 ui_out_text (uiout, ": ");
7422 if (list->type == show_cmd)
7423 do_setshow_command ((char *) NULL, from_tty, list);
7425 cmd_func (list, NULL, from_tty);
7426 /* Close the tuple. */
7427 do_cleanups (option_chain);
7430 /* Close the tuple. */
7431 do_cleanups (showlist_chain);
7435 /* Function to be called whenever a new objfile (shlib) is detected. */
7437 remote_new_objfile (struct objfile *objfile)
7439 if (remote_desc != 0) /* Have a remote connection. */
7440 remote_check_symbols (objfile);
7444 _initialize_remote (void)
7446 struct remote_state *rs;
7448 /* architecture specific data */
7449 remote_gdbarch_data_handle =
7450 gdbarch_data_register_post_init (init_remote_state);
7451 remote_g_packet_data_handle =
7452 gdbarch_data_register_pre_init (remote_g_packet_data_init);
7454 /* Initialize the per-target state. At the moment there is only one
7455 of these, not one per target. Only one target is active at a
7456 time. The default buffer size is unimportant; it will be expanded
7457 whenever a larger buffer is needed. */
7458 rs = get_remote_state_raw ();
7460 rs->buf = xmalloc (rs->buf_size);
7463 add_target (&remote_ops);
7465 init_extended_remote_ops ();
7466 add_target (&extended_remote_ops);
7468 /* Hook into new objfile notification. */
7469 observer_attach_new_objfile (remote_new_objfile);
7471 /* Set up signal handlers. */
7472 sigint_remote_token =
7473 create_async_signal_handler (async_remote_interrupt, NULL);
7474 sigint_remote_twice_token =
7475 create_async_signal_handler (inferior_event_handler_wrapper, NULL);
7478 init_remote_threadtests ();
7481 /* set/show remote ... */
7483 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
7484 Remote protocol specific variables\n\
7485 Configure various remote-protocol specific variables such as\n\
7486 the packets being used"),
7487 &remote_set_cmdlist, "set remote ",
7488 0 /* allow-unknown */, &setlist);
7489 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
7490 Remote protocol specific variables\n\
7491 Configure various remote-protocol specific variables such as\n\
7492 the packets being used"),
7493 &remote_show_cmdlist, "show remote ",
7494 0 /* allow-unknown */, &showlist);
7496 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
7497 Compare section data on target to the exec file.\n\
7498 Argument is a single section name (default: all loaded sections)."),
7501 add_cmd ("packet", class_maintenance, packet_command, _("\
7502 Send an arbitrary packet to a remote target.\n\
7503 maintenance packet TEXT\n\
7504 If GDB is talking to an inferior via the GDB serial protocol, then\n\
7505 this command sends the string TEXT to the inferior, and displays the\n\
7506 response packet. GDB supplies the initial `$' character, and the\n\
7507 terminating `#' character and checksum."),
7510 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
7511 Set whether to send break if interrupted."), _("\
7512 Show whether to send break if interrupted."), _("\
7513 If set, a break, instead of a cntrl-c, is sent to the remote target."),
7514 NULL, NULL, /* FIXME: i18n: Whether to send break if interrupted is %s. */
7515 &setlist, &showlist);
7517 /* Install commands for configuring memory read/write packets. */
7519 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
7520 Set the maximum number of bytes per memory write packet (deprecated)."),
7522 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
7523 Show the maximum number of bytes per memory write packet (deprecated)."),
7525 add_cmd ("memory-write-packet-size", no_class,
7526 set_memory_write_packet_size, _("\
7527 Set the maximum number of bytes per memory-write packet.\n\
7528 Specify the number of bytes in a packet or 0 (zero) for the\n\
7529 default packet size. The actual limit is further reduced\n\
7530 dependent on the target. Specify ``fixed'' to disable the\n\
7531 further restriction and ``limit'' to enable that restriction."),
7532 &remote_set_cmdlist);
7533 add_cmd ("memory-read-packet-size", no_class,
7534 set_memory_read_packet_size, _("\
7535 Set the maximum number of bytes per memory-read packet.\n\
7536 Specify the number of bytes in a packet or 0 (zero) for the\n\
7537 default packet size. The actual limit is further reduced\n\
7538 dependent on the target. Specify ``fixed'' to disable the\n\
7539 further restriction and ``limit'' to enable that restriction."),
7540 &remote_set_cmdlist);
7541 add_cmd ("memory-write-packet-size", no_class,
7542 show_memory_write_packet_size,
7543 _("Show the maximum number of bytes per memory-write packet."),
7544 &remote_show_cmdlist);
7545 add_cmd ("memory-read-packet-size", no_class,
7546 show_memory_read_packet_size,
7547 _("Show the maximum number of bytes per memory-read packet."),
7548 &remote_show_cmdlist);
7550 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
7551 &remote_hw_watchpoint_limit, _("\
7552 Set the maximum number of target hardware watchpoints."), _("\
7553 Show the maximum number of target hardware watchpoints."), _("\
7554 Specify a negative limit for unlimited."),
7555 NULL, NULL, /* FIXME: i18n: The maximum number of target hardware watchpoints is %s. */
7556 &remote_set_cmdlist, &remote_show_cmdlist);
7557 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
7558 &remote_hw_breakpoint_limit, _("\
7559 Set the maximum number of target hardware breakpoints."), _("\
7560 Show the maximum number of target hardware breakpoints."), _("\
7561 Specify a negative limit for unlimited."),
7562 NULL, NULL, /* FIXME: i18n: The maximum number of target hardware breakpoints is %s. */
7563 &remote_set_cmdlist, &remote_show_cmdlist);
7565 add_setshow_integer_cmd ("remoteaddresssize", class_obscure,
7566 &remote_address_size, _("\
7567 Set the maximum size of the address (in bits) in a memory packet."), _("\
7568 Show the maximum size of the address (in bits) in a memory packet."), NULL,
7570 NULL, /* FIXME: i18n: */
7571 &setlist, &showlist);
7573 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
7574 "X", "binary-download", 1);
7576 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
7577 "vCont", "verbose-resume", 0);
7579 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
7580 "QPassSignals", "pass-signals", 0);
7582 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
7583 "qSymbol", "symbol-lookup", 0);
7585 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
7586 "P", "set-register", 1);
7588 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
7589 "p", "fetch-register", 1);
7591 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
7592 "Z0", "software-breakpoint", 0);
7594 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
7595 "Z1", "hardware-breakpoint", 0);
7597 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
7598 "Z2", "write-watchpoint", 0);
7600 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
7601 "Z3", "read-watchpoint", 0);
7603 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
7604 "Z4", "access-watchpoint", 0);
7606 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
7607 "qXfer:auxv:read", "read-aux-vector", 0);
7609 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
7610 "qXfer:features:read", "target-features", 0);
7612 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
7613 "qXfer:libraries:read", "library-info", 0);
7615 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
7616 "qXfer:memory-map:read", "memory-map", 0);
7618 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
7619 "qXfer:spu:read", "read-spu-object", 0);
7621 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
7622 "qXfer:spu:write", "write-spu-object", 0);
7624 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
7625 "qGetTLSAddr", "get-thread-local-storage-address",
7628 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
7629 "qSupported", "supported-packets", 0);
7631 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
7632 "qSearch:memory", "search-memory", 0);
7634 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
7635 "vFile:open", "hostio-open", 0);
7637 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
7638 "vFile:pread", "hostio-pread", 0);
7640 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
7641 "vFile:pwrite", "hostio-pwrite", 0);
7643 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
7644 "vFile:close", "hostio-close", 0);
7646 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
7647 "vFile:unlink", "hostio-unlink", 0);
7649 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
7650 "vAttach", "attach", 0);
7652 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
7655 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
7656 "QStartNoAckMode", "noack", 0);
7658 /* Keep the old ``set remote Z-packet ...'' working. Each individual
7659 Z sub-packet has its own set and show commands, but users may
7660 have sets to this variable in their .gdbinit files (or in their
7662 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
7663 &remote_Z_packet_detect, _("\
7664 Set use of remote protocol `Z' packets"), _("\
7665 Show use of remote protocol `Z' packets "), _("\
7666 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
7668 set_remote_protocol_Z_packet_cmd,
7669 show_remote_protocol_Z_packet_cmd, /* FIXME: i18n: Use of remote protocol `Z' packets is %s. */
7670 &remote_set_cmdlist, &remote_show_cmdlist);
7672 add_prefix_cmd ("remote", class_files, remote_command, _("\
7673 Manipulate files on the remote system\n\
7674 Transfer files to and from the remote target system."),
7675 &remote_cmdlist, "remote ",
7676 0 /* allow-unknown */, &cmdlist);
7678 add_cmd ("put", class_files, remote_put_command,
7679 _("Copy a local file to the remote system."),
7682 add_cmd ("get", class_files, remote_get_command,
7683 _("Copy a remote file to the local system."),
7686 add_cmd ("delete", class_files, remote_delete_command,
7687 _("Delete a remote file."),
7690 remote_exec_file = xstrdup ("");
7691 add_setshow_string_noescape_cmd ("exec-file", class_files,
7692 &remote_exec_file, _("\
7693 Set the remote pathname for \"run\""), _("\
7694 Show the remote pathname for \"run\""), NULL, NULL, NULL,
7695 &remote_set_cmdlist, &remote_show_cmdlist);
7697 /* Eventually initialize fileio. See fileio.c */
7698 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
7700 /* Take advantage of the fact that the LWP field is not used, to tag
7701 special ptids with it set to != 0. */
7702 magic_null_ptid = ptid_build (0, 1, -1);
7703 not_sent_ptid = ptid_build (0, 1, -2);
7704 any_thread_ptid = ptid_build (0, 1, 0);