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"
64 #include "memory-map.h"
66 /* The size to align memory write packets, when practical. The protocol
67 does not guarantee any alignment, and gdb will generate short
68 writes and unaligned writes, but even as a best-effort attempt this
69 can improve bulk transfers. For instance, if a write is misaligned
70 relative to the target's data bus, the stub may need to make an extra
71 round trip fetching data from the target. This doesn't make a
72 huge difference, but it's easy to do, so we try to be helpful.
74 The alignment chosen is arbitrary; usually data bus width is
75 important here, not the possibly larger cache line size. */
76 enum { REMOTE_ALIGN_WRITES = 16 };
78 /* Prototypes for local functions. */
79 static void cleanup_sigint_signal_handler (void *dummy);
80 static void initialize_sigint_signal_handler (void);
81 static int getpkt_sane (char **buf, long *sizeof_buf, int forever);
83 static void handle_remote_sigint (int);
84 static void handle_remote_sigint_twice (int);
85 static void async_remote_interrupt (gdb_client_data);
86 void async_remote_interrupt_twice (gdb_client_data);
88 static void remote_files_info (struct target_ops *ignore);
90 static void remote_prepare_to_store (struct regcache *regcache);
92 static void remote_fetch_registers (struct regcache *regcache, int regno);
94 static void remote_resume (ptid_t ptid, int step,
95 enum target_signal siggnal);
96 static void remote_open (char *name, int from_tty);
98 static void extended_remote_open (char *name, int from_tty);
100 static void remote_open_1 (char *, int, struct target_ops *, int extended_p);
102 static void remote_close (int quitting);
104 static void remote_store_registers (struct regcache *regcache, int regno);
106 static void remote_mourn (void);
108 static void extended_remote_restart (void);
110 static void extended_remote_mourn (void);
112 static void remote_mourn_1 (struct target_ops *);
114 static void remote_send (char **buf, long *sizeof_buf_p);
116 static int readchar (int timeout);
118 static ptid_t remote_wait (ptid_t ptid,
119 struct target_waitstatus *status);
121 static void remote_kill (void);
123 static int tohex (int nib);
125 static int remote_can_async_p (void);
127 static int remote_is_async_p (void);
129 static void remote_async (void (*callback) (enum inferior_event_type event_type,
130 void *context), void *context);
132 static int remote_async_mask (int new_mask);
134 static void remote_detach (char *args, int from_tty);
136 static void remote_interrupt (int signo);
138 static void remote_interrupt_twice (int signo);
140 static void interrupt_query (void);
142 static void set_general_thread (struct ptid ptid);
143 static void set_continue_thread (struct ptid ptid);
145 static int remote_thread_alive (ptid_t);
147 static void get_offsets (void);
149 static void skip_frame (void);
151 static long read_frame (char **buf_p, long *sizeof_buf);
153 static int hexnumlen (ULONGEST num);
155 static void init_remote_ops (void);
157 static void init_extended_remote_ops (void);
159 static void remote_stop (ptid_t);
161 static int ishex (int ch, int *val);
163 static int stubhex (int ch);
165 static int hexnumstr (char *, ULONGEST);
167 static int hexnumnstr (char *, ULONGEST, int);
169 static CORE_ADDR remote_address_masked (CORE_ADDR);
171 static void print_packet (char *);
173 static unsigned long crc32 (unsigned char *, int, unsigned int);
175 static void compare_sections_command (char *, int);
177 static void packet_command (char *, int);
179 static int stub_unpack_int (char *buff, int fieldlength);
181 static ptid_t remote_current_thread (ptid_t oldptid);
183 static void remote_find_new_threads (void);
185 static void record_currthread (ptid_t currthread);
187 static int fromhex (int a);
189 static int hex2bin (const char *hex, gdb_byte *bin, int count);
191 static int bin2hex (const gdb_byte *bin, char *hex, int count);
193 static int putpkt_binary (char *buf, int cnt);
195 static void check_binary_download (CORE_ADDR addr);
197 struct packet_config;
199 static void show_packet_config_cmd (struct packet_config *config);
201 static void update_packet_config (struct packet_config *config);
203 static void set_remote_protocol_packet_cmd (char *args, int from_tty,
204 struct cmd_list_element *c);
206 static void show_remote_protocol_packet_cmd (struct ui_file *file,
208 struct cmd_list_element *c,
211 static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
212 static ptid_t read_ptid (char *buf, char **obuf);
214 static void remote_query_supported (void);
216 static void remote_check_symbols (struct objfile *objfile);
218 void _initialize_remote (void);
222 static struct cmd_list_element *remote_cmdlist;
224 /* For "set remote" and "show remote". */
226 static struct cmd_list_element *remote_set_cmdlist;
227 static struct cmd_list_element *remote_show_cmdlist;
229 /* Description of the remote protocol state for the currently
230 connected target. This is per-target state, and independent of the
231 selected architecture. */
235 /* A buffer to use for incoming packets, and its current size. The
236 buffer is grown dynamically for larger incoming packets.
237 Outgoing packets may also be constructed in this buffer.
238 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
239 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
244 /* If we negotiated packet size explicitly (and thus can bypass
245 heuristics for the largest packet size that will not overflow
246 a buffer in the stub), this will be set to that packet size.
247 Otherwise zero, meaning to use the guessed size. */
248 long explicit_packet_size;
250 /* remote_wait is normally called when the target is running and
251 waits for a stop reply packet. But sometimes we need to call it
252 when the target is already stopped. We can send a "?" packet
253 and have remote_wait read the response. Or, if we already have
254 the response, we can stash it in BUF and tell remote_wait to
255 skip calling getpkt. This flag is set when BUF contains a
256 stop reply packet and the target is not waiting. */
257 int cached_wait_status;
259 /* True, if in no ack mode. That is, neither GDB nor the stub will
260 expect acks from each other. The connection is assumed to be
264 /* True if we're connected in extended remote mode. */
267 /* True if the stub reported support for multi-process
269 int multi_process_aware;
271 /* True if we resumed the target and we're waiting for the target to
272 stop. In the mean time, we can't start another command/query.
273 The remote server wouldn't be ready to process it, so we'd
274 timeout waiting for a reply that would never come and eventually
275 we'd close the connection. This can happen in asynchronous mode
276 because we allow GDB commands while the target is running. */
277 int waiting_for_stop_reply;
280 /* Returns true if the multi-process extensions are in effect. */
282 remote_multi_process_p (struct remote_state *rs)
284 return rs->extended && rs->multi_process_aware;
287 /* This data could be associated with a target, but we do not always
288 have access to the current target when we need it, so for now it is
289 static. This will be fine for as long as only one target is in use
291 static struct remote_state remote_state;
293 static struct remote_state *
294 get_remote_state_raw (void)
296 return &remote_state;
299 /* Description of the remote protocol for a given architecture. */
303 long offset; /* Offset into G packet. */
304 long regnum; /* GDB's internal register number. */
305 LONGEST pnum; /* Remote protocol register number. */
306 int in_g_packet; /* Always part of G packet. */
307 /* long size in bytes; == register_size (target_gdbarch, regnum);
309 /* char *name; == gdbarch_register_name (target_gdbarch, regnum);
313 struct remote_arch_state
315 /* Description of the remote protocol registers. */
316 long sizeof_g_packet;
318 /* Description of the remote protocol registers indexed by REGNUM
319 (making an array gdbarch_num_regs in size). */
320 struct packet_reg *regs;
322 /* This is the size (in chars) of the first response to the ``g''
323 packet. It is used as a heuristic when determining the maximum
324 size of memory-read and memory-write packets. A target will
325 typically only reserve a buffer large enough to hold the ``g''
326 packet. The size does not include packet overhead (headers and
328 long actual_register_packet_size;
330 /* This is the maximum size (in chars) of a non read/write packet.
331 It is also used as a cap on the size of read/write packets. */
332 long remote_packet_size;
336 /* Handle for retreving the remote protocol data from gdbarch. */
337 static struct gdbarch_data *remote_gdbarch_data_handle;
339 static struct remote_arch_state *
340 get_remote_arch_state (void)
342 return gdbarch_data (target_gdbarch, remote_gdbarch_data_handle);
345 /* Fetch the global remote target state. */
347 static struct remote_state *
348 get_remote_state (void)
350 /* Make sure that the remote architecture state has been
351 initialized, because doing so might reallocate rs->buf. Any
352 function which calls getpkt also needs to be mindful of changes
353 to rs->buf, but this call limits the number of places which run
355 get_remote_arch_state ();
357 return get_remote_state_raw ();
361 compare_pnums (const void *lhs_, const void *rhs_)
363 const struct packet_reg * const *lhs = lhs_;
364 const struct packet_reg * const *rhs = rhs_;
366 if ((*lhs)->pnum < (*rhs)->pnum)
368 else if ((*lhs)->pnum == (*rhs)->pnum)
375 init_remote_state (struct gdbarch *gdbarch)
377 int regnum, num_remote_regs, offset;
378 struct remote_state *rs = get_remote_state_raw ();
379 struct remote_arch_state *rsa;
380 struct packet_reg **remote_regs;
382 rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
384 /* Use the architecture to build a regnum<->pnum table, which will be
385 1:1 unless a feature set specifies otherwise. */
386 rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
387 gdbarch_num_regs (gdbarch),
389 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
391 struct packet_reg *r = &rsa->regs[regnum];
393 if (register_size (gdbarch, regnum) == 0)
394 /* Do not try to fetch zero-sized (placeholder) registers. */
397 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
402 /* Define the g/G packet format as the contents of each register
403 with a remote protocol number, in order of ascending protocol
406 remote_regs = alloca (gdbarch_num_regs (gdbarch)
407 * sizeof (struct packet_reg *));
408 for (num_remote_regs = 0, regnum = 0;
409 regnum < gdbarch_num_regs (gdbarch);
411 if (rsa->regs[regnum].pnum != -1)
412 remote_regs[num_remote_regs++] = &rsa->regs[regnum];
414 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
417 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
419 remote_regs[regnum]->in_g_packet = 1;
420 remote_regs[regnum]->offset = offset;
421 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
424 /* Record the maximum possible size of the g packet - it may turn out
426 rsa->sizeof_g_packet = offset;
428 /* Default maximum number of characters in a packet body. Many
429 remote stubs have a hardwired buffer size of 400 bytes
430 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
431 as the maximum packet-size to ensure that the packet and an extra
432 NUL character can always fit in the buffer. This stops GDB
433 trashing stubs that try to squeeze an extra NUL into what is
434 already a full buffer (As of 1999-12-04 that was most stubs). */
435 rsa->remote_packet_size = 400 - 1;
437 /* This one is filled in when a ``g'' packet is received. */
438 rsa->actual_register_packet_size = 0;
440 /* Should rsa->sizeof_g_packet needs more space than the
441 default, adjust the size accordingly. Remember that each byte is
442 encoded as two characters. 32 is the overhead for the packet
443 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
444 (``$NN:G...#NN'') is a better guess, the below has been padded a
446 if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
447 rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
449 /* Make sure that the packet buffer is plenty big enough for
450 this architecture. */
451 if (rs->buf_size < rsa->remote_packet_size)
453 rs->buf_size = 2 * rsa->remote_packet_size;
454 rs->buf = xrealloc (rs->buf, rs->buf_size);
460 /* Return the current allowed size of a remote packet. This is
461 inferred from the current architecture, and should be used to
462 limit the length of outgoing packets. */
464 get_remote_packet_size (void)
466 struct remote_state *rs = get_remote_state ();
467 struct remote_arch_state *rsa = get_remote_arch_state ();
469 if (rs->explicit_packet_size)
470 return rs->explicit_packet_size;
472 return rsa->remote_packet_size;
475 static struct packet_reg *
476 packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
478 if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch))
482 struct packet_reg *r = &rsa->regs[regnum];
483 gdb_assert (r->regnum == regnum);
488 static struct packet_reg *
489 packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
492 for (i = 0; i < gdbarch_num_regs (target_gdbarch); i++)
494 struct packet_reg *r = &rsa->regs[i];
501 /* FIXME: graces/2002-08-08: These variables should eventually be
502 bound to an instance of the target object (as in gdbarch-tdep()),
503 when such a thing exists. */
505 /* This is set to the data address of the access causing the target
506 to stop for a watchpoint. */
507 static CORE_ADDR remote_watch_data_address;
509 /* This is non-zero if target stopped for a watchpoint. */
510 static int remote_stopped_by_watchpoint_p;
512 static struct target_ops remote_ops;
514 static struct target_ops extended_remote_ops;
516 static int remote_async_mask_value = 1;
518 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
519 ``forever'' still use the normal timeout mechanism. This is
520 currently used by the ASYNC code to guarentee that target reads
521 during the initial connect always time-out. Once getpkt has been
522 modified to return a timeout indication and, in turn
523 remote_wait()/wait_for_inferior() have gained a timeout parameter
525 static int wait_forever_enabled_p = 1;
528 /* This variable chooses whether to send a ^C or a break when the user
529 requests program interruption. Although ^C is usually what remote
530 systems expect, and that is the default here, sometimes a break is
531 preferable instead. */
533 static int remote_break;
535 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
536 remote_open knows that we don't have a file open when the program
538 static struct serial *remote_desc = NULL;
540 /* This variable sets the number of bits in an address that are to be
541 sent in a memory ("M" or "m") packet. Normally, after stripping
542 leading zeros, the entire address would be sent. This variable
543 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
544 initial implementation of remote.c restricted the address sent in
545 memory packets to ``host::sizeof long'' bytes - (typically 32
546 bits). Consequently, for 64 bit targets, the upper 32 bits of an
547 address was never sent. Since fixing this bug may cause a break in
548 some remote targets this variable is principly provided to
549 facilitate backward compatibility. */
551 static int remote_address_size;
553 /* Temporary to track who currently owns the terminal. See
554 remote_terminal_* for more details. */
556 static int remote_async_terminal_ours_p;
558 /* The executable file to use for "run" on the remote side. */
560 static char *remote_exec_file = "";
563 /* User configurable variables for the number of characters in a
564 memory read/write packet. MIN (rsa->remote_packet_size,
565 rsa->sizeof_g_packet) is the default. Some targets need smaller
566 values (fifo overruns, et.al.) and some users need larger values
567 (speed up transfers). The variables ``preferred_*'' (the user
568 request), ``current_*'' (what was actually set) and ``forced_*''
569 (Positive - a soft limit, negative - a hard limit). */
571 struct memory_packet_config
578 /* Compute the current size of a read/write packet. Since this makes
579 use of ``actual_register_packet_size'' the computation is dynamic. */
582 get_memory_packet_size (struct memory_packet_config *config)
584 struct remote_state *rs = get_remote_state ();
585 struct remote_arch_state *rsa = get_remote_arch_state ();
587 /* NOTE: The somewhat arbitrary 16k comes from the knowledge (folk
588 law?) that some hosts don't cope very well with large alloca()
589 calls. Eventually the alloca() code will be replaced by calls to
590 xmalloc() and make_cleanups() allowing this restriction to either
591 be lifted or removed. */
592 #ifndef MAX_REMOTE_PACKET_SIZE
593 #define MAX_REMOTE_PACKET_SIZE 16384
595 /* NOTE: 20 ensures we can write at least one byte. */
596 #ifndef MIN_REMOTE_PACKET_SIZE
597 #define MIN_REMOTE_PACKET_SIZE 20
602 if (config->size <= 0)
603 what_they_get = MAX_REMOTE_PACKET_SIZE;
605 what_they_get = config->size;
609 what_they_get = get_remote_packet_size ();
610 /* Limit the packet to the size specified by the user. */
612 && what_they_get > config->size)
613 what_they_get = config->size;
615 /* Limit it to the size of the targets ``g'' response unless we have
616 permission from the stub to use a larger packet size. */
617 if (rs->explicit_packet_size == 0
618 && rsa->actual_register_packet_size > 0
619 && what_they_get > rsa->actual_register_packet_size)
620 what_they_get = rsa->actual_register_packet_size;
622 if (what_they_get > MAX_REMOTE_PACKET_SIZE)
623 what_they_get = MAX_REMOTE_PACKET_SIZE;
624 if (what_they_get < MIN_REMOTE_PACKET_SIZE)
625 what_they_get = MIN_REMOTE_PACKET_SIZE;
627 /* Make sure there is room in the global buffer for this packet
628 (including its trailing NUL byte). */
629 if (rs->buf_size < what_they_get + 1)
631 rs->buf_size = 2 * what_they_get;
632 rs->buf = xrealloc (rs->buf, 2 * what_they_get);
635 return what_they_get;
638 /* Update the size of a read/write packet. If they user wants
639 something really big then do a sanity check. */
642 set_memory_packet_size (char *args, struct memory_packet_config *config)
644 int fixed_p = config->fixed_p;
645 long size = config->size;
647 error (_("Argument required (integer, `fixed' or `limited')."));
648 else if (strcmp (args, "hard") == 0
649 || strcmp (args, "fixed") == 0)
651 else if (strcmp (args, "soft") == 0
652 || strcmp (args, "limit") == 0)
657 size = strtoul (args, &end, 0);
659 error (_("Invalid %s (bad syntax)."), config->name);
661 /* Instead of explicitly capping the size of a packet to
662 MAX_REMOTE_PACKET_SIZE or dissallowing it, the user is
663 instead allowed to set the size to something arbitrarily
665 if (size > MAX_REMOTE_PACKET_SIZE)
666 error (_("Invalid %s (too large)."), config->name);
670 if (fixed_p && !config->fixed_p)
672 if (! query (_("The target may not be able to correctly handle a %s\n"
673 "of %ld bytes. Change the packet size? "),
675 error (_("Packet size not changed."));
677 /* Update the config. */
678 config->fixed_p = fixed_p;
683 show_memory_packet_size (struct memory_packet_config *config)
685 printf_filtered (_("The %s is %ld. "), config->name, config->size);
687 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
688 get_memory_packet_size (config));
690 printf_filtered (_("Packets are limited to %ld bytes.\n"),
691 get_memory_packet_size (config));
694 static struct memory_packet_config memory_write_packet_config =
696 "memory-write-packet-size",
700 set_memory_write_packet_size (char *args, int from_tty)
702 set_memory_packet_size (args, &memory_write_packet_config);
706 show_memory_write_packet_size (char *args, int from_tty)
708 show_memory_packet_size (&memory_write_packet_config);
712 get_memory_write_packet_size (void)
714 return get_memory_packet_size (&memory_write_packet_config);
717 static struct memory_packet_config memory_read_packet_config =
719 "memory-read-packet-size",
723 set_memory_read_packet_size (char *args, int from_tty)
725 set_memory_packet_size (args, &memory_read_packet_config);
729 show_memory_read_packet_size (char *args, int from_tty)
731 show_memory_packet_size (&memory_read_packet_config);
735 get_memory_read_packet_size (void)
737 long size = get_memory_packet_size (&memory_read_packet_config);
738 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
739 extra buffer size argument before the memory read size can be
740 increased beyond this. */
741 if (size > get_remote_packet_size ())
742 size = get_remote_packet_size ();
747 /* Generic configuration support for packets the stub optionally
748 supports. Allows the user to specify the use of the packet as well
749 as allowing GDB to auto-detect support in the remote stub. */
753 PACKET_SUPPORT_UNKNOWN = 0,
762 enum auto_boolean detect;
763 enum packet_support support;
766 /* Analyze a packet's return value and update the packet config
777 update_packet_config (struct packet_config *config)
779 switch (config->detect)
781 case AUTO_BOOLEAN_TRUE:
782 config->support = PACKET_ENABLE;
784 case AUTO_BOOLEAN_FALSE:
785 config->support = PACKET_DISABLE;
787 case AUTO_BOOLEAN_AUTO:
788 config->support = PACKET_SUPPORT_UNKNOWN;
794 show_packet_config_cmd (struct packet_config *config)
796 char *support = "internal-error";
797 switch (config->support)
803 support = "disabled";
805 case PACKET_SUPPORT_UNKNOWN:
809 switch (config->detect)
811 case AUTO_BOOLEAN_AUTO:
812 printf_filtered (_("Support for the `%s' packet is auto-detected, currently %s.\n"),
813 config->name, support);
815 case AUTO_BOOLEAN_TRUE:
816 case AUTO_BOOLEAN_FALSE:
817 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
818 config->name, support);
824 add_packet_config_cmd (struct packet_config *config, const char *name,
825 const char *title, int legacy)
832 config->title = title;
833 config->detect = AUTO_BOOLEAN_AUTO;
834 config->support = PACKET_SUPPORT_UNKNOWN;
835 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
837 show_doc = xstrprintf ("Show current use of remote protocol `%s' (%s) packet",
839 /* set/show TITLE-packet {auto,on,off} */
840 cmd_name = xstrprintf ("%s-packet", title);
841 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
842 &config->detect, set_doc, show_doc, NULL, /* help_doc */
843 set_remote_protocol_packet_cmd,
844 show_remote_protocol_packet_cmd,
845 &remote_set_cmdlist, &remote_show_cmdlist);
846 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
850 legacy_name = xstrprintf ("%s-packet", name);
851 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
852 &remote_set_cmdlist);
853 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
854 &remote_show_cmdlist);
858 static enum packet_result
859 packet_check_result (const char *buf)
863 /* The stub recognized the packet request. Check that the
864 operation succeeded. */
866 && isxdigit (buf[1]) && isxdigit (buf[2])
868 /* "Enn" - definitly an error. */
871 /* Always treat "E." as an error. This will be used for
872 more verbose error messages, such as E.memtypes. */
873 if (buf[0] == 'E' && buf[1] == '.')
876 /* The packet may or may not be OK. Just assume it is. */
880 /* The stub does not support the packet. */
881 return PACKET_UNKNOWN;
884 static enum packet_result
885 packet_ok (const char *buf, struct packet_config *config)
887 enum packet_result result;
889 result = packet_check_result (buf);
894 /* The stub recognized the packet request. */
895 switch (config->support)
897 case PACKET_SUPPORT_UNKNOWN:
899 fprintf_unfiltered (gdb_stdlog,
900 "Packet %s (%s) is supported\n",
901 config->name, config->title);
902 config->support = PACKET_ENABLE;
905 internal_error (__FILE__, __LINE__,
906 _("packet_ok: attempt to use a disabled packet"));
913 /* The stub does not support the packet. */
914 switch (config->support)
917 if (config->detect == AUTO_BOOLEAN_AUTO)
918 /* If the stub previously indicated that the packet was
919 supported then there is a protocol error.. */
920 error (_("Protocol error: %s (%s) conflicting enabled responses."),
921 config->name, config->title);
923 /* The user set it wrong. */
924 error (_("Enabled packet %s (%s) not recognized by stub"),
925 config->name, config->title);
927 case PACKET_SUPPORT_UNKNOWN:
929 fprintf_unfiltered (gdb_stdlog,
930 "Packet %s (%s) is NOT supported\n",
931 config->name, config->title);
932 config->support = PACKET_DISABLE;
960 PACKET_qXfer_features,
961 PACKET_qXfer_libraries,
962 PACKET_qXfer_memory_map,
963 PACKET_qXfer_spu_read,
964 PACKET_qXfer_spu_write,
968 PACKET_qSearch_memory,
971 PACKET_QStartNoAckMode,
976 static struct packet_config remote_protocol_packets[PACKET_MAX];
979 set_remote_protocol_packet_cmd (char *args, int from_tty,
980 struct cmd_list_element *c)
982 struct packet_config *packet;
984 for (packet = remote_protocol_packets;
985 packet < &remote_protocol_packets[PACKET_MAX];
988 if (&packet->detect == c->var)
990 update_packet_config (packet);
994 internal_error (__FILE__, __LINE__, "Could not find config for %s",
999 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1000 struct cmd_list_element *c,
1003 struct packet_config *packet;
1005 for (packet = remote_protocol_packets;
1006 packet < &remote_protocol_packets[PACKET_MAX];
1009 if (&packet->detect == c->var)
1011 show_packet_config_cmd (packet);
1015 internal_error (__FILE__, __LINE__, "Could not find config for %s",
1019 /* Should we try one of the 'Z' requests? */
1023 Z_PACKET_SOFTWARE_BP,
1024 Z_PACKET_HARDWARE_BP,
1031 /* For compatibility with older distributions. Provide a ``set remote
1032 Z-packet ...'' command that updates all the Z packet types. */
1034 static enum auto_boolean remote_Z_packet_detect;
1037 set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1038 struct cmd_list_element *c)
1041 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1043 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
1044 update_packet_config (&remote_protocol_packets[PACKET_Z0 + i]);
1049 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1050 struct cmd_list_element *c,
1054 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1056 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
1060 /* Should we try the 'ThreadInfo' query packet?
1062 This variable (NOT available to the user: auto-detect only!)
1063 determines whether GDB will use the new, simpler "ThreadInfo"
1064 query or the older, more complex syntax for thread queries.
1065 This is an auto-detect variable (set to true at each connect,
1066 and set to false when the target fails to recognize it). */
1068 static int use_threadinfo_query;
1069 static int use_threadextra_query;
1071 /* Tokens for use by the asynchronous signal handlers for SIGINT. */
1072 static struct async_signal_handler *sigint_remote_twice_token;
1073 static struct async_signal_handler *sigint_remote_token;
1077 static ptid_t magic_null_ptid;
1078 static ptid_t not_sent_ptid;
1079 static ptid_t any_thread_ptid;
1081 /* These are the threads which we last sent to the remote system. The
1082 TID member will be -1 for all or -2 for not sent yet. */
1084 static ptid_t general_thread;
1085 static ptid_t continue_thread;
1088 /* Call this function as a result of
1089 1) A halt indication (T packet) containing a thread id
1090 2) A direct query of currthread
1091 3) Successful execution of set thread
1095 record_currthread (ptid_t currthread)
1097 general_thread = currthread;
1099 /* When connecting to a target remote, or to a target
1100 extended-remote which already was debugging an inferior, we may
1101 not know about it yet. Add it before adding its child thread, so
1102 notifications are emitted in a sensible order. */
1103 if (!in_inferior_list (ptid_get_pid (currthread)))
1104 add_inferior (ptid_get_pid (currthread));
1106 /* If this is a new thread, add it to GDB's thread list.
1107 If we leave it up to WFI to do this, bad things will happen. */
1109 if (in_thread_list (currthread) && is_exited (currthread))
1111 /* We're seeing an event on a thread id we knew had exited.
1112 This has to be a new thread reusing the old id. Add it. */
1113 add_thread (currthread);
1117 if (!in_thread_list (currthread))
1119 if (ptid_equal (pid_to_ptid (ptid_get_pid (currthread)), inferior_ptid))
1121 /* inferior_ptid has no thread member yet. This can happen
1122 with the vAttach -> remote_wait,"TAAthread:" path if the
1123 stub doesn't support qC. This is the first stop reported
1124 after an attach, so this is the main thread. Update the
1125 ptid in the thread list. */
1126 thread_change_ptid (inferior_ptid, currthread);
1130 if (ptid_equal (magic_null_ptid, inferior_ptid))
1132 /* inferior_ptid is not set yet. This can happen with the
1133 vRun -> remote_wait,"TAAthread:" path if the stub
1134 doesn't support qC. This is the first stop reported
1135 after an attach, so this is the main thread. Update the
1136 ptid in the thread list. */
1137 thread_change_ptid (inferior_ptid, currthread);
1141 /* This is really a new thread. Add it. */
1142 add_thread (currthread);
1146 static char *last_pass_packet;
1148 /* If 'QPassSignals' is supported, tell the remote stub what signals
1149 it can simply pass through to the inferior without reporting. */
1152 remote_pass_signals (void)
1154 if (remote_protocol_packets[PACKET_QPassSignals].support != PACKET_DISABLE)
1156 char *pass_packet, *p;
1157 int numsigs = (int) TARGET_SIGNAL_LAST;
1160 gdb_assert (numsigs < 256);
1161 for (i = 0; i < numsigs; i++)
1163 if (signal_stop_state (i) == 0
1164 && signal_print_state (i) == 0
1165 && signal_pass_state (i) == 1)
1168 pass_packet = xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
1169 strcpy (pass_packet, "QPassSignals:");
1170 p = pass_packet + strlen (pass_packet);
1171 for (i = 0; i < numsigs; i++)
1173 if (signal_stop_state (i) == 0
1174 && signal_print_state (i) == 0
1175 && signal_pass_state (i) == 1)
1178 *p++ = tohex (i >> 4);
1179 *p++ = tohex (i & 15);
1188 if (!last_pass_packet || strcmp (last_pass_packet, pass_packet))
1190 struct remote_state *rs = get_remote_state ();
1191 char *buf = rs->buf;
1193 putpkt (pass_packet);
1194 getpkt (&rs->buf, &rs->buf_size, 0);
1195 packet_ok (buf, &remote_protocol_packets[PACKET_QPassSignals]);
1196 if (last_pass_packet)
1197 xfree (last_pass_packet);
1198 last_pass_packet = pass_packet;
1201 xfree (pass_packet);
1205 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
1206 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
1207 thread. If GEN is set, set the general thread, if not, then set
1208 the step/continue thread. */
1210 set_thread (struct ptid ptid, int gen)
1212 struct remote_state *rs = get_remote_state ();
1213 ptid_t state = gen ? general_thread : continue_thread;
1214 char *buf = rs->buf;
1215 char *endbuf = rs->buf + get_remote_packet_size ();
1217 if (ptid_equal (state, ptid))
1221 *buf++ = gen ? 'g' : 'c';
1222 if (ptid_equal (ptid, magic_null_ptid))
1223 xsnprintf (buf, endbuf - buf, "0");
1224 else if (ptid_equal (ptid, any_thread_ptid))
1225 xsnprintf (buf, endbuf - buf, "0");
1226 else if (ptid_equal (ptid, minus_one_ptid))
1227 xsnprintf (buf, endbuf - buf, "-1");
1229 write_ptid (buf, endbuf, ptid);
1231 getpkt (&rs->buf, &rs->buf_size, 0);
1233 general_thread = ptid;
1235 continue_thread = ptid;
1239 set_general_thread (struct ptid ptid)
1241 set_thread (ptid, 1);
1245 set_continue_thread (struct ptid ptid)
1247 set_thread (ptid, 0);
1250 /* Change the remote current process. Which thread within the process
1251 ends up selected isn't important, as long as it is the same process
1252 as what INFERIOR_PTID points to.
1254 This comes from that fact that there is no explicit notion of
1255 "selected process" in the protocol. The selected process for
1256 general operations is the process the selected general thread
1260 set_general_process (void)
1262 struct remote_state *rs = get_remote_state ();
1264 /* If the remote can't handle multiple processes, don't bother. */
1265 if (!remote_multi_process_p (rs))
1268 /* We only need to change the remote current thread if it's pointing
1269 at some other process. */
1270 if (ptid_get_pid (general_thread) != ptid_get_pid (inferior_ptid))
1271 set_general_thread (inferior_ptid);
1275 /* Return nonzero if the thread PTID is still alive on the remote
1279 remote_thread_alive (ptid_t ptid)
1281 struct remote_state *rs = get_remote_state ();
1282 int tid = ptid_get_tid (ptid);
1285 if (ptid_equal (ptid, magic_null_ptid))
1286 /* The main thread is always alive. */
1289 if (ptid_get_pid (ptid) != 0 && ptid_get_tid (ptid) == 0)
1290 /* The main thread is always alive. This can happen after a
1291 vAttach, if the remote side doesn't support
1296 endp = rs->buf + get_remote_packet_size ();
1299 write_ptid (p, endp, ptid);
1302 getpkt (&rs->buf, &rs->buf_size, 0);
1303 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
1306 /* About these extended threadlist and threadinfo packets. They are
1307 variable length packets but, the fields within them are often fixed
1308 length. They are redundent enough to send over UDP as is the
1309 remote protocol in general. There is a matching unit test module
1312 #define OPAQUETHREADBYTES 8
1314 /* a 64 bit opaque identifier */
1315 typedef unsigned char threadref[OPAQUETHREADBYTES];
1317 /* WARNING: This threadref data structure comes from the remote O.S.,
1318 libstub protocol encoding, and remote.c. it is not particularly
1321 /* Right now, the internal structure is int. We want it to be bigger.
1325 typedef int gdb_threadref; /* Internal GDB thread reference. */
1327 /* gdb_ext_thread_info is an internal GDB data structure which is
1328 equivalent to the reply of the remote threadinfo packet. */
1330 struct gdb_ext_thread_info
1332 threadref threadid; /* External form of thread reference. */
1333 int active; /* Has state interesting to GDB?
1335 char display[256]; /* Brief state display, name,
1336 blocked/suspended. */
1337 char shortname[32]; /* To be used to name threads. */
1338 char more_display[256]; /* Long info, statistics, queue depth,
1342 /* The volume of remote transfers can be limited by submitting
1343 a mask containing bits specifying the desired information.
1344 Use a union of these values as the 'selection' parameter to
1345 get_thread_info. FIXME: Make these TAG names more thread specific.
1348 #define TAG_THREADID 1
1349 #define TAG_EXISTS 2
1350 #define TAG_DISPLAY 4
1351 #define TAG_THREADNAME 8
1352 #define TAG_MOREDISPLAY 16
1354 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
1356 char *unpack_varlen_hex (char *buff, ULONGEST *result);
1358 static char *unpack_nibble (char *buf, int *val);
1360 static char *pack_nibble (char *buf, int nibble);
1362 static char *pack_hex_byte (char *pkt, int /* unsigned char */ byte);
1364 static char *unpack_byte (char *buf, int *value);
1366 static char *pack_int (char *buf, int value);
1368 static char *unpack_int (char *buf, int *value);
1370 static char *unpack_string (char *src, char *dest, int length);
1372 static char *pack_threadid (char *pkt, threadref *id);
1374 static char *unpack_threadid (char *inbuf, threadref *id);
1376 void int_to_threadref (threadref *id, int value);
1378 static int threadref_to_int (threadref *ref);
1380 static void copy_threadref (threadref *dest, threadref *src);
1382 static int threadmatch (threadref *dest, threadref *src);
1384 static char *pack_threadinfo_request (char *pkt, int mode,
1387 static int remote_unpack_thread_info_response (char *pkt,
1388 threadref *expectedref,
1389 struct gdb_ext_thread_info
1393 static int remote_get_threadinfo (threadref *threadid,
1394 int fieldset, /*TAG mask */
1395 struct gdb_ext_thread_info *info);
1397 static char *pack_threadlist_request (char *pkt, int startflag,
1399 threadref *nextthread);
1401 static int parse_threadlist_response (char *pkt,
1403 threadref *original_echo,
1404 threadref *resultlist,
1407 static int remote_get_threadlist (int startflag,
1408 threadref *nextthread,
1412 threadref *threadlist);
1414 typedef int (*rmt_thread_action) (threadref *ref, void *context);
1416 static int remote_threadlist_iterator (rmt_thread_action stepfunction,
1417 void *context, int looplimit);
1419 static int remote_newthread_step (threadref *ref, void *context);
1422 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
1423 buffer we're allowed to write to. Returns
1424 BUF+CHARACTERS_WRITTEN. */
1427 write_ptid (char *buf, const char *endbuf, ptid_t ptid)
1430 struct remote_state *rs = get_remote_state ();
1432 if (remote_multi_process_p (rs))
1434 pid = ptid_get_pid (ptid);
1436 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
1438 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
1440 tid = ptid_get_tid (ptid);
1442 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
1444 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
1449 /* Extract a PTID from BUF. If non-null, OBUF is set to the to one
1450 passed the last parsed char. Returns null_ptid on error. */
1453 read_ptid (char *buf, char **obuf)
1457 ULONGEST pid = 0, tid = 0;
1462 /* Multi-process ptid. */
1463 pp = unpack_varlen_hex (p + 1, &pid);
1465 error (_("invalid remote ptid: %s\n"), p);
1468 pp = unpack_varlen_hex (p + 1, &tid);
1471 return ptid_build (pid, 0, tid);
1474 /* No multi-process. Just a tid. */
1475 pp = unpack_varlen_hex (p, &tid);
1477 /* Since the stub is not sending a process id, then default to
1478 what's in inferior_ptid. */
1479 pid = ptid_get_pid (inferior_ptid);
1483 return ptid_build (pid, 0, tid);
1486 /* Encode 64 bits in 16 chars of hex. */
1488 static const char hexchars[] = "0123456789abcdef";
1491 ishex (int ch, int *val)
1493 if ((ch >= 'a') && (ch <= 'f'))
1495 *val = ch - 'a' + 10;
1498 if ((ch >= 'A') && (ch <= 'F'))
1500 *val = ch - 'A' + 10;
1503 if ((ch >= '0') && (ch <= '9'))
1514 if (ch >= 'a' && ch <= 'f')
1515 return ch - 'a' + 10;
1516 if (ch >= '0' && ch <= '9')
1518 if (ch >= 'A' && ch <= 'F')
1519 return ch - 'A' + 10;
1524 stub_unpack_int (char *buff, int fieldlength)
1531 nibble = stubhex (*buff++);
1535 retval = retval << 4;
1541 unpack_varlen_hex (char *buff, /* packet to parse */
1545 ULONGEST retval = 0;
1547 while (ishex (*buff, &nibble))
1550 retval = retval << 4;
1551 retval |= nibble & 0x0f;
1558 unpack_nibble (char *buf, int *val)
1560 *val = fromhex (*buf++);
1565 pack_nibble (char *buf, int nibble)
1567 *buf++ = hexchars[(nibble & 0x0f)];
1572 pack_hex_byte (char *pkt, int byte)
1574 *pkt++ = hexchars[(byte >> 4) & 0xf];
1575 *pkt++ = hexchars[(byte & 0xf)];
1580 unpack_byte (char *buf, int *value)
1582 *value = stub_unpack_int (buf, 2);
1587 pack_int (char *buf, int value)
1589 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
1590 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
1591 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
1592 buf = pack_hex_byte (buf, (value & 0xff));
1597 unpack_int (char *buf, int *value)
1599 *value = stub_unpack_int (buf, 8);
1603 #if 0 /* Currently unused, uncomment when needed. */
1604 static char *pack_string (char *pkt, char *string);
1607 pack_string (char *pkt, char *string)
1612 len = strlen (string);
1614 len = 200; /* Bigger than most GDB packets, junk??? */
1615 pkt = pack_hex_byte (pkt, len);
1619 if ((ch == '\0') || (ch == '#'))
1620 ch = '*'; /* Protect encapsulation. */
1625 #endif /* 0 (unused) */
1628 unpack_string (char *src, char *dest, int length)
1637 pack_threadid (char *pkt, threadref *id)
1640 unsigned char *altid;
1642 altid = (unsigned char *) id;
1643 limit = pkt + BUF_THREAD_ID_SIZE;
1645 pkt = pack_hex_byte (pkt, *altid++);
1651 unpack_threadid (char *inbuf, threadref *id)
1654 char *limit = inbuf + BUF_THREAD_ID_SIZE;
1657 altref = (char *) id;
1659 while (inbuf < limit)
1661 x = stubhex (*inbuf++);
1662 y = stubhex (*inbuf++);
1663 *altref++ = (x << 4) | y;
1668 /* Externally, threadrefs are 64 bits but internally, they are still
1669 ints. This is due to a mismatch of specifications. We would like
1670 to use 64bit thread references internally. This is an adapter
1674 int_to_threadref (threadref *id, int value)
1676 unsigned char *scan;
1678 scan = (unsigned char *) id;
1684 *scan++ = (value >> 24) & 0xff;
1685 *scan++ = (value >> 16) & 0xff;
1686 *scan++ = (value >> 8) & 0xff;
1687 *scan++ = (value & 0xff);
1691 threadref_to_int (threadref *ref)
1694 unsigned char *scan;
1700 value = (value << 8) | ((*scan++) & 0xff);
1705 copy_threadref (threadref *dest, threadref *src)
1708 unsigned char *csrc, *cdest;
1710 csrc = (unsigned char *) src;
1711 cdest = (unsigned char *) dest;
1718 threadmatch (threadref *dest, threadref *src)
1720 /* Things are broken right now, so just assume we got a match. */
1722 unsigned char *srcp, *destp;
1724 srcp = (char *) src;
1725 destp = (char *) dest;
1729 result &= (*srcp++ == *destp++) ? 1 : 0;
1736 threadid:1, # always request threadid
1743 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
1746 pack_threadinfo_request (char *pkt, int mode, threadref *id)
1748 *pkt++ = 'q'; /* Info Query */
1749 *pkt++ = 'P'; /* process or thread info */
1750 pkt = pack_int (pkt, mode); /* mode */
1751 pkt = pack_threadid (pkt, id); /* threadid */
1752 *pkt = '\0'; /* terminate */
1756 /* These values tag the fields in a thread info response packet. */
1757 /* Tagging the fields allows us to request specific fields and to
1758 add more fields as time goes by. */
1760 #define TAG_THREADID 1 /* Echo the thread identifier. */
1761 #define TAG_EXISTS 2 /* Is this process defined enough to
1762 fetch registers and its stack? */
1763 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
1764 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
1765 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
1769 remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
1770 struct gdb_ext_thread_info *info)
1772 struct remote_state *rs = get_remote_state ();
1776 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
1779 /* info->threadid = 0; FIXME: implement zero_threadref. */
1781 info->display[0] = '\0';
1782 info->shortname[0] = '\0';
1783 info->more_display[0] = '\0';
1785 /* Assume the characters indicating the packet type have been
1787 pkt = unpack_int (pkt, &mask); /* arg mask */
1788 pkt = unpack_threadid (pkt, &ref);
1791 warning (_("Incomplete response to threadinfo request."));
1792 if (!threadmatch (&ref, expectedref))
1793 { /* This is an answer to a different request. */
1794 warning (_("ERROR RMT Thread info mismatch."));
1797 copy_threadref (&info->threadid, &ref);
1799 /* Loop on tagged fields , try to bail if somthing goes wrong. */
1801 /* Packets are terminated with nulls. */
1802 while ((pkt < limit) && mask && *pkt)
1804 pkt = unpack_int (pkt, &tag); /* tag */
1805 pkt = unpack_byte (pkt, &length); /* length */
1806 if (!(tag & mask)) /* Tags out of synch with mask. */
1808 warning (_("ERROR RMT: threadinfo tag mismatch."));
1812 if (tag == TAG_THREADID)
1816 warning (_("ERROR RMT: length of threadid is not 16."));
1820 pkt = unpack_threadid (pkt, &ref);
1821 mask = mask & ~TAG_THREADID;
1824 if (tag == TAG_EXISTS)
1826 info->active = stub_unpack_int (pkt, length);
1828 mask = mask & ~(TAG_EXISTS);
1831 warning (_("ERROR RMT: 'exists' length too long."));
1837 if (tag == TAG_THREADNAME)
1839 pkt = unpack_string (pkt, &info->shortname[0], length);
1840 mask = mask & ~TAG_THREADNAME;
1843 if (tag == TAG_DISPLAY)
1845 pkt = unpack_string (pkt, &info->display[0], length);
1846 mask = mask & ~TAG_DISPLAY;
1849 if (tag == TAG_MOREDISPLAY)
1851 pkt = unpack_string (pkt, &info->more_display[0], length);
1852 mask = mask & ~TAG_MOREDISPLAY;
1855 warning (_("ERROR RMT: unknown thread info tag."));
1856 break; /* Not a tag we know about. */
1862 remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
1863 struct gdb_ext_thread_info *info)
1865 struct remote_state *rs = get_remote_state ();
1868 pack_threadinfo_request (rs->buf, fieldset, threadid);
1870 getpkt (&rs->buf, &rs->buf_size, 0);
1872 if (rs->buf[0] == '\0')
1875 result = remote_unpack_thread_info_response (rs->buf + 2,
1880 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
1883 pack_threadlist_request (char *pkt, int startflag, int threadcount,
1884 threadref *nextthread)
1886 *pkt++ = 'q'; /* info query packet */
1887 *pkt++ = 'L'; /* Process LIST or threadLIST request */
1888 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
1889 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
1890 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
1895 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
1898 parse_threadlist_response (char *pkt, int result_limit,
1899 threadref *original_echo, threadref *resultlist,
1902 struct remote_state *rs = get_remote_state ();
1904 int count, resultcount, done;
1907 /* Assume the 'q' and 'M chars have been stripped. */
1908 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
1909 /* done parse past here */
1910 pkt = unpack_byte (pkt, &count); /* count field */
1911 pkt = unpack_nibble (pkt, &done);
1912 /* The first threadid is the argument threadid. */
1913 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
1914 while ((count-- > 0) && (pkt < limit))
1916 pkt = unpack_threadid (pkt, resultlist++);
1917 if (resultcount++ >= result_limit)
1926 remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
1927 int *done, int *result_count, threadref *threadlist)
1929 struct remote_state *rs = get_remote_state ();
1930 static threadref echo_nextthread;
1933 /* Trancate result limit to be smaller than the packet size. */
1934 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10) >= get_remote_packet_size ())
1935 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
1937 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
1939 getpkt (&rs->buf, &rs->buf_size, 0);
1941 if (*rs->buf == '\0')
1945 parse_threadlist_response (rs->buf + 2, result_limit, &echo_nextthread,
1948 if (!threadmatch (&echo_nextthread, nextthread))
1950 /* FIXME: This is a good reason to drop the packet. */
1951 /* Possably, there is a duplicate response. */
1953 retransmit immediatly - race conditions
1954 retransmit after timeout - yes
1956 wait for packet, then exit
1958 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
1959 return 0; /* I choose simply exiting. */
1961 if (*result_count <= 0)
1965 warning (_("RMT ERROR : failed to get remote thread list."));
1968 return result; /* break; */
1970 if (*result_count > result_limit)
1973 warning (_("RMT ERROR: threadlist response longer than requested."));
1979 /* This is the interface between remote and threads, remotes upper
1982 /* remote_find_new_threads retrieves the thread list and for each
1983 thread in the list, looks up the thread in GDB's internal list,
1984 adding the thread if it does not already exist. This involves
1985 getting partial thread lists from the remote target so, polling the
1986 quit_flag is required. */
1989 /* About this many threadisds fit in a packet. */
1991 #define MAXTHREADLISTRESULTS 32
1994 remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
1997 int done, i, result_count;
2001 static threadref nextthread;
2002 static threadref resultthreadlist[MAXTHREADLISTRESULTS];
2007 if (loopcount++ > looplimit)
2010 warning (_("Remote fetch threadlist -infinite loop-."));
2013 if (!remote_get_threadlist (startflag, &nextthread, MAXTHREADLISTRESULTS,
2014 &done, &result_count, resultthreadlist))
2019 /* Clear for later iterations. */
2021 /* Setup to resume next batch of thread references, set nextthread. */
2022 if (result_count >= 1)
2023 copy_threadref (&nextthread, &resultthreadlist[result_count - 1]);
2025 while (result_count--)
2026 if (!(result = (*stepfunction) (&resultthreadlist[i++], context)))
2033 remote_newthread_step (threadref *ref, void *context)
2035 int pid = ptid_get_pid (inferior_ptid);
2036 ptid_t ptid = ptid_build (pid, 0, threadref_to_int (ref));
2038 if (!in_thread_list (ptid))
2040 return 1; /* continue iterator */
2043 #define CRAZY_MAX_THREADS 1000
2046 remote_current_thread (ptid_t oldpid)
2048 struct remote_state *rs = get_remote_state ();
2054 getpkt (&rs->buf, &rs->buf_size, 0);
2055 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
2056 return read_ptid (&rs->buf[2], NULL);
2061 /* Find new threads for info threads command.
2062 * Original version, using John Metzler's thread protocol.
2066 remote_find_new_threads (void)
2068 remote_threadlist_iterator (remote_newthread_step, 0,
2073 * Find all threads for info threads command.
2074 * Uses new thread protocol contributed by Cisco.
2075 * Falls back and attempts to use the older method (above)
2076 * if the target doesn't respond to the new method.
2080 remote_threads_info (void)
2082 struct remote_state *rs = get_remote_state ();
2086 if (remote_desc == 0) /* paranoia */
2087 error (_("Command can only be used when connected to the remote target."));
2089 if (use_threadinfo_query)
2091 putpkt ("qfThreadInfo");
2092 getpkt (&rs->buf, &rs->buf_size, 0);
2094 if (bufp[0] != '\0') /* q packet recognized */
2096 while (*bufp++ == 'm') /* reply contains one or more TID */
2100 new_thread = read_ptid (bufp, &bufp);
2101 if (!ptid_equal (new_thread, null_ptid)
2102 && (!in_thread_list (new_thread)
2103 || is_exited (new_thread)))
2105 /* When connected to a multi-process aware stub,
2106 "info threads" may show up threads of
2107 inferiors we didn't know about yet. Add them
2108 now, and before adding any of its child
2109 threads, so notifications are emitted in a
2111 if (!in_inferior_list (ptid_get_pid (new_thread)))
2112 add_inferior (ptid_get_pid (new_thread));
2114 add_thread (new_thread);
2117 while (*bufp++ == ','); /* comma-separated list */
2118 putpkt ("qsThreadInfo");
2119 getpkt (&rs->buf, &rs->buf_size, 0);
2126 /* Else fall back to old method based on jmetzler protocol. */
2127 use_threadinfo_query = 0;
2128 remote_find_new_threads ();
2133 * Collect a descriptive string about the given thread.
2134 * The target may say anything it wants to about the thread
2135 * (typically info about its blocked / runnable state, name, etc.).
2136 * This string will appear in the info threads display.
2138 * Optional: targets are not required to implement this function.
2142 remote_threads_extra_info (struct thread_info *tp)
2144 struct remote_state *rs = get_remote_state ();
2148 struct gdb_ext_thread_info threadinfo;
2149 static char display_buf[100]; /* arbitrary... */
2150 int n = 0; /* position in display_buf */
2152 if (remote_desc == 0) /* paranoia */
2153 internal_error (__FILE__, __LINE__,
2154 _("remote_threads_extra_info"));
2156 if (ptid_equal (tp->ptid, magic_null_ptid)
2157 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_tid (tp->ptid) == 0))
2158 /* This is the main thread which was added by GDB. The remote
2159 server doesn't know about it. */
2162 if (use_threadextra_query)
2165 char *endb = rs->buf + get_remote_packet_size ();
2167 xsnprintf (b, endb - b, "qThreadExtraInfo,");
2169 write_ptid (b, endb, tp->ptid);
2172 getpkt (&rs->buf, &rs->buf_size, 0);
2173 if (rs->buf[0] != 0)
2175 n = min (strlen (rs->buf) / 2, sizeof (display_buf));
2176 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
2177 display_buf [result] = '\0';
2182 /* If the above query fails, fall back to the old method. */
2183 use_threadextra_query = 0;
2184 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
2185 | TAG_MOREDISPLAY | TAG_DISPLAY;
2186 int_to_threadref (&id, ptid_get_tid (tp->ptid));
2187 if (remote_get_threadinfo (&id, set, &threadinfo))
2188 if (threadinfo.active)
2190 if (*threadinfo.shortname)
2191 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
2192 " Name: %s,", threadinfo.shortname);
2193 if (*threadinfo.display)
2194 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
2195 " State: %s,", threadinfo.display);
2196 if (*threadinfo.more_display)
2197 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
2198 " Priority: %s", threadinfo.more_display);
2202 /* For purely cosmetic reasons, clear up trailing commas. */
2203 if (',' == display_buf[n-1])
2204 display_buf[n-1] = ' ';
2212 /* Restart the remote side; this is an extended protocol operation. */
2215 extended_remote_restart (void)
2217 struct remote_state *rs = get_remote_state ();
2219 /* Send the restart command; for reasons I don't understand the
2220 remote side really expects a number after the "R". */
2221 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
2224 remote_fileio_reset ();
2227 /* Clean up connection to a remote debugger. */
2230 remote_close (int quitting)
2234 /* Unregister the file descriptor from the event loop. */
2235 if (target_is_async_p ())
2236 target_async (NULL, 0);
2237 serial_close (remote_desc);
2241 /* Make sure we don't leave the async SIGINT signal handler
2243 signal (SIGINT, handle_sigint);
2245 /* We don't have a connection to the remote stub anymore. Get rid
2246 of all the inferiors and their threads we were controlling. */
2247 discard_all_inferiors ();
2249 generic_mourn_inferior ();
2252 /* Query the remote side for the text, data and bss offsets. */
2257 struct remote_state *rs = get_remote_state ();
2260 int lose, num_segments = 0, do_sections, do_segments;
2261 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
2262 struct section_offsets *offs;
2263 struct symfile_segment_data *data;
2265 if (symfile_objfile == NULL)
2268 putpkt ("qOffsets");
2269 getpkt (&rs->buf, &rs->buf_size, 0);
2272 if (buf[0] == '\000')
2273 return; /* Return silently. Stub doesn't support
2277 warning (_("Remote failure reply: %s"), buf);
2281 /* Pick up each field in turn. This used to be done with scanf, but
2282 scanf will make trouble if CORE_ADDR size doesn't match
2283 conversion directives correctly. The following code will work
2284 with any size of CORE_ADDR. */
2285 text_addr = data_addr = bss_addr = 0;
2289 if (strncmp (ptr, "Text=", 5) == 0)
2292 /* Don't use strtol, could lose on big values. */
2293 while (*ptr && *ptr != ';')
2294 text_addr = (text_addr << 4) + fromhex (*ptr++);
2296 if (strncmp (ptr, ";Data=", 6) == 0)
2299 while (*ptr && *ptr != ';')
2300 data_addr = (data_addr << 4) + fromhex (*ptr++);
2305 if (!lose && strncmp (ptr, ";Bss=", 5) == 0)
2308 while (*ptr && *ptr != ';')
2309 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
2311 if (bss_addr != data_addr)
2312 warning (_("Target reported unsupported offsets: %s"), buf);
2317 else if (strncmp (ptr, "TextSeg=", 8) == 0)
2320 /* Don't use strtol, could lose on big values. */
2321 while (*ptr && *ptr != ';')
2322 text_addr = (text_addr << 4) + fromhex (*ptr++);
2325 if (strncmp (ptr, ";DataSeg=", 9) == 0)
2328 while (*ptr && *ptr != ';')
2329 data_addr = (data_addr << 4) + fromhex (*ptr++);
2337 error (_("Malformed response to offset query, %s"), buf);
2338 else if (*ptr != '\0')
2339 warning (_("Target reported unsupported offsets: %s"), buf);
2341 offs = ((struct section_offsets *)
2342 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
2343 memcpy (offs, symfile_objfile->section_offsets,
2344 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
2346 data = get_symfile_segment_data (symfile_objfile->obfd);
2347 do_segments = (data != NULL);
2348 do_sections = num_segments == 0;
2350 if (num_segments > 0)
2352 segments[0] = text_addr;
2353 segments[1] = data_addr;
2355 /* If we have two segments, we can still try to relocate everything
2356 by assuming that the .text and .data offsets apply to the whole
2357 text and data segments. Convert the offsets given in the packet
2358 to base addresses for symfile_map_offsets_to_segments. */
2359 else if (data && data->num_segments == 2)
2361 segments[0] = data->segment_bases[0] + text_addr;
2362 segments[1] = data->segment_bases[1] + data_addr;
2365 /* If the object file has only one segment, assume that it is text
2366 rather than data; main programs with no writable data are rare,
2367 but programs with no code are useless. Of course the code might
2368 have ended up in the data segment... to detect that we would need
2369 the permissions here. */
2370 else if (data && data->num_segments == 1)
2372 segments[0] = data->segment_bases[0] + text_addr;
2375 /* There's no way to relocate by segment. */
2381 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
2382 offs, num_segments, segments);
2384 if (ret == 0 && !do_sections)
2385 error (_("Can not handle qOffsets TextSeg response with this symbol file"));
2392 free_symfile_segment_data (data);
2396 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
2398 /* This is a temporary kludge to force data and bss to use the same offsets
2399 because that's what nlmconv does now. The real solution requires changes
2400 to the stub and remote.c that I don't have time to do right now. */
2402 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
2403 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
2406 objfile_relocate (symfile_objfile, offs);
2409 /* Stub for catch_exception. */
2411 struct start_remote_args
2415 /* The current target. */
2416 struct target_ops *target;
2418 /* Non-zero if this is an extended-remote target. */
2423 remote_start_remote (struct ui_out *uiout, void *opaque)
2425 struct start_remote_args *args = opaque;
2426 struct remote_state *rs = get_remote_state ();
2427 struct packet_config *noack_config;
2428 char *wait_status = NULL;
2430 immediate_quit++; /* Allow user to interrupt it. */
2432 /* Ack any packet which the remote side has already sent. */
2433 serial_write (remote_desc, "+", 1);
2435 /* The first packet we send to the target is the optional "supported
2436 packets" request. If the target can answer this, it will tell us
2437 which later probes to skip. */
2438 remote_query_supported ();
2440 /* Next, we possibly activate noack mode.
2442 If the QStartNoAckMode packet configuration is set to AUTO,
2443 enable noack mode if the stub reported a wish for it with
2446 If set to TRUE, then enable noack mode even if the stub didn't
2447 report it in qSupported. If the stub doesn't reply OK, the
2448 session ends with an error.
2450 If FALSE, then don't activate noack mode, regardless of what the
2451 stub claimed should be the default with qSupported. */
2453 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
2455 if (noack_config->detect == AUTO_BOOLEAN_TRUE
2456 || (noack_config->detect == AUTO_BOOLEAN_AUTO
2457 && noack_config->support == PACKET_ENABLE))
2459 putpkt ("QStartNoAckMode");
2460 getpkt (&rs->buf, &rs->buf_size, 0);
2461 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
2465 if (args->extended_p)
2467 /* Tell the remote that we are using the extended protocol. */
2469 getpkt (&rs->buf, &rs->buf_size, 0);
2472 /* Next, if the target can specify a description, read it. We do
2473 this before anything involving memory or registers. */
2474 target_find_description ();
2476 /* Check whether the target is running now. */
2478 getpkt (&rs->buf, &rs->buf_size, 0);
2480 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
2482 if (args->extended_p)
2484 /* We're connected, but not running. Drop out before we
2485 call start_remote. */
2486 target_mark_exited (args->target);
2490 error (_("The target is not running (try extended-remote?)"));
2494 if (args->extended_p)
2495 target_mark_running (args->target);
2497 /* Save the reply for later. */
2498 wait_status = alloca (strlen (rs->buf) + 1);
2499 strcpy (wait_status, rs->buf);
2503 init_thread_list ();
2505 /* Let the stub know that we want it to return the thread. */
2506 set_continue_thread (minus_one_ptid);
2508 /* Without this, some commands which require an active target
2509 (such as kill) won't work. This variable serves (at least)
2510 double duty as both the pid of the target process (if it has
2511 such), and as a flag indicating that a target is active.
2512 These functions should be split out into seperate variables,
2513 especially since GDB will someday have a notion of debugging
2514 several processes. */
2515 inferior_ptid = magic_null_ptid;
2517 /* Now, if we have thread information, update inferior_ptid. */
2518 inferior_ptid = remote_current_thread (inferior_ptid);
2520 add_inferior (ptid_get_pid (inferior_ptid));
2522 /* Always add the main thread. */
2523 add_thread_silent (inferior_ptid);
2525 get_offsets (); /* Get text, data & bss offsets. */
2527 /* Use the previously fetched status. */
2528 gdb_assert (wait_status != NULL);
2529 strcpy (rs->buf, wait_status);
2530 rs->cached_wait_status = 1;
2533 start_remote (args->from_tty); /* Initialize gdb process mechanisms. */
2535 /* If we connected to a live target, do some additional setup. */
2536 if (target_has_execution)
2538 if (exec_bfd) /* No use without an exec file. */
2539 remote_check_symbols (symfile_objfile);
2543 /* Open a connection to a remote debugger.
2544 NAME is the filename used for communication. */
2547 remote_open (char *name, int from_tty)
2549 remote_open_1 (name, from_tty, &remote_ops, 0);
2552 /* Open a connection to a remote debugger using the extended
2553 remote gdb protocol. NAME is the filename used for communication. */
2556 extended_remote_open (char *name, int from_tty)
2558 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
2561 /* Generic code for opening a connection to a remote target. */
2564 init_all_packet_configs (void)
2567 for (i = 0; i < PACKET_MAX; i++)
2568 update_packet_config (&remote_protocol_packets[i]);
2571 /* Symbol look-up. */
2574 remote_check_symbols (struct objfile *objfile)
2576 struct remote_state *rs = get_remote_state ();
2577 char *msg, *reply, *tmp;
2578 struct minimal_symbol *sym;
2581 if (remote_protocol_packets[PACKET_qSymbol].support == PACKET_DISABLE)
2584 /* Make sure the remote is pointing at the right process. */
2585 set_general_process ();
2587 /* Allocate a message buffer. We can't reuse the input buffer in RS,
2588 because we need both at the same time. */
2589 msg = alloca (get_remote_packet_size ());
2591 /* Invite target to request symbol lookups. */
2593 putpkt ("qSymbol::");
2594 getpkt (&rs->buf, &rs->buf_size, 0);
2595 packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSymbol]);
2598 while (strncmp (reply, "qSymbol:", 8) == 0)
2601 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
2603 sym = lookup_minimal_symbol (msg, NULL, NULL);
2605 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
2608 CORE_ADDR sym_addr = SYMBOL_VALUE_ADDRESS (sym);
2610 /* If this is a function address, return the start of code
2611 instead of any data function descriptor. */
2612 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch,
2616 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
2617 paddr_nz (sym_addr), &reply[8]);
2621 getpkt (&rs->buf, &rs->buf_size, 0);
2626 static struct serial *
2627 remote_serial_open (char *name)
2629 static int udp_warning = 0;
2631 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
2632 of in ser-tcp.c, because it is the remote protocol assuming that the
2633 serial connection is reliable and not the serial connection promising
2635 if (!udp_warning && strncmp (name, "udp:", 4) == 0)
2638 The remote protocol may be unreliable over UDP.\n\
2639 Some events may be lost, rendering further debugging impossible."));
2643 return serial_open (name);
2646 /* This type describes each known response to the qSupported
2648 struct protocol_feature
2650 /* The name of this protocol feature. */
2653 /* The default for this protocol feature. */
2654 enum packet_support default_support;
2656 /* The function to call when this feature is reported, or after
2657 qSupported processing if the feature is not supported.
2658 The first argument points to this structure. The second
2659 argument indicates whether the packet requested support be
2660 enabled, disabled, or probed (or the default, if this function
2661 is being called at the end of processing and this feature was
2662 not reported). The third argument may be NULL; if not NULL, it
2663 is a NUL-terminated string taken from the packet following
2664 this feature's name and an equals sign. */
2665 void (*func) (const struct protocol_feature *, enum packet_support,
2668 /* The corresponding packet for this feature. Only used if
2669 FUNC is remote_supported_packet. */
2674 remote_supported_packet (const struct protocol_feature *feature,
2675 enum packet_support support,
2676 const char *argument)
2680 warning (_("Remote qSupported response supplied an unexpected value for"
2681 " \"%s\"."), feature->name);
2685 if (remote_protocol_packets[feature->packet].support
2686 == PACKET_SUPPORT_UNKNOWN)
2687 remote_protocol_packets[feature->packet].support = support;
2691 remote_packet_size (const struct protocol_feature *feature,
2692 enum packet_support support, const char *value)
2694 struct remote_state *rs = get_remote_state ();
2699 if (support != PACKET_ENABLE)
2702 if (value == NULL || *value == '\0')
2704 warning (_("Remote target reported \"%s\" without a size."),
2710 packet_size = strtol (value, &value_end, 16);
2711 if (errno != 0 || *value_end != '\0' || packet_size < 0)
2713 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
2714 feature->name, value);
2718 if (packet_size > MAX_REMOTE_PACKET_SIZE)
2720 warning (_("limiting remote suggested packet size (%d bytes) to %d"),
2721 packet_size, MAX_REMOTE_PACKET_SIZE);
2722 packet_size = MAX_REMOTE_PACKET_SIZE;
2725 /* Record the new maximum packet size. */
2726 rs->explicit_packet_size = packet_size;
2730 remote_multi_process_feature (const struct protocol_feature *feature,
2731 enum packet_support support, const char *value)
2733 struct remote_state *rs = get_remote_state ();
2734 rs->multi_process_aware = (support == PACKET_ENABLE);
2737 static struct protocol_feature remote_protocol_features[] = {
2738 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
2739 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
2740 PACKET_qXfer_auxv },
2741 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
2742 PACKET_qXfer_features },
2743 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
2744 PACKET_qXfer_libraries },
2745 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
2746 PACKET_qXfer_memory_map },
2747 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
2748 PACKET_qXfer_spu_read },
2749 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
2750 PACKET_qXfer_spu_write },
2751 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
2752 PACKET_QPassSignals },
2753 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
2754 PACKET_QStartNoAckMode },
2755 { "multiprocess", PACKET_DISABLE, remote_multi_process_feature, -1 },
2759 remote_query_supported (void)
2761 struct remote_state *rs = get_remote_state ();
2764 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
2766 /* The packet support flags are handled differently for this packet
2767 than for most others. We treat an error, a disabled packet, and
2768 an empty response identically: any features which must be reported
2769 to be used will be automatically disabled. An empty buffer
2770 accomplishes this, since that is also the representation for a list
2771 containing no features. */
2774 if (remote_protocol_packets[PACKET_qSupported].support != PACKET_DISABLE)
2777 putpkt ("qSupported:multiprocess+");
2779 putpkt ("qSupported");
2781 getpkt (&rs->buf, &rs->buf_size, 0);
2783 /* If an error occured, warn, but do not return - just reset the
2784 buffer to empty and go on to disable features. */
2785 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
2788 warning (_("Remote failure reply: %s"), rs->buf);
2793 memset (seen, 0, sizeof (seen));
2798 enum packet_support is_supported;
2799 char *p, *end, *name_end, *value;
2801 /* First separate out this item from the rest of the packet. If
2802 there's another item after this, we overwrite the separator
2803 (terminated strings are much easier to work with). */
2805 end = strchr (p, ';');
2808 end = p + strlen (p);
2818 warning (_("empty item in \"qSupported\" response"));
2823 name_end = strchr (p, '=');
2826 /* This is a name=value entry. */
2827 is_supported = PACKET_ENABLE;
2828 value = name_end + 1;
2837 is_supported = PACKET_ENABLE;
2841 is_supported = PACKET_DISABLE;
2845 is_supported = PACKET_SUPPORT_UNKNOWN;
2849 warning (_("unrecognized item \"%s\" in \"qSupported\" response"), p);
2855 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
2856 if (strcmp (remote_protocol_features[i].name, p) == 0)
2858 const struct protocol_feature *feature;
2861 feature = &remote_protocol_features[i];
2862 feature->func (feature, is_supported, value);
2867 /* If we increased the packet size, make sure to increase the global
2868 buffer size also. We delay this until after parsing the entire
2869 qSupported packet, because this is the same buffer we were
2871 if (rs->buf_size < rs->explicit_packet_size)
2873 rs->buf_size = rs->explicit_packet_size;
2874 rs->buf = xrealloc (rs->buf, rs->buf_size);
2877 /* Handle the defaults for unmentioned features. */
2878 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
2881 const struct protocol_feature *feature;
2883 feature = &remote_protocol_features[i];
2884 feature->func (feature, feature->default_support, NULL);
2890 remote_open_1 (char *name, int from_tty, struct target_ops *target, int extended_p)
2892 struct remote_state *rs = get_remote_state ();
2895 error (_("To open a remote debug connection, you need to specify what\n"
2896 "serial device is attached to the remote system\n"
2897 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
2899 /* See FIXME above. */
2900 if (!target_async_permitted)
2901 wait_forever_enabled_p = 1;
2903 /* If we're connected to a running target, target_preopen will kill it.
2904 But if we're connected to a target system with no running process,
2905 then we will still be connected when it returns. Ask this question
2906 first, before target_preopen has a chance to kill anything. */
2907 if (remote_desc != NULL && !target_has_execution)
2910 || query (_("Already connected to a remote target. Disconnect? ")))
2913 error (_("Still connected."));
2916 target_preopen (from_tty);
2918 unpush_target (target);
2920 /* This time without a query. If we were connected to an
2921 extended-remote target and target_preopen killed the running
2922 process, we may still be connected. If we are starting "target
2923 remote" now, the extended-remote target will not have been
2924 removed by unpush_target. */
2925 if (remote_desc != NULL && !target_has_execution)
2928 /* Make sure we send the passed signals list the next time we resume. */
2929 xfree (last_pass_packet);
2930 last_pass_packet = NULL;
2932 remote_fileio_reset ();
2933 reopen_exec_file ();
2936 remote_desc = remote_serial_open (name);
2938 perror_with_name (name);
2940 if (baud_rate != -1)
2942 if (serial_setbaudrate (remote_desc, baud_rate))
2944 /* The requested speed could not be set. Error out to
2945 top level after closing remote_desc. Take care to
2946 set remote_desc to NULL to avoid closing remote_desc
2948 serial_close (remote_desc);
2950 perror_with_name (name);
2954 serial_raw (remote_desc);
2956 /* If there is something sitting in the buffer we might take it as a
2957 response to a command, which would be bad. */
2958 serial_flush_input (remote_desc);
2962 puts_filtered ("Remote debugging using ");
2963 puts_filtered (name);
2964 puts_filtered ("\n");
2966 push_target (target); /* Switch to using remote target now. */
2968 /* Assume that the target is running, unless we learn otherwise. */
2969 target_mark_running (target);
2971 /* Reset the target state; these things will be queried either by
2972 remote_query_supported or as they are needed. */
2973 init_all_packet_configs ();
2974 rs->explicit_packet_size = 0;
2976 rs->multi_process_aware = 0;
2977 rs->extended = extended_p;
2978 rs->waiting_for_stop_reply = 0;
2980 general_thread = not_sent_ptid;
2981 continue_thread = not_sent_ptid;
2983 /* Probe for ability to use "ThreadInfo" query, as required. */
2984 use_threadinfo_query = 1;
2985 use_threadextra_query = 1;
2987 if (target_async_permitted)
2989 /* With this target we start out by owning the terminal. */
2990 remote_async_terminal_ours_p = 1;
2992 /* FIXME: cagney/1999-09-23: During the initial connection it is
2993 assumed that the target is already ready and able to respond to
2994 requests. Unfortunately remote_start_remote() eventually calls
2995 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
2996 around this. Eventually a mechanism that allows
2997 wait_for_inferior() to expect/get timeouts will be
2999 wait_forever_enabled_p = 0;
3002 /* First delete any symbols previously loaded from shared libraries. */
3003 no_shared_libraries (NULL, 0);
3005 /* Start the remote connection. If error() or QUIT, discard this
3006 target (we'd otherwise be in an inconsistent state) and then
3007 propogate the error on up the exception chain. This ensures that
3008 the caller doesn't stumble along blindly assuming that the
3009 function succeeded. The CLI doesn't have this problem but other
3010 UI's, such as MI do.
3012 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
3013 this function should return an error indication letting the
3014 caller restore the previous state. Unfortunately the command
3015 ``target remote'' is directly wired to this function making that
3016 impossible. On a positive note, the CLI side of this problem has
3017 been fixed - the function set_cmd_context() makes it possible for
3018 all the ``target ....'' commands to share a common callback
3019 function. See cli-dump.c. */
3021 struct gdb_exception ex;
3022 struct start_remote_args args;
3024 args.from_tty = from_tty;
3025 args.target = target;
3026 args.extended_p = extended_p;
3028 ex = catch_exception (uiout, remote_start_remote, &args, RETURN_MASK_ALL);
3031 /* Pop the partially set up target - unless something else did
3032 already before throwing the exception. */
3033 if (remote_desc != NULL)
3035 if (target_async_permitted)
3036 wait_forever_enabled_p = 1;
3037 throw_exception (ex);
3041 if (target_async_permitted)
3042 wait_forever_enabled_p = 1;
3045 /* This takes a program previously attached to and detaches it. After
3046 this is done, GDB can be used to debug some other program. We
3047 better not have left any breakpoints in the target program or it'll
3048 die when it hits one. */
3051 remote_detach_1 (char *args, int from_tty, int extended)
3053 int pid = ptid_get_pid (inferior_ptid);
3054 struct remote_state *rs = get_remote_state ();
3057 error (_("Argument given to \"detach\" when remotely debugging."));
3059 if (!target_has_execution)
3060 error (_("No process to detach from."));
3062 /* Tell the remote target to detach. */
3063 if (remote_multi_process_p (rs))
3064 sprintf (rs->buf, "D;%x", pid);
3066 strcpy (rs->buf, "D");
3069 getpkt (&rs->buf, &rs->buf_size, 0);
3071 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
3073 else if (rs->buf[0] == '\0')
3074 error (_("Remote doesn't know how to detach"));
3076 error (_("Can't detach process."));
3080 if (remote_multi_process_p (rs))
3081 printf_filtered (_("Detached from remote %s.\n"),
3082 target_pid_to_str (pid_to_ptid (pid)));
3086 puts_filtered (_("Detached from remote process.\n"));
3088 puts_filtered (_("Ending remote debugging.\n"));
3092 detach_inferior (pid);
3093 target_mourn_inferior ();
3097 remote_detach (char *args, int from_tty)
3099 remote_detach_1 (args, from_tty, 0);
3103 extended_remote_detach (char *args, int from_tty)
3105 remote_detach_1 (args, from_tty, 1);
3108 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
3111 remote_disconnect (struct target_ops *target, char *args, int from_tty)
3114 error (_("Argument given to \"disconnect\" when remotely debugging."));
3116 /* Make sure we unpush even the extended remote targets; mourn
3117 won't do it. So call remote_mourn_1 directly instead of
3118 target_mourn_inferior. */
3119 remote_mourn_1 (target);
3122 puts_filtered ("Ending remote debugging.\n");
3125 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
3126 be chatty about it. */
3129 extended_remote_attach_1 (struct target_ops *target, char *args, int from_tty)
3131 struct remote_state *rs = get_remote_state ();
3134 char *wait_status = NULL;
3135 struct inferior *inf;
3138 error_no_arg (_("process-id to attach"));
3141 pid = strtol (args, &dummy, 0);
3142 /* Some targets don't set errno on errors, grrr! */
3143 if (pid == 0 && args == dummy)
3144 error (_("Illegal process-id: %s."), args);
3146 if (remote_protocol_packets[PACKET_vAttach].support == PACKET_DISABLE)
3147 error (_("This target does not support attaching to a process"));
3149 sprintf (rs->buf, "vAttach;%x", pid);
3151 getpkt (&rs->buf, &rs->buf_size, 0);
3153 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vAttach]) == PACKET_OK)
3156 printf_unfiltered (_("Attached to %s\n"),
3157 target_pid_to_str (pid_to_ptid (pid)));
3159 /* Save the reply for later. */
3160 wait_status = alloca (strlen (rs->buf) + 1);
3161 strcpy (wait_status, rs->buf);
3163 else if (remote_protocol_packets[PACKET_vAttach].support == PACKET_DISABLE)
3164 error (_("This target does not support attaching to a process"));
3166 error (_("Attaching to %s failed"),
3167 target_pid_to_str (pid_to_ptid (pid)));
3169 target_mark_running (target);
3170 inferior_ptid = pid_to_ptid (pid);
3172 /* Now, if we have thread information, update inferior_ptid. */
3173 inferior_ptid = remote_current_thread (inferior_ptid);
3175 inf = add_inferior (pid);
3176 inf->attach_flag = 1;
3178 /* Now, add the main thread to the thread list. */
3179 add_thread_silent (inferior_ptid);
3181 /* Next, if the target can specify a description, read it. We do
3182 this before anything involving memory or registers. */
3183 target_find_description ();
3185 /* Use the previously fetched status. */
3186 gdb_assert (wait_status != NULL);
3187 strcpy (rs->buf, wait_status);
3188 rs->cached_wait_status = 1;
3192 extended_remote_attach (char *args, int from_tty)
3194 extended_remote_attach_1 (&extended_remote_ops, args, from_tty);
3197 /* Convert hex digit A to a number. */
3202 if (a >= '0' && a <= '9')
3204 else if (a >= 'a' && a <= 'f')
3205 return a - 'a' + 10;
3206 else if (a >= 'A' && a <= 'F')
3207 return a - 'A' + 10;
3209 error (_("Reply contains invalid hex digit %d"), a);
3213 hex2bin (const char *hex, gdb_byte *bin, int count)
3217 for (i = 0; i < count; i++)
3219 if (hex[0] == 0 || hex[1] == 0)
3221 /* Hex string is short, or of uneven length.
3222 Return the count that has been converted so far. */
3225 *bin++ = fromhex (hex[0]) * 16 + fromhex (hex[1]);
3231 /* Convert number NIB to a hex digit. */
3239 return 'a' + nib - 10;
3243 bin2hex (const gdb_byte *bin, char *hex, int count)
3246 /* May use a length, or a nul-terminated string as input. */
3248 count = strlen ((char *) bin);
3250 for (i = 0; i < count; i++)
3252 *hex++ = tohex ((*bin >> 4) & 0xf);
3253 *hex++ = tohex (*bin++ & 0xf);
3259 /* Check for the availability of vCont. This function should also check
3263 remote_vcont_probe (struct remote_state *rs)
3267 strcpy (rs->buf, "vCont?");
3269 getpkt (&rs->buf, &rs->buf_size, 0);
3272 /* Make sure that the features we assume are supported. */
3273 if (strncmp (buf, "vCont", 5) == 0)
3276 int support_s, support_S, support_c, support_C;
3282 while (p && *p == ';')
3285 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
3287 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
3289 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
3291 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
3294 p = strchr (p, ';');
3297 /* If s, S, c, and C are not all supported, we can't use vCont. Clearing
3298 BUF will make packet_ok disable the packet. */
3299 if (!support_s || !support_S || !support_c || !support_C)
3303 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
3306 /* Resume the remote inferior by using a "vCont" packet. The thread
3307 to be resumed is PTID; STEP and SIGGNAL indicate whether the
3308 resumed thread should be single-stepped and/or signalled. If PTID
3309 equals minus_one_ptid, then all threads are resumed; the thread to
3310 be stepped and/or signalled is given in the global INFERIOR_PTID.
3311 This function returns non-zero iff it resumes the inferior.
3313 This function issues a strict subset of all possible vCont commands at the
3317 remote_vcont_resume (ptid_t ptid, int step, enum target_signal siggnal)
3319 struct remote_state *rs = get_remote_state ();
3323 if (remote_protocol_packets[PACKET_vCont].support == PACKET_SUPPORT_UNKNOWN)
3324 remote_vcont_probe (rs);
3326 if (remote_protocol_packets[PACKET_vCont].support == PACKET_DISABLE)
3330 endp = rs->buf + get_remote_packet_size ();
3332 /* If we could generate a wider range of packets, we'd have to worry
3333 about overflowing BUF. Should there be a generic
3334 "multi-part-packet" packet? */
3336 if (ptid_equal (ptid, magic_null_ptid))
3338 /* MAGIC_NULL_PTID means that we don't have any active threads,
3339 so we don't have any TID numbers the inferior will
3340 understand. Make sure to only send forms that do not specify
3342 if (step && siggnal != TARGET_SIGNAL_0)
3343 xsnprintf (p, endp - p, "vCont;S%02x", siggnal);
3345 xsnprintf (p, endp - p, "vCont;s");
3346 else if (siggnal != TARGET_SIGNAL_0)
3347 xsnprintf (p, endp - p, "vCont;C%02x", siggnal);
3349 xsnprintf (p, endp - p, "vCont;c");
3351 else if (ptid_equal (ptid, minus_one_ptid))
3353 /* Resume all threads, with preference for INFERIOR_PTID. */
3354 if (step && siggnal != TARGET_SIGNAL_0)
3356 /* Step inferior_ptid with signal. */
3357 p += xsnprintf (p, endp - p, "vCont;S%02x:", siggnal);
3358 p = write_ptid (p, endp, inferior_ptid);
3359 /* And continue others. */
3360 p += xsnprintf (p, endp - p, ";c");
3364 /* Step inferior_ptid. */
3365 p += xsnprintf (p, endp - p, "vCont;s:");
3366 p = write_ptid (p, endp, inferior_ptid);
3367 /* And continue others. */
3368 p += xsnprintf (p, endp - p, ";c");
3370 else if (siggnal != TARGET_SIGNAL_0)
3372 /* Continue inferior_ptid with signal. */
3373 p += xsnprintf (p, endp - p, "vCont;C%02x:", siggnal);
3374 p = write_ptid (p, endp, inferior_ptid);
3375 /* And continue others. */
3376 p += xsnprintf (p, endp - p, ";c");
3379 xsnprintf (p, endp - p, "vCont;c");
3383 /* Scheduler locking; resume only PTID. */
3384 if (step && siggnal != TARGET_SIGNAL_0)
3386 /* Step ptid with signal. */
3387 p += xsnprintf (p, endp - p, "vCont;S%02x:", siggnal);
3388 p = write_ptid (p, endp, ptid);
3393 p += xsnprintf (p, endp - p, "vCont;s:");
3394 p = write_ptid (p, endp, ptid);
3396 else if (siggnal != TARGET_SIGNAL_0)
3398 /* Continue ptid with signal. */
3399 p += xsnprintf (p, endp - p, "vCont;C%02x:", siggnal);
3400 p = write_ptid (p, endp, ptid);
3404 /* Continue ptid. */
3405 p += xsnprintf (p, endp - p, "vCont;c:");
3406 p = write_ptid (p, endp, ptid);
3410 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
3416 /* Tell the remote machine to resume. */
3418 static enum target_signal last_sent_signal = TARGET_SIGNAL_0;
3420 static int last_sent_step;
3423 remote_resume (ptid_t ptid, int step, enum target_signal siggnal)
3425 struct remote_state *rs = get_remote_state ();
3428 last_sent_signal = siggnal;
3429 last_sent_step = step;
3431 /* Update the inferior on signals to silently pass, if they've changed. */
3432 remote_pass_signals ();
3434 /* The vCont packet doesn't need to specify threads via Hc. */
3435 if (remote_vcont_resume (ptid, step, siggnal))
3438 /* All other supported resume packets do use Hc, so set the continue
3440 if (ptid_equal (ptid, minus_one_ptid))
3441 set_continue_thread (any_thread_ptid);
3443 set_continue_thread (ptid);
3446 if (execution_direction == EXEC_REVERSE)
3448 /* We don't pass signals to the target in reverse exec mode. */
3449 if (info_verbose && siggnal != TARGET_SIGNAL_0)
3450 warning (" - Can't pass signal %d to target in reverse: ignored.\n",
3452 strcpy (buf, step ? "bs" : "bc");
3454 else if (siggnal != TARGET_SIGNAL_0)
3456 buf[0] = step ? 'S' : 'C';
3457 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
3458 buf[2] = tohex (((int) siggnal) & 0xf);
3462 strcpy (buf, step ? "s" : "c");
3467 /* We are about to start executing the inferior, let's register it
3468 with the event loop. NOTE: this is the one place where all the
3469 execution commands end up. We could alternatively do this in each
3470 of the execution commands in infcmd.c. */
3471 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
3472 into infcmd.c in order to allow inferior function calls to work
3473 NOT asynchronously. */
3474 if (target_can_async_p ())
3475 target_async (inferior_event_handler, 0);
3477 /* We've just told the target to resume. The remote server will
3478 wait for the inferior to stop, and then send a stop reply. In
3479 the mean time, we can't start another command/query ourselves
3480 because the stub wouldn't be ready to process it. */
3481 rs->waiting_for_stop_reply = 1;
3485 /* Set up the signal handler for SIGINT, while the target is
3486 executing, ovewriting the 'regular' SIGINT signal handler. */
3488 initialize_sigint_signal_handler (void)
3490 signal (SIGINT, handle_remote_sigint);
3493 /* Signal handler for SIGINT, while the target is executing. */
3495 handle_remote_sigint (int sig)
3497 signal (sig, handle_remote_sigint_twice);
3498 mark_async_signal_handler_wrapper (sigint_remote_token);
3501 /* Signal handler for SIGINT, installed after SIGINT has already been
3502 sent once. It will take effect the second time that the user sends
3505 handle_remote_sigint_twice (int sig)
3507 signal (sig, handle_remote_sigint);
3508 mark_async_signal_handler_wrapper (sigint_remote_twice_token);
3511 /* Perform the real interruption of the target execution, in response
3514 async_remote_interrupt (gdb_client_data arg)
3517 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
3519 target_stop (inferior_ptid);
3522 /* Perform interrupt, if the first attempt did not succeed. Just give
3523 up on the target alltogether. */
3525 async_remote_interrupt_twice (gdb_client_data arg)
3528 fprintf_unfiltered (gdb_stdlog, "remote_interrupt_twice called\n");
3533 /* Reinstall the usual SIGINT handlers, after the target has
3536 cleanup_sigint_signal_handler (void *dummy)
3538 signal (SIGINT, handle_sigint);
3541 /* Send ^C to target to halt it. Target will respond, and send us a
3543 static void (*ofunc) (int);
3545 /* The command line interface's stop routine. This function is installed
3546 as a signal handler for SIGINT. The first time a user requests a
3547 stop, we call remote_stop to send a break or ^C. If there is no
3548 response from the target (it didn't stop when the user requested it),
3549 we ask the user if he'd like to detach from the target. */
3551 remote_interrupt (int signo)
3553 /* If this doesn't work, try more severe steps. */
3554 signal (signo, remote_interrupt_twice);
3556 gdb_call_async_signal_handler (sigint_remote_token, 1);
3559 /* The user typed ^C twice. */
3562 remote_interrupt_twice (int signo)
3564 signal (signo, ofunc);
3565 gdb_call_async_signal_handler (sigint_remote_twice_token, 1);
3566 signal (signo, remote_interrupt);
3569 /* This is the generic stop called via the target vector. When a target
3570 interrupt is requested, either by the command line or the GUI, we
3571 will eventually end up here. */
3573 remote_stop (ptid_t ptid)
3575 /* Send a break or a ^C, depending on user preference. */
3577 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
3580 serial_send_break (remote_desc);
3582 serial_write (remote_desc, "\003", 1);
3585 /* Ask the user what to do when an interrupt is received. */
3588 interrupt_query (void)
3590 target_terminal_ours ();
3592 if (query ("Interrupted while waiting for the program.\n\
3593 Give up (and stop debugging it)? "))
3596 deprecated_throw_reason (RETURN_QUIT);
3599 target_terminal_inferior ();
3602 /* Enable/disable target terminal ownership. Most targets can use
3603 terminal groups to control terminal ownership. Remote targets are
3604 different in that explicit transfer of ownership to/from GDB/target
3608 remote_terminal_inferior (void)
3610 if (!target_async_permitted)
3611 /* Nothing to do. */
3614 /* FIXME: cagney/1999-09-27: Shouldn't need to test for
3615 sync_execution here. This function should only be called when
3616 GDB is resuming the inferior in the forground. A background
3617 resume (``run&'') should leave GDB in control of the terminal and
3618 consequently should not call this code. */
3619 if (!sync_execution)
3621 /* FIXME: cagney/1999-09-27: Closely related to the above. Make
3622 calls target_terminal_*() idenpotent. The event-loop GDB talking
3623 to an asynchronous target with a synchronous command calls this
3624 function from both event-top.c and infrun.c/infcmd.c. Once GDB
3625 stops trying to transfer the terminal to the target when it
3626 shouldn't this guard can go away. */
3627 if (!remote_async_terminal_ours_p)
3629 delete_file_handler (input_fd);
3630 remote_async_terminal_ours_p = 0;
3631 initialize_sigint_signal_handler ();
3632 /* NOTE: At this point we could also register our selves as the
3633 recipient of all input. Any characters typed could then be
3634 passed on down to the target. */
3638 remote_terminal_ours (void)
3640 if (!target_async_permitted)
3641 /* Nothing to do. */
3644 /* See FIXME in remote_terminal_inferior. */
3645 if (!sync_execution)
3647 /* See FIXME in remote_terminal_inferior. */
3648 if (remote_async_terminal_ours_p)
3650 cleanup_sigint_signal_handler (NULL);
3651 add_file_handler (input_fd, stdin_event_handler, 0);
3652 remote_async_terminal_ours_p = 1;
3656 remote_console_output (char *msg)
3660 for (p = msg; p[0] && p[1]; p += 2)
3663 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
3666 fputs_unfiltered (tb, gdb_stdtarg);
3668 gdb_flush (gdb_stdtarg);
3671 /* Wait until the remote machine stops, then return,
3672 storing status in STATUS just as `wait' would. */
3675 remote_wait_as (ptid_t ptid, struct target_waitstatus *status)
3677 struct remote_state *rs = get_remote_state ();
3678 struct remote_arch_state *rsa = get_remote_arch_state ();
3679 ptid_t event_ptid = null_ptid;
3681 int solibs_changed = 0;
3682 int replay_event = 0;
3685 status->kind = TARGET_WAITKIND_IGNORE;
3686 status->value.integer = 0;
3688 if (rs->cached_wait_status)
3689 /* Use the cached wait status, but only once. */
3690 rs->cached_wait_status = 0;
3693 if (!target_is_async_p ())
3695 ofunc = signal (SIGINT, remote_interrupt);
3696 /* If the user hit C-c before this packet, or between
3697 packets, pretend that it was hit right here. */
3701 remote_interrupt (SIGINT);
3704 /* FIXME: cagney/1999-09-27: If we're in async mode we should
3705 _never_ wait for ever -> test on target_is_async_p().
3706 However, before we do that we need to ensure that the caller
3707 knows how to take the target into/out of async mode. */
3708 getpkt (&rs->buf, &rs->buf_size, wait_forever_enabled_p);
3709 if (!target_is_async_p ())
3710 signal (SIGINT, ofunc);
3715 remote_stopped_by_watchpoint_p = 0;
3717 /* We got something. */
3718 rs->waiting_for_stop_reply = 0;
3722 case 'E': /* Error of some sort. */
3723 /* We're out of sync with the target now. Did it continue or
3724 not? Not is more likely, so report a stop. */
3725 warning (_("Remote failure reply: %s"), buf);
3726 status->kind = TARGET_WAITKIND_STOPPED;
3727 status->value.sig = TARGET_SIGNAL_0;
3729 case 'F': /* File-I/O request. */
3730 remote_fileio_request (buf);
3732 /* This stop reply is special. We reply back to the stub,
3733 and keep waiting for the target to stop. */
3734 rs->waiting_for_stop_reply = 1;
3736 case 'T': /* Status with PC, SP, FP, ... */
3738 gdb_byte regs[MAX_REGISTER_SIZE];
3740 /* Expedited reply, containing Signal, {regno, reg} repeat. */
3741 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
3743 n... = register number
3744 r... = register contents
3746 p = &buf[3]; /* after Txx */
3755 /* If the packet contains a register number, save it in
3756 pnum and set p1 to point to the character following it.
3757 Otherwise p1 points to p. */
3759 /* If this packet is an awatch packet, don't parse the
3760 'a' as a register number. */
3762 if (strncmp (p, "awatch", strlen("awatch")) != 0)
3764 /* Read the ``P'' register number. */
3765 pnum = strtol (p, &p_temp, 16);
3771 if (p1 == p) /* No register number present here. */
3773 p1 = strchr (p, ':');
3775 error (_("Malformed packet(a) (missing colon): %s\n\
3778 if (strncmp (p, "thread", p1 - p) == 0)
3779 event_ptid = read_ptid (++p1, &p);
3780 else if ((strncmp (p, "watch", p1 - p) == 0)
3781 || (strncmp (p, "rwatch", p1 - p) == 0)
3782 || (strncmp (p, "awatch", p1 - p) == 0))
3784 remote_stopped_by_watchpoint_p = 1;
3785 p = unpack_varlen_hex (++p1, &addr);
3786 remote_watch_data_address = (CORE_ADDR)addr;
3788 else if (strncmp (p, "library", p1 - p) == 0)
3792 while (*p_temp && *p_temp != ';')
3798 else if (strncmp (p, "replaylog", p1 - p) == 0)
3800 /* NO_HISTORY event.
3801 p1 will indicate "begin" or "end", but
3802 it makes no difference for now, so ignore it. */
3804 p_temp = strchr (p1 + 1, ';');
3810 /* Silently skip unknown optional info. */
3811 p_temp = strchr (p1 + 1, ';');
3818 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
3822 error (_("Malformed packet(b) (missing colon): %s\n\
3828 error (_("Remote sent bad register number %s: %s\n\
3830 phex_nz (pnum, 0), p, buf);
3832 fieldsize = hex2bin (p, regs,
3833 register_size (target_gdbarch,
3836 if (fieldsize < register_size (target_gdbarch,
3838 warning (_("Remote reply is too short: %s"), buf);
3839 regcache_raw_supply (get_current_regcache (),
3844 error (_("Remote register badly formatted: %s\nhere: %s"),
3850 case 'S': /* Old style status, just signal only. */
3852 status->kind = TARGET_WAITKIND_LOADED;
3853 else if (replay_event)
3854 status->kind = TARGET_WAITKIND_NO_HISTORY;
3857 status->kind = TARGET_WAITKIND_STOPPED;
3858 status->value.sig = (enum target_signal)
3859 (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
3862 case 'W': /* Target exited. */
3869 /* GDB used to accept only 2 hex chars here. Stubs should
3870 only send more if they detect GDB supports multi-process
3872 p = unpack_varlen_hex (&buf[1], &value);
3876 /* The remote process exited. */
3877 status->kind = TARGET_WAITKIND_EXITED;
3878 status->value.integer = value;
3882 /* The remote process exited with a signal. */
3883 status->kind = TARGET_WAITKIND_SIGNALLED;
3884 status->value.sig = (enum target_signal) value;
3887 /* If no process is specified, assume inferior_ptid. */
3888 pid = ptid_get_pid (inferior_ptid);
3897 else if (strncmp (p,
3898 "process:", sizeof ("process:") - 1) == 0)
3901 p += sizeof ("process:") - 1;
3902 unpack_varlen_hex (p, &upid);
3906 error (_("unknown stop reply packet: %s"), buf);
3909 error (_("unknown stop reply packet: %s"), buf);
3910 event_ptid = pid_to_ptid (pid);
3913 case 'O': /* Console output. */
3914 remote_console_output (buf + 1);
3916 /* The target didn't really stop; keep waiting. */
3917 rs->waiting_for_stop_reply = 1;
3921 if (last_sent_signal != TARGET_SIGNAL_0)
3923 /* Zero length reply means that we tried 'S' or 'C' and the
3924 remote system doesn't support it. */
3925 target_terminal_ours_for_output ();
3927 ("Can't send signals to this remote system. %s not sent.\n",
3928 target_signal_to_name (last_sent_signal));
3929 last_sent_signal = TARGET_SIGNAL_0;
3930 target_terminal_inferior ();
3932 strcpy ((char *) buf, last_sent_step ? "s" : "c");
3933 putpkt ((char *) buf);
3935 /* We just told the target to resume, so a stop reply is in
3937 rs->waiting_for_stop_reply = 1;
3940 /* else fallthrough */
3942 warning (_("Invalid remote reply: %s"), buf);
3944 rs->waiting_for_stop_reply = 1;
3948 /* Nothing interesting happened. */
3949 if (status->kind == TARGET_WAITKIND_IGNORE)
3950 return minus_one_ptid;
3952 if (status->kind == TARGET_WAITKIND_EXITED
3953 || status->kind == TARGET_WAITKIND_SIGNALLED)
3955 int pid = ptid_get_pid (event_ptid);
3956 delete_inferior (pid);
3960 if (!ptid_equal (event_ptid, null_ptid))
3961 record_currthread (event_ptid);
3963 event_ptid = inferior_ptid;
3970 remote_wait (ptid_t ptid, struct target_waitstatus *status)
3974 /* In synchronous mode, keep waiting until the target stops. In
3975 asynchronous mode, always return to the event loop. */
3979 event_ptid = remote_wait_as (ptid, status);
3981 while (status->kind == TARGET_WAITKIND_IGNORE
3982 && !target_can_async_p ());
3987 /* Fetch a single register using a 'p' packet. */
3990 fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
3992 struct remote_state *rs = get_remote_state ();
3994 char regp[MAX_REGISTER_SIZE];
3997 if (remote_protocol_packets[PACKET_p].support == PACKET_DISABLE)
4000 if (reg->pnum == -1)
4005 p += hexnumstr (p, reg->pnum);
4007 remote_send (&rs->buf, &rs->buf_size);
4011 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
4015 case PACKET_UNKNOWN:
4018 error (_("Could not fetch register \"%s\""),
4019 gdbarch_register_name (get_regcache_arch (regcache), reg->regnum));
4022 /* If this register is unfetchable, tell the regcache. */
4025 regcache_raw_supply (regcache, reg->regnum, NULL);
4029 /* Otherwise, parse and supply the value. */
4035 error (_("fetch_register_using_p: early buf termination"));
4037 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
4040 regcache_raw_supply (regcache, reg->regnum, regp);
4044 /* Fetch the registers included in the target's 'g' packet. */
4047 send_g_packet (void)
4049 struct remote_state *rs = get_remote_state ();
4054 sprintf (rs->buf, "g");
4055 remote_send (&rs->buf, &rs->buf_size);
4057 /* We can get out of synch in various cases. If the first character
4058 in the buffer is not a hex character, assume that has happened
4059 and try to fetch another packet to read. */
4060 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
4061 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
4062 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
4063 && rs->buf[0] != 'x') /* New: unavailable register value. */
4066 fprintf_unfiltered (gdb_stdlog,
4067 "Bad register packet; fetching a new packet\n");
4068 getpkt (&rs->buf, &rs->buf_size, 0);
4071 buf_len = strlen (rs->buf);
4073 /* Sanity check the received packet. */
4074 if (buf_len % 2 != 0)
4075 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
4081 process_g_packet (struct regcache *regcache)
4083 struct gdbarch *gdbarch = get_regcache_arch (regcache);
4084 struct remote_state *rs = get_remote_state ();
4085 struct remote_arch_state *rsa = get_remote_arch_state ();
4090 buf_len = strlen (rs->buf);
4092 /* Further sanity checks, with knowledge of the architecture. */
4093 if (buf_len > 2 * rsa->sizeof_g_packet)
4094 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
4096 /* Save the size of the packet sent to us by the target. It is used
4097 as a heuristic when determining the max size of packets that the
4098 target can safely receive. */
4099 if (rsa->actual_register_packet_size == 0)
4100 rsa->actual_register_packet_size = buf_len;
4102 /* If this is smaller than we guessed the 'g' packet would be,
4103 update our records. A 'g' reply that doesn't include a register's
4104 value implies either that the register is not available, or that
4105 the 'p' packet must be used. */
4106 if (buf_len < 2 * rsa->sizeof_g_packet)
4108 rsa->sizeof_g_packet = buf_len / 2;
4110 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
4112 if (rsa->regs[i].pnum == -1)
4115 if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
4116 rsa->regs[i].in_g_packet = 0;
4118 rsa->regs[i].in_g_packet = 1;
4122 regs = alloca (rsa->sizeof_g_packet);
4124 /* Unimplemented registers read as all bits zero. */
4125 memset (regs, 0, rsa->sizeof_g_packet);
4127 /* Reply describes registers byte by byte, each byte encoded as two
4128 hex characters. Suck them all up, then supply them to the
4129 register cacheing/storage mechanism. */
4132 for (i = 0; i < rsa->sizeof_g_packet; i++)
4134 if (p[0] == 0 || p[1] == 0)
4135 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
4136 internal_error (__FILE__, __LINE__,
4137 "unexpected end of 'g' packet reply");
4139 if (p[0] == 'x' && p[1] == 'x')
4140 regs[i] = 0; /* 'x' */
4142 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
4148 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
4150 struct packet_reg *r = &rsa->regs[i];
4153 if (r->offset * 2 >= strlen (rs->buf))
4154 /* This shouldn't happen - we adjusted in_g_packet above. */
4155 internal_error (__FILE__, __LINE__,
4156 "unexpected end of 'g' packet reply");
4157 else if (rs->buf[r->offset * 2] == 'x')
4159 gdb_assert (r->offset * 2 < strlen (rs->buf));
4160 /* The register isn't available, mark it as such (at
4161 the same time setting the value to zero). */
4162 regcache_raw_supply (regcache, r->regnum, NULL);
4165 regcache_raw_supply (regcache, r->regnum,
4173 fetch_registers_using_g (struct regcache *regcache)
4176 process_g_packet (regcache);
4180 remote_fetch_registers (struct regcache *regcache, int regnum)
4182 struct remote_state *rs = get_remote_state ();
4183 struct remote_arch_state *rsa = get_remote_arch_state ();
4186 set_general_thread (inferior_ptid);
4190 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
4191 gdb_assert (reg != NULL);
4193 /* If this register might be in the 'g' packet, try that first -
4194 we are likely to read more than one register. If this is the
4195 first 'g' packet, we might be overly optimistic about its
4196 contents, so fall back to 'p'. */
4197 if (reg->in_g_packet)
4199 fetch_registers_using_g (regcache);
4200 if (reg->in_g_packet)
4204 if (fetch_register_using_p (regcache, reg))
4207 /* This register is not available. */
4208 regcache_raw_supply (regcache, reg->regnum, NULL);
4213 fetch_registers_using_g (regcache);
4215 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
4216 if (!rsa->regs[i].in_g_packet)
4217 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
4219 /* This register is not available. */
4220 regcache_raw_supply (regcache, i, NULL);
4224 /* Prepare to store registers. Since we may send them all (using a
4225 'G' request), we have to read out the ones we don't want to change
4229 remote_prepare_to_store (struct regcache *regcache)
4231 struct remote_arch_state *rsa = get_remote_arch_state ();
4233 gdb_byte buf[MAX_REGISTER_SIZE];
4235 /* Make sure the entire registers array is valid. */
4236 switch (remote_protocol_packets[PACKET_P].support)
4238 case PACKET_DISABLE:
4239 case PACKET_SUPPORT_UNKNOWN:
4240 /* Make sure all the necessary registers are cached. */
4241 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
4242 if (rsa->regs[i].in_g_packet)
4243 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
4250 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
4251 packet was not recognized. */
4254 store_register_using_P (const struct regcache *regcache, struct packet_reg *reg)
4256 struct gdbarch *gdbarch = get_regcache_arch (regcache);
4257 struct remote_state *rs = get_remote_state ();
4258 struct remote_arch_state *rsa = get_remote_arch_state ();
4259 /* Try storing a single register. */
4260 char *buf = rs->buf;
4261 gdb_byte regp[MAX_REGISTER_SIZE];
4264 if (remote_protocol_packets[PACKET_P].support == PACKET_DISABLE)
4267 if (reg->pnum == -1)
4270 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
4271 p = buf + strlen (buf);
4272 regcache_raw_collect (regcache, reg->regnum, regp);
4273 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
4274 remote_send (&rs->buf, &rs->buf_size);
4276 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
4281 error (_("Could not write register \"%s\""),
4282 gdbarch_register_name (gdbarch, reg->regnum));
4283 case PACKET_UNKNOWN:
4286 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
4290 /* Store register REGNUM, or all registers if REGNUM == -1, from the
4291 contents of the register cache buffer. FIXME: ignores errors. */
4294 store_registers_using_G (const struct regcache *regcache)
4296 struct remote_state *rs = get_remote_state ();
4297 struct remote_arch_state *rsa = get_remote_arch_state ();
4301 /* Extract all the registers in the regcache copying them into a
4305 regs = alloca (rsa->sizeof_g_packet);
4306 memset (regs, 0, rsa->sizeof_g_packet);
4307 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
4309 struct packet_reg *r = &rsa->regs[i];
4311 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
4315 /* Command describes registers byte by byte,
4316 each byte encoded as two hex characters. */
4319 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
4321 bin2hex (regs, p, rsa->sizeof_g_packet);
4322 remote_send (&rs->buf, &rs->buf_size);
4325 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
4326 of the register cache buffer. FIXME: ignores errors. */
4329 remote_store_registers (struct regcache *regcache, int regnum)
4331 struct remote_state *rs = get_remote_state ();
4332 struct remote_arch_state *rsa = get_remote_arch_state ();
4335 set_general_thread (inferior_ptid);
4339 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
4340 gdb_assert (reg != NULL);
4342 /* Always prefer to store registers using the 'P' packet if
4343 possible; we often change only a small number of registers.
4344 Sometimes we change a larger number; we'd need help from a
4345 higher layer to know to use 'G'. */
4346 if (store_register_using_P (regcache, reg))
4349 /* For now, don't complain if we have no way to write the
4350 register. GDB loses track of unavailable registers too
4351 easily. Some day, this may be an error. We don't have
4352 any way to read the register, either... */
4353 if (!reg->in_g_packet)
4356 store_registers_using_G (regcache);
4360 store_registers_using_G (regcache);
4362 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
4363 if (!rsa->regs[i].in_g_packet)
4364 if (!store_register_using_P (regcache, &rsa->regs[i]))
4365 /* See above for why we do not issue an error here. */
4370 /* Return the number of hex digits in num. */
4373 hexnumlen (ULONGEST num)
4377 for (i = 0; num != 0; i++)
4383 /* Set BUF to the minimum number of hex digits representing NUM. */
4386 hexnumstr (char *buf, ULONGEST num)
4388 int len = hexnumlen (num);
4389 return hexnumnstr (buf, num, len);
4393 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
4396 hexnumnstr (char *buf, ULONGEST num, int width)
4402 for (i = width - 1; i >= 0; i--)
4404 buf[i] = "0123456789abcdef"[(num & 0xf)];
4411 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
4414 remote_address_masked (CORE_ADDR addr)
4416 int address_size = remote_address_size;
4417 /* If "remoteaddresssize" was not set, default to target address size. */
4419 address_size = gdbarch_addr_bit (target_gdbarch);
4421 if (address_size > 0
4422 && address_size < (sizeof (ULONGEST) * 8))
4424 /* Only create a mask when that mask can safely be constructed
4425 in a ULONGEST variable. */
4427 mask = (mask << address_size) - 1;
4433 /* Convert BUFFER, binary data at least LEN bytes long, into escaped
4434 binary data in OUT_BUF. Set *OUT_LEN to the length of the data
4435 encoded in OUT_BUF, and return the number of bytes in OUT_BUF
4436 (which may be more than *OUT_LEN due to escape characters). The
4437 total number of bytes in the output buffer will be at most
4441 remote_escape_output (const gdb_byte *buffer, int len,
4442 gdb_byte *out_buf, int *out_len,
4445 int input_index, output_index;
4448 for (input_index = 0; input_index < len; input_index++)
4450 gdb_byte b = buffer[input_index];
4452 if (b == '$' || b == '#' || b == '}')
4454 /* These must be escaped. */
4455 if (output_index + 2 > out_maxlen)
4457 out_buf[output_index++] = '}';
4458 out_buf[output_index++] = b ^ 0x20;
4462 if (output_index + 1 > out_maxlen)
4464 out_buf[output_index++] = b;
4468 *out_len = input_index;
4469 return output_index;
4472 /* Convert BUFFER, escaped data LEN bytes long, into binary data
4473 in OUT_BUF. Return the number of bytes written to OUT_BUF.
4474 Raise an error if the total number of bytes exceeds OUT_MAXLEN.
4476 This function reverses remote_escape_output. It allows more
4477 escaped characters than that function does, in particular because
4478 '*' must be escaped to avoid the run-length encoding processing
4479 in reading packets. */
4482 remote_unescape_input (const gdb_byte *buffer, int len,
4483 gdb_byte *out_buf, int out_maxlen)
4485 int input_index, output_index;
4490 for (input_index = 0; input_index < len; input_index++)
4492 gdb_byte b = buffer[input_index];
4494 if (output_index + 1 > out_maxlen)
4496 warning (_("Received too much data from remote target;"
4497 " ignoring overflow."));
4498 return output_index;
4503 out_buf[output_index++] = b ^ 0x20;
4509 out_buf[output_index++] = b;
4513 error (_("Unmatched escape character in target response."));
4515 return output_index;
4518 /* Determine whether the remote target supports binary downloading.
4519 This is accomplished by sending a no-op memory write of zero length
4520 to the target at the specified address. It does not suffice to send
4521 the whole packet, since many stubs strip the eighth bit and
4522 subsequently compute a wrong checksum, which causes real havoc with
4525 NOTE: This can still lose if the serial line is not eight-bit
4526 clean. In cases like this, the user should clear "remote
4530 check_binary_download (CORE_ADDR addr)
4532 struct remote_state *rs = get_remote_state ();
4534 switch (remote_protocol_packets[PACKET_X].support)
4536 case PACKET_DISABLE:
4540 case PACKET_SUPPORT_UNKNOWN:
4546 p += hexnumstr (p, (ULONGEST) addr);
4548 p += hexnumstr (p, (ULONGEST) 0);
4552 putpkt_binary (rs->buf, (int) (p - rs->buf));
4553 getpkt (&rs->buf, &rs->buf_size, 0);
4555 if (rs->buf[0] == '\0')
4558 fprintf_unfiltered (gdb_stdlog,
4559 "binary downloading NOT suppported by target\n");
4560 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
4565 fprintf_unfiltered (gdb_stdlog,
4566 "binary downloading suppported by target\n");
4567 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
4574 /* Write memory data directly to the remote machine.
4575 This does not inform the data cache; the data cache uses this.
4576 HEADER is the starting part of the packet.
4577 MEMADDR is the address in the remote memory space.
4578 MYADDR is the address of the buffer in our space.
4579 LEN is the number of bytes.
4580 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
4581 should send data as binary ('X'), or hex-encoded ('M').
4583 The function creates packet of the form
4584 <HEADER><ADDRESS>,<LENGTH>:<DATA>
4586 where encoding of <DATA> is termined by PACKET_FORMAT.
4588 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
4591 Returns the number of bytes transferred, or 0 (setting errno) for
4592 error. Only transfer a single packet. */
4595 remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
4596 const gdb_byte *myaddr, int len,
4597 char packet_format, int use_length)
4599 struct remote_state *rs = get_remote_state ();
4609 if (packet_format != 'X' && packet_format != 'M')
4610 internal_error (__FILE__, __LINE__,
4611 "remote_write_bytes_aux: bad packet format");
4616 payload_size = get_memory_write_packet_size ();
4618 /* The packet buffer will be large enough for the payload;
4619 get_memory_packet_size ensures this. */
4622 /* Compute the size of the actual payload by subtracting out the
4623 packet header and footer overhead: "$M<memaddr>,<len>:...#nn".
4625 payload_size -= strlen ("$,:#NN");
4627 /* The comma won't be used. */
4629 header_length = strlen (header);
4630 payload_size -= header_length;
4631 payload_size -= hexnumlen (memaddr);
4633 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
4635 strcat (rs->buf, header);
4636 p = rs->buf + strlen (header);
4638 /* Compute a best guess of the number of bytes actually transfered. */
4639 if (packet_format == 'X')
4641 /* Best guess at number of bytes that will fit. */
4642 todo = min (len, payload_size);
4644 payload_size -= hexnumlen (todo);
4645 todo = min (todo, payload_size);
4649 /* Num bytes that will fit. */
4650 todo = min (len, payload_size / 2);
4652 payload_size -= hexnumlen (todo);
4653 todo = min (todo, payload_size / 2);
4657 internal_error (__FILE__, __LINE__,
4658 _("minumum packet size too small to write data"));
4660 /* If we already need another packet, then try to align the end
4661 of this packet to a useful boundary. */
4662 if (todo > 2 * REMOTE_ALIGN_WRITES && todo < len)
4663 todo = ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
4665 /* Append "<memaddr>". */
4666 memaddr = remote_address_masked (memaddr);
4667 p += hexnumstr (p, (ULONGEST) memaddr);
4674 /* Append <len>. Retain the location/size of <len>. It may need to
4675 be adjusted once the packet body has been created. */
4677 plenlen = hexnumstr (p, (ULONGEST) todo);
4685 /* Append the packet body. */
4686 if (packet_format == 'X')
4688 /* Binary mode. Send target system values byte by byte, in
4689 increasing byte addresses. Only escape certain critical
4691 payload_length = remote_escape_output (myaddr, todo, p, &nr_bytes,
4694 /* If not all TODO bytes fit, then we'll need another packet. Make
4695 a second try to keep the end of the packet aligned. Don't do
4696 this if the packet is tiny. */
4697 if (nr_bytes < todo && nr_bytes > 2 * REMOTE_ALIGN_WRITES)
4701 new_nr_bytes = (((memaddr + nr_bytes) & ~(REMOTE_ALIGN_WRITES - 1))
4703 if (new_nr_bytes != nr_bytes)
4704 payload_length = remote_escape_output (myaddr, new_nr_bytes,
4709 p += payload_length;
4710 if (use_length && nr_bytes < todo)
4712 /* Escape chars have filled up the buffer prematurely,
4713 and we have actually sent fewer bytes than planned.
4714 Fix-up the length field of the packet. Use the same
4715 number of characters as before. */
4716 plen += hexnumnstr (plen, (ULONGEST) nr_bytes, plenlen);
4717 *plen = ':'; /* overwrite \0 from hexnumnstr() */
4722 /* Normal mode: Send target system values byte by byte, in
4723 increasing byte addresses. Each byte is encoded as a two hex
4725 nr_bytes = bin2hex (myaddr, p, todo);
4729 putpkt_binary (rs->buf, (int) (p - rs->buf));
4730 getpkt (&rs->buf, &rs->buf_size, 0);
4732 if (rs->buf[0] == 'E')
4734 /* There is no correspondance between what the remote protocol
4735 uses for errors and errno codes. We would like a cleaner way
4736 of representing errors (big enough to include errno codes,
4737 bfd_error codes, and others). But for now just return EIO. */
4742 /* Return NR_BYTES, not TODO, in case escape chars caused us to send
4743 fewer bytes than we'd planned. */
4747 /* Write memory data directly to the remote machine.
4748 This does not inform the data cache; the data cache uses this.
4749 MEMADDR is the address in the remote memory space.
4750 MYADDR is the address of the buffer in our space.
4751 LEN is the number of bytes.
4753 Returns number of bytes transferred, or 0 (setting errno) for
4754 error. Only transfer a single packet. */
4757 remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, int len)
4759 char *packet_format = 0;
4761 /* Check whether the target supports binary download. */
4762 check_binary_download (memaddr);
4764 switch (remote_protocol_packets[PACKET_X].support)
4767 packet_format = "X";
4769 case PACKET_DISABLE:
4770 packet_format = "M";
4772 case PACKET_SUPPORT_UNKNOWN:
4773 internal_error (__FILE__, __LINE__,
4774 _("remote_write_bytes: bad internal state"));
4776 internal_error (__FILE__, __LINE__, _("bad switch"));
4779 return remote_write_bytes_aux (packet_format,
4780 memaddr, myaddr, len, packet_format[0], 1);
4783 /* Read memory data directly from the remote machine.
4784 This does not use the data cache; the data cache uses this.
4785 MEMADDR is the address in the remote memory space.
4786 MYADDR is the address of the buffer in our space.
4787 LEN is the number of bytes.
4789 Returns number of bytes transferred, or 0 for error. */
4791 /* NOTE: cagney/1999-10-18: This function (and its siblings in other
4792 remote targets) shouldn't attempt to read the entire buffer.
4793 Instead it should read a single packet worth of data and then
4794 return the byte size of that packet to the caller. The caller (its
4795 caller and its callers caller ;-) already contains code for
4796 handling partial reads. */
4799 remote_read_bytes (CORE_ADDR memaddr, gdb_byte *myaddr, int len)
4801 struct remote_state *rs = get_remote_state ();
4802 int max_buf_size; /* Max size of packet output buffer. */
4808 max_buf_size = get_memory_read_packet_size ();
4809 /* The packet buffer will be large enough for the payload;
4810 get_memory_packet_size ensures this. */
4819 todo = min (len, max_buf_size / 2); /* num bytes that will fit */
4821 /* construct "m"<memaddr>","<len>" */
4822 /* sprintf (rs->buf, "m%lx,%x", (unsigned long) memaddr, todo); */
4823 memaddr = remote_address_masked (memaddr);
4826 p += hexnumstr (p, (ULONGEST) memaddr);
4828 p += hexnumstr (p, (ULONGEST) todo);
4832 getpkt (&rs->buf, &rs->buf_size, 0);
4834 if (rs->buf[0] == 'E'
4835 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
4836 && rs->buf[3] == '\0')
4838 /* There is no correspondance between what the remote
4839 protocol uses for errors and errno codes. We would like
4840 a cleaner way of representing errors (big enough to
4841 include errno codes, bfd_error codes, and others). But
4842 for now just return EIO. */
4847 /* Reply describes memory byte by byte,
4848 each byte encoded as two hex characters. */
4851 if ((i = hex2bin (p, myaddr, todo)) < todo)
4853 /* Reply is short. This means that we were able to read
4854 only part of what we wanted to. */
4855 return i + (origlen - len);
4864 /* Read or write LEN bytes from inferior memory at MEMADDR,
4865 transferring to or from debugger address BUFFER. Write to inferior
4866 if SHOULD_WRITE is nonzero. Returns length of data written or
4867 read; 0 for error. TARGET is unused. */
4870 remote_xfer_memory (CORE_ADDR mem_addr, gdb_byte *buffer, int mem_len,
4871 int should_write, struct mem_attrib *attrib,
4872 struct target_ops *target)
4876 set_general_thread (inferior_ptid);
4879 res = remote_write_bytes (mem_addr, buffer, mem_len);
4881 res = remote_read_bytes (mem_addr, buffer, mem_len);
4886 /* Sends a packet with content determined by the printf format string
4887 FORMAT and the remaining arguments, then gets the reply. Returns
4888 whether the packet was a success, a failure, or unknown. */
4891 remote_send_printf (const char *format, ...)
4893 struct remote_state *rs = get_remote_state ();
4894 int max_size = get_remote_packet_size ();
4897 va_start (ap, format);
4900 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
4901 internal_error (__FILE__, __LINE__, "Too long remote packet.");
4903 if (putpkt (rs->buf) < 0)
4904 error (_("Communication problem with target."));
4907 getpkt (&rs->buf, &rs->buf_size, 0);
4909 return packet_check_result (rs->buf);
4913 restore_remote_timeout (void *p)
4915 int value = *(int *)p;
4916 remote_timeout = value;
4919 /* Flash writing can take quite some time. We'll set
4920 effectively infinite timeout for flash operations.
4921 In future, we'll need to decide on a better approach. */
4922 static const int remote_flash_timeout = 1000;
4925 remote_flash_erase (struct target_ops *ops,
4926 ULONGEST address, LONGEST length)
4928 int saved_remote_timeout = remote_timeout;
4929 enum packet_result ret;
4931 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
4932 &saved_remote_timeout);
4933 remote_timeout = remote_flash_timeout;
4935 ret = remote_send_printf ("vFlashErase:%s,%s",
4940 case PACKET_UNKNOWN:
4941 error (_("Remote target does not support flash erase"));
4943 error (_("Error erasing flash with vFlashErase packet"));
4948 do_cleanups (back_to);
4952 remote_flash_write (struct target_ops *ops,
4953 ULONGEST address, LONGEST length,
4954 const gdb_byte *data)
4956 int saved_remote_timeout = remote_timeout;
4958 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
4959 &saved_remote_timeout);
4961 remote_timeout = remote_flash_timeout;
4962 ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length, 'X', 0);
4963 do_cleanups (back_to);
4969 remote_flash_done (struct target_ops *ops)
4971 int saved_remote_timeout = remote_timeout;
4973 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
4974 &saved_remote_timeout);
4976 remote_timeout = remote_flash_timeout;
4977 ret = remote_send_printf ("vFlashDone");
4978 do_cleanups (back_to);
4982 case PACKET_UNKNOWN:
4983 error (_("Remote target does not support vFlashDone"));
4985 error (_("Error finishing flash operation"));
4992 remote_files_info (struct target_ops *ignore)
4994 puts_filtered ("Debugging a target over a serial line.\n");
4997 /* Stuff for dealing with the packets which are part of this protocol.
4998 See comment at top of file for details. */
5000 /* Read a single character from the remote end. */
5003 readchar (int timeout)
5007 ch = serial_readchar (remote_desc, timeout);
5012 switch ((enum serial_rc) ch)
5016 error (_("Remote connection closed"));
5019 perror_with_name (_("Remote communication error"));
5021 case SERIAL_TIMEOUT:
5027 /* Send the command in *BUF to the remote machine, and read the reply
5028 into *BUF. Report an error if we get an error reply. Resize
5029 *BUF using xrealloc if necessary to hold the result, and update
5033 remote_send (char **buf,
5037 getpkt (buf, sizeof_buf, 0);
5039 if ((*buf)[0] == 'E')
5040 error (_("Remote failure reply: %s"), *buf);
5043 /* Display a null-terminated packet on stdout, for debugging, using C
5047 print_packet (char *buf)
5049 puts_filtered ("\"");
5050 fputstr_filtered (buf, '"', gdb_stdout);
5051 puts_filtered ("\"");
5057 return putpkt_binary (buf, strlen (buf));
5060 /* Send a packet to the remote machine, with error checking. The data
5061 of the packet is in BUF. The string in BUF can be at most
5062 get_remote_packet_size () - 5 to account for the $, # and checksum,
5063 and for a possible /0 if we are debugging (remote_debug) and want
5064 to print the sent packet as a string. */
5067 putpkt_binary (char *buf, int cnt)
5069 struct remote_state *rs = get_remote_state ();
5071 unsigned char csum = 0;
5072 char *buf2 = alloca (cnt + 6);
5078 /* Catch cases like trying to read memory or listing threads while
5079 we're waiting for a stop reply. The remote server wouldn't be
5080 ready to handle this request, so we'd hang and timeout. We don't
5081 have to worry about this in synchronous mode, because in that
5082 case it's not possible to issue a command while the target is
5084 if (target_can_async_p () && rs->waiting_for_stop_reply)
5085 error (_("Cannot execute this command while the target is running."));
5087 /* We're sending out a new packet. Make sure we don't look at a
5088 stale cached response. */
5089 rs->cached_wait_status = 0;
5091 /* Copy the packet into buffer BUF2, encapsulating it
5092 and giving it a checksum. */
5097 for (i = 0; i < cnt; i++)
5103 *p++ = tohex ((csum >> 4) & 0xf);
5104 *p++ = tohex (csum & 0xf);
5106 /* Send it over and over until we get a positive ack. */
5110 int started_error_output = 0;
5115 fprintf_unfiltered (gdb_stdlog, "Sending packet: ");
5116 fputstrn_unfiltered (buf2, p - buf2, 0, gdb_stdlog);
5117 fprintf_unfiltered (gdb_stdlog, "...");
5118 gdb_flush (gdb_stdlog);
5120 if (serial_write (remote_desc, buf2, p - buf2))
5121 perror_with_name (_("putpkt: write failed"));
5123 /* If this is a no acks version of the remote protocol, send the
5124 packet and move on. */
5128 /* Read until either a timeout occurs (-2) or '+' is read. */
5131 ch = readchar (remote_timeout);
5139 case SERIAL_TIMEOUT:
5141 if (started_error_output)
5143 putchar_unfiltered ('\n');
5144 started_error_output = 0;
5153 fprintf_unfiltered (gdb_stdlog, "Ack\n");
5157 fprintf_unfiltered (gdb_stdlog, "Nak\n");
5158 case SERIAL_TIMEOUT:
5162 break; /* Retransmit buffer. */
5166 fprintf_unfiltered (gdb_stdlog,
5167 "Packet instead of Ack, ignoring it\n");
5168 /* It's probably an old response sent because an ACK
5169 was lost. Gobble up the packet and ack it so it
5170 doesn't get retransmitted when we resend this
5173 serial_write (remote_desc, "+", 1);
5174 continue; /* Now, go look for +. */
5179 if (!started_error_output)
5181 started_error_output = 1;
5182 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
5184 fputc_unfiltered (ch & 0177, gdb_stdlog);
5188 break; /* Here to retransmit. */
5192 /* This is wrong. If doing a long backtrace, the user should be
5193 able to get out next time we call QUIT, without anything as
5194 violent as interrupt_query. If we want to provide a way out of
5195 here without getting to the next QUIT, it should be based on
5196 hitting ^C twice as in remote_wait. */
5207 /* Come here after finding the start of a frame when we expected an
5208 ack. Do our best to discard the rest of this packet. */
5217 c = readchar (remote_timeout);
5220 case SERIAL_TIMEOUT:
5221 /* Nothing we can do. */
5224 /* Discard the two bytes of checksum and stop. */
5225 c = readchar (remote_timeout);
5227 c = readchar (remote_timeout);
5230 case '*': /* Run length encoding. */
5231 /* Discard the repeat count. */
5232 c = readchar (remote_timeout);
5237 /* A regular character. */
5243 /* Come here after finding the start of the frame. Collect the rest
5244 into *BUF, verifying the checksum, length, and handling run-length
5245 compression. NUL terminate the buffer. If there is not enough room,
5246 expand *BUF using xrealloc.
5248 Returns -1 on error, number of characters in buffer (ignoring the
5249 trailing NULL) on success. (could be extended to return one of the
5250 SERIAL status indications). */
5253 read_frame (char **buf_p,
5260 struct remote_state *rs = get_remote_state ();
5267 c = readchar (remote_timeout);
5270 case SERIAL_TIMEOUT:
5272 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
5276 fputs_filtered ("Saw new packet start in middle of old one\n",
5278 return -1; /* Start a new packet, count retries. */
5281 unsigned char pktcsum;
5287 check_0 = readchar (remote_timeout);
5289 check_1 = readchar (remote_timeout);
5291 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
5294 fputs_filtered ("Timeout in checksum, retrying\n",
5298 else if (check_0 < 0 || check_1 < 0)
5301 fputs_filtered ("Communication error in checksum\n",
5306 /* Don't recompute the checksum; with no ack packets we
5307 don't have any way to indicate a packet retransmission
5312 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
5313 if (csum == pktcsum)
5318 fprintf_filtered (gdb_stdlog,
5319 "Bad checksum, sentsum=0x%x, csum=0x%x, buf=",
5321 fputstrn_filtered (buf, bc, 0, gdb_stdlog);
5322 fputs_filtered ("\n", gdb_stdlog);
5324 /* Number of characters in buffer ignoring trailing
5328 case '*': /* Run length encoding. */
5333 c = readchar (remote_timeout);
5335 repeat = c - ' ' + 3; /* Compute repeat count. */
5337 /* The character before ``*'' is repeated. */
5339 if (repeat > 0 && repeat <= 255 && bc > 0)
5341 if (bc + repeat - 1 >= *sizeof_buf - 1)
5343 /* Make some more room in the buffer. */
5344 *sizeof_buf += repeat;
5345 *buf_p = xrealloc (*buf_p, *sizeof_buf);
5349 memset (&buf[bc], buf[bc - 1], repeat);
5355 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
5359 if (bc >= *sizeof_buf - 1)
5361 /* Make some more room in the buffer. */
5363 *buf_p = xrealloc (*buf_p, *sizeof_buf);
5374 /* Read a packet from the remote machine, with error checking, and
5375 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
5376 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
5377 rather than timing out; this is used (in synchronous mode) to wait
5378 for a target that is is executing user code to stop. */
5379 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
5380 don't have to change all the calls to getpkt to deal with the
5381 return value, because at the moment I don't know what the right
5382 thing to do it for those. */
5390 timed_out = getpkt_sane (buf, sizeof_buf, forever);
5394 /* Read a packet from the remote machine, with error checking, and
5395 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
5396 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
5397 rather than timing out; this is used (in synchronous mode) to wait
5398 for a target that is is executing user code to stop. If FOREVER ==
5399 0, this function is allowed to time out gracefully and return an
5400 indication of this to the caller. Otherwise return the number
5403 getpkt_sane (char **buf, long *sizeof_buf, int forever)
5405 struct remote_state *rs = get_remote_state ();
5411 /* We're reading a new response. Make sure we don't look at a
5412 previously cached response. */
5413 rs->cached_wait_status = 0;
5415 strcpy (*buf, "timeout");
5419 timeout = watchdog > 0 ? watchdog : -1;
5423 timeout = remote_timeout;
5427 for (tries = 1; tries <= MAX_TRIES; tries++)
5429 /* This can loop forever if the remote side sends us characters
5430 continuously, but if it pauses, we'll get a zero from
5431 readchar because of timeout. Then we'll count that as a
5434 /* Note that we will only wait forever prior to the start of a
5435 packet. After that, we expect characters to arrive at a
5436 brisk pace. They should show up within remote_timeout
5441 c = readchar (timeout);
5443 if (c == SERIAL_TIMEOUT)
5445 if (forever) /* Watchdog went off? Kill the target. */
5449 error (_("Watchdog timeout has expired. Target detached."));
5452 fputs_filtered ("Timed out.\n", gdb_stdlog);
5458 /* We've found the start of a packet, now collect the data. */
5460 val = read_frame (buf, sizeof_buf);
5466 fprintf_unfiltered (gdb_stdlog, "Packet received: ");
5467 fputstrn_unfiltered (*buf, val, 0, gdb_stdlog);
5468 fprintf_unfiltered (gdb_stdlog, "\n");
5471 /* Skip the ack char if we're in no-ack mode. */
5472 if (!rs->noack_mode)
5473 serial_write (remote_desc, "+", 1);
5477 /* Try the whole thing again. */
5479 /* Skip the nack char if we're in no-ack mode. */
5480 if (!rs->noack_mode)
5481 serial_write (remote_desc, "-", 1);
5484 /* We have tried hard enough, and just can't receive the packet.
5487 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
5489 /* Skip the ack char if we're in no-ack mode. */
5490 if (!rs->noack_mode)
5491 serial_write (remote_desc, "+", 1);
5498 /* Use catch_errors so the user can quit from gdb even when we
5499 aren't on speaking terms with the remote system. */
5500 catch_errors ((catch_errors_ftype *) putpkt, "k", "", RETURN_MASK_ERROR);
5502 /* Don't wait for it to die. I'm not really sure it matters whether
5503 we do or not. For the existing stubs, kill is a noop. */
5504 target_mourn_inferior ();
5508 remote_vkill (int pid, struct remote_state *rs)
5510 if (remote_protocol_packets[PACKET_vKill].support == PACKET_DISABLE)
5513 /* Tell the remote target to detach. */
5514 sprintf (rs->buf, "vKill;%x", pid);
5516 getpkt (&rs->buf, &rs->buf_size, 0);
5518 if (packet_ok (rs->buf,
5519 &remote_protocol_packets[PACKET_vKill]) == PACKET_OK)
5521 else if (remote_protocol_packets[PACKET_vKill].support == PACKET_DISABLE)
5528 extended_remote_kill (void)
5531 int pid = ptid_get_pid (inferior_ptid);
5532 struct remote_state *rs = get_remote_state ();
5534 res = remote_vkill (pid, rs);
5535 if (res == -1 && !remote_multi_process_p (rs))
5537 /* Don't try 'k' on a multi-process aware stub -- it has no way
5538 to specify the pid. */
5542 getpkt (&rs->buf, &rs->buf_size, 0);
5543 if (rs->buf[0] != 'O' || rs->buf[0] != 'K')
5546 /* Don't wait for it to die. I'm not really sure it matters whether
5547 we do or not. For the existing stubs, kill is a noop. */
5553 error (_("Can't kill process"));
5555 delete_inferior (pid);
5556 target_mourn_inferior ();
5562 remote_mourn_1 (&remote_ops);
5565 /* Worker function for remote_mourn. */
5567 remote_mourn_1 (struct target_ops *target)
5569 unpush_target (target);
5571 /* remote_close takes care of cleaning up. */
5575 select_new_thread_callback (struct thread_info *th, void* data)
5577 if (!ptid_equal (th->ptid, minus_one_ptid))
5579 switch_to_thread (th->ptid);
5580 printf_filtered (_("[Switching to %s]\n"),
5581 target_pid_to_str (inferior_ptid));
5588 extended_remote_mourn_1 (struct target_ops *target)
5590 struct remote_state *rs = get_remote_state ();
5592 /* In case we got here due to an error, but we're going to stay
5594 rs->waiting_for_stop_reply = 0;
5596 /* Unlike "target remote", we do not want to unpush the target; then
5597 the next time the user says "run", we won't be connected. */
5599 if (have_inferiors ())
5601 extern void nullify_last_target_wait_ptid ();
5602 /* Multi-process case. The current process has exited, but
5603 there are other processes to debug. Switch to the first
5605 iterate_over_threads (select_new_thread_callback, NULL);
5606 nullify_last_target_wait_ptid ();
5610 struct remote_state *rs = get_remote_state ();
5612 /* Call common code to mark the inferior as not running. */
5613 generic_mourn_inferior ();
5614 if (!remote_multi_process_p (rs))
5616 /* Check whether the target is running now - some remote stubs
5617 automatically restart after kill. */
5619 getpkt (&rs->buf, &rs->buf_size, 0);
5621 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
5623 /* Assume that the target has been restarted. Set inferior_ptid
5624 so that bits of core GDB realizes there's something here, e.g.,
5625 so that the user can say "kill" again. */
5626 inferior_ptid = magic_null_ptid;
5630 /* Mark this (still pushed) target as not executable until we
5632 target_mark_exited (target);
5636 /* Always remove execution if this was the last process. */
5637 target_mark_exited (target);
5642 extended_remote_mourn (void)
5644 extended_remote_mourn_1 (&extended_remote_ops);
5648 extended_remote_run (char *args)
5650 struct remote_state *rs = get_remote_state ();
5654 /* If the user has disabled vRun support, or we have detected that
5655 support is not available, do not try it. */
5656 if (remote_protocol_packets[PACKET_vRun].support == PACKET_DISABLE)
5659 strcpy (rs->buf, "vRun;");
5660 len = strlen (rs->buf);
5662 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
5663 error (_("Remote file name too long for run packet"));
5664 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len, 0);
5666 gdb_assert (args != NULL);
5669 struct cleanup *back_to;
5673 argv = gdb_buildargv (args);
5674 back_to = make_cleanup ((void (*) (void *)) freeargv, argv);
5675 for (i = 0; argv[i] != NULL; i++)
5677 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
5678 error (_("Argument list too long for run packet"));
5679 rs->buf[len++] = ';';
5680 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len, 0);
5682 do_cleanups (back_to);
5685 rs->buf[len++] = '\0';
5688 getpkt (&rs->buf, &rs->buf_size, 0);
5690 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]) == PACKET_OK)
5692 /* We have a wait response; we don't need it, though. All is well. */
5695 else if (remote_protocol_packets[PACKET_vRun].support == PACKET_DISABLE)
5696 /* It wasn't disabled before, but it is now. */
5700 if (remote_exec_file[0] == '\0')
5701 error (_("Running the default executable on the remote target failed; "
5702 "try \"set remote exec-file\"?"));
5704 error (_("Running \"%s\" on the remote target failed"),
5709 /* In the extended protocol we want to be able to do things like
5710 "run" and have them basically work as expected. So we need
5711 a special create_inferior function. We support changing the
5712 executable file and the command line arguments, but not the
5716 extended_remote_create_inferior_1 (char *exec_file, char *args,
5717 char **env, int from_tty)
5719 /* If running asynchronously, register the target file descriptor
5720 with the event loop. */
5721 if (target_can_async_p ())
5722 target_async (inferior_event_handler, 0);
5724 /* Now restart the remote server. */
5725 if (extended_remote_run (args) == -1)
5727 /* vRun was not supported. Fail if we need it to do what the
5729 if (remote_exec_file[0])
5730 error (_("Remote target does not support \"set remote exec-file\""));
5732 error (_("Remote target does not support \"set args\" or run <ARGS>"));
5734 /* Fall back to "R". */
5735 extended_remote_restart ();
5738 /* Clean up from the last time we ran, before we mark the target
5739 running again. This will mark breakpoints uninserted, and
5740 get_offsets may insert breakpoints. */
5741 init_thread_list ();
5742 init_wait_for_inferior ();
5744 /* Now mark the inferior as running before we do anything else. */
5745 inferior_ptid = magic_null_ptid;
5747 add_inferior (ptid_get_pid (inferior_ptid));
5748 add_thread_silent (inferior_ptid);
5750 target_mark_running (&extended_remote_ops);
5752 /* Get updated offsets, if the stub uses qOffsets. */
5757 extended_remote_create_inferior (char *exec_file, char *args,
5758 char **env, int from_tty)
5760 extended_remote_create_inferior_1 (exec_file, args, env, from_tty);
5764 /* Insert a breakpoint. On targets that have software breakpoint
5765 support, we ask the remote target to do the work; on targets
5766 which don't, we insert a traditional memory breakpoint. */
5769 remote_insert_breakpoint (struct bp_target_info *bp_tgt)
5771 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
5772 If it succeeds, then set the support to PACKET_ENABLE. If it
5773 fails, and the user has explicitly requested the Z support then
5774 report an error, otherwise, mark it disabled and go on. */
5776 if (remote_protocol_packets[PACKET_Z0].support != PACKET_DISABLE)
5778 CORE_ADDR addr = bp_tgt->placed_address;
5779 struct remote_state *rs;
5783 gdbarch_breakpoint_from_pc (target_gdbarch, &addr, &bpsize);
5785 rs = get_remote_state ();
5791 addr = (ULONGEST) remote_address_masked (addr);
5792 p += hexnumstr (p, addr);
5793 sprintf (p, ",%d", bpsize);
5796 getpkt (&rs->buf, &rs->buf_size, 0);
5798 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
5803 bp_tgt->placed_address = addr;
5804 bp_tgt->placed_size = bpsize;
5806 case PACKET_UNKNOWN:
5811 return memory_insert_breakpoint (bp_tgt);
5815 remote_remove_breakpoint (struct bp_target_info *bp_tgt)
5817 CORE_ADDR addr = bp_tgt->placed_address;
5818 struct remote_state *rs = get_remote_state ();
5821 if (remote_protocol_packets[PACKET_Z0].support != PACKET_DISABLE)
5829 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
5830 p += hexnumstr (p, addr);
5831 sprintf (p, ",%d", bp_tgt->placed_size);
5834 getpkt (&rs->buf, &rs->buf_size, 0);
5836 return (rs->buf[0] == 'E');
5839 return memory_remove_breakpoint (bp_tgt);
5843 watchpoint_to_Z_packet (int type)
5848 return Z_PACKET_WRITE_WP;
5851 return Z_PACKET_READ_WP;
5854 return Z_PACKET_ACCESS_WP;
5857 internal_error (__FILE__, __LINE__,
5858 _("hw_bp_to_z: bad watchpoint type %d"), type);
5863 remote_insert_watchpoint (CORE_ADDR addr, int len, int type)
5865 struct remote_state *rs = get_remote_state ();
5867 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
5869 if (remote_protocol_packets[PACKET_Z0 + packet].support == PACKET_DISABLE)
5872 sprintf (rs->buf, "Z%x,", packet);
5873 p = strchr (rs->buf, '\0');
5874 addr = remote_address_masked (addr);
5875 p += hexnumstr (p, (ULONGEST) addr);
5876 sprintf (p, ",%x", len);
5879 getpkt (&rs->buf, &rs->buf_size, 0);
5881 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
5884 case PACKET_UNKNOWN:
5889 internal_error (__FILE__, __LINE__,
5890 _("remote_insert_watchpoint: reached end of function"));
5895 remote_remove_watchpoint (CORE_ADDR addr, int len, int type)
5897 struct remote_state *rs = get_remote_state ();
5899 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
5901 if (remote_protocol_packets[PACKET_Z0 + packet].support == PACKET_DISABLE)
5904 sprintf (rs->buf, "z%x,", packet);
5905 p = strchr (rs->buf, '\0');
5906 addr = remote_address_masked (addr);
5907 p += hexnumstr (p, (ULONGEST) addr);
5908 sprintf (p, ",%x", len);
5910 getpkt (&rs->buf, &rs->buf_size, 0);
5912 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
5915 case PACKET_UNKNOWN:
5920 internal_error (__FILE__, __LINE__,
5921 _("remote_remove_watchpoint: reached end of function"));
5925 int remote_hw_watchpoint_limit = -1;
5926 int remote_hw_breakpoint_limit = -1;
5929 remote_check_watch_resources (int type, int cnt, int ot)
5931 if (type == bp_hardware_breakpoint)
5933 if (remote_hw_breakpoint_limit == 0)
5935 else if (remote_hw_breakpoint_limit < 0)
5937 else if (cnt <= remote_hw_breakpoint_limit)
5942 if (remote_hw_watchpoint_limit == 0)
5944 else if (remote_hw_watchpoint_limit < 0)
5948 else if (cnt <= remote_hw_watchpoint_limit)
5955 remote_stopped_by_watchpoint (void)
5957 return remote_stopped_by_watchpoint_p;
5961 remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
5964 if (remote_stopped_by_watchpoint ())
5966 *addr_p = remote_watch_data_address;
5975 remote_insert_hw_breakpoint (struct bp_target_info *bp_tgt)
5978 struct remote_state *rs;
5981 /* The length field should be set to the size of a breakpoint
5982 instruction, even though we aren't inserting one ourselves. */
5984 gdbarch_breakpoint_from_pc
5985 (target_gdbarch, &bp_tgt->placed_address, &bp_tgt->placed_size);
5987 if (remote_protocol_packets[PACKET_Z1].support == PACKET_DISABLE)
5990 rs = get_remote_state ();
5997 addr = remote_address_masked (bp_tgt->placed_address);
5998 p += hexnumstr (p, (ULONGEST) addr);
5999 sprintf (p, ",%x", bp_tgt->placed_size);
6002 getpkt (&rs->buf, &rs->buf_size, 0);
6004 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
6007 case PACKET_UNKNOWN:
6012 internal_error (__FILE__, __LINE__,
6013 _("remote_insert_hw_breakpoint: reached end of function"));
6018 remote_remove_hw_breakpoint (struct bp_target_info *bp_tgt)
6021 struct remote_state *rs = get_remote_state ();
6024 if (remote_protocol_packets[PACKET_Z1].support == PACKET_DISABLE)
6031 addr = remote_address_masked (bp_tgt->placed_address);
6032 p += hexnumstr (p, (ULONGEST) addr);
6033 sprintf (p, ",%x", bp_tgt->placed_size);
6036 getpkt (&rs->buf, &rs->buf_size, 0);
6038 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
6041 case PACKET_UNKNOWN:
6046 internal_error (__FILE__, __LINE__,
6047 _("remote_remove_hw_breakpoint: reached end of function"));
6050 /* Table used by the crc32 function to calcuate the checksum. */
6052 static unsigned long crc32_table[256] =
6055 static unsigned long
6056 crc32 (unsigned char *buf, int len, unsigned int crc)
6058 if (!crc32_table[1])
6060 /* Initialize the CRC table and the decoding table. */
6064 for (i = 0; i < 256; i++)
6066 for (c = i << 24, j = 8; j > 0; --j)
6067 c = c & 0x80000000 ? (c << 1) ^ 0x04c11db7 : (c << 1);
6074 crc = (crc << 8) ^ crc32_table[((crc >> 24) ^ *buf) & 255];
6080 /* compare-sections command
6082 With no arguments, compares each loadable section in the exec bfd
6083 with the same memory range on the target, and reports mismatches.
6084 Useful for verifying the image on the target against the exec file.
6085 Depends on the target understanding the new "qCRC:" request. */
6087 /* FIXME: cagney/1999-10-26: This command should be broken down into a
6088 target method (target verify memory) and generic version of the
6089 actual command. This will allow other high-level code (especially
6090 generic_load()) to make use of this target functionality. */
6093 compare_sections_command (char *args, int from_tty)
6095 struct remote_state *rs = get_remote_state ();
6097 unsigned long host_crc, target_crc;
6098 extern bfd *exec_bfd;
6099 struct cleanup *old_chain;
6102 const char *sectname;
6109 error (_("command cannot be used without an exec file"));
6110 if (!current_target.to_shortname ||
6111 strcmp (current_target.to_shortname, "remote") != 0)
6112 error (_("command can only be used with remote target"));
6114 for (s = exec_bfd->sections; s; s = s->next)
6116 if (!(s->flags & SEC_LOAD))
6117 continue; /* skip non-loadable section */
6119 size = bfd_get_section_size (s);
6121 continue; /* skip zero-length section */
6123 sectname = bfd_get_section_name (exec_bfd, s);
6124 if (args && strcmp (args, sectname) != 0)
6125 continue; /* not the section selected by user */
6127 matched = 1; /* do this section */
6129 /* FIXME: assumes lma can fit into long. */
6130 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
6131 (long) lma, (long) size);
6134 /* Be clever; compute the host_crc before waiting for target
6136 sectdata = xmalloc (size);
6137 old_chain = make_cleanup (xfree, sectdata);
6138 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
6139 host_crc = crc32 ((unsigned char *) sectdata, size, 0xffffffff);
6141 getpkt (&rs->buf, &rs->buf_size, 0);
6142 if (rs->buf[0] == 'E')
6143 error (_("target memory fault, section %s, range 0x%s -- 0x%s"),
6144 sectname, paddr (lma), paddr (lma + size));
6145 if (rs->buf[0] != 'C')
6146 error (_("remote target does not support this operation"));
6148 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
6149 target_crc = target_crc * 16 + fromhex (*tmp);
6151 printf_filtered ("Section %s, range 0x%s -- 0x%s: ",
6152 sectname, paddr (lma), paddr (lma + size));
6153 if (host_crc == target_crc)
6154 printf_filtered ("matched.\n");
6157 printf_filtered ("MIS-MATCHED!\n");
6161 do_cleanups (old_chain);
6164 warning (_("One or more sections of the remote executable does not match\n\
6165 the loaded file\n"));
6166 if (args && !matched)
6167 printf_filtered (_("No loaded section named '%s'.\n"), args);
6170 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
6171 into remote target. The number of bytes written to the remote
6172 target is returned, or -1 for error. */
6175 remote_write_qxfer (struct target_ops *ops, const char *object_name,
6176 const char *annex, const gdb_byte *writebuf,
6177 ULONGEST offset, LONGEST len,
6178 struct packet_config *packet)
6183 struct remote_state *rs = get_remote_state ();
6184 int max_size = get_memory_write_packet_size ();
6186 if (packet->support == PACKET_DISABLE)
6189 /* Insert header. */
6190 i = snprintf (rs->buf, max_size,
6191 "qXfer:%s:write:%s:%s:",
6192 object_name, annex ? annex : "",
6193 phex_nz (offset, sizeof offset));
6194 max_size -= (i + 1);
6196 /* Escape as much data as fits into rs->buf. */
6197 buf_len = remote_escape_output
6198 (writebuf, len, (rs->buf + i), &max_size, max_size);
6200 if (putpkt_binary (rs->buf, i + buf_len) < 0
6201 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
6202 || packet_ok (rs->buf, packet) != PACKET_OK)
6205 unpack_varlen_hex (rs->buf, &n);
6209 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
6210 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
6211 number of bytes read is returned, or 0 for EOF, or -1 for error.
6212 The number of bytes read may be less than LEN without indicating an
6213 EOF. PACKET is checked and updated to indicate whether the remote
6214 target supports this object. */
6217 remote_read_qxfer (struct target_ops *ops, const char *object_name,
6219 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
6220 struct packet_config *packet)
6222 static char *finished_object;
6223 static char *finished_annex;
6224 static ULONGEST finished_offset;
6226 struct remote_state *rs = get_remote_state ();
6227 unsigned int total = 0;
6228 LONGEST i, n, packet_len;
6230 if (packet->support == PACKET_DISABLE)
6233 /* Check whether we've cached an end-of-object packet that matches
6235 if (finished_object)
6237 if (strcmp (object_name, finished_object) == 0
6238 && strcmp (annex ? annex : "", finished_annex) == 0
6239 && offset == finished_offset)
6242 /* Otherwise, we're now reading something different. Discard
6244 xfree (finished_object);
6245 xfree (finished_annex);
6246 finished_object = NULL;
6247 finished_annex = NULL;
6250 /* Request only enough to fit in a single packet. The actual data
6251 may not, since we don't know how much of it will need to be escaped;
6252 the target is free to respond with slightly less data. We subtract
6253 five to account for the response type and the protocol frame. */
6254 n = min (get_remote_packet_size () - 5, len);
6255 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
6256 object_name, annex ? annex : "",
6257 phex_nz (offset, sizeof offset),
6258 phex_nz (n, sizeof n));
6259 i = putpkt (rs->buf);
6264 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
6265 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
6268 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
6269 error (_("Unknown remote qXfer reply: %s"), rs->buf);
6271 /* 'm' means there is (or at least might be) more data after this
6272 batch. That does not make sense unless there's at least one byte
6273 of data in this reply. */
6274 if (rs->buf[0] == 'm' && packet_len == 1)
6275 error (_("Remote qXfer reply contained no data."));
6277 /* Got some data. */
6278 i = remote_unescape_input (rs->buf + 1, packet_len - 1, readbuf, n);
6280 /* 'l' is an EOF marker, possibly including a final block of data,
6281 or possibly empty. If we have the final block of a non-empty
6282 object, record this fact to bypass a subsequent partial read. */
6283 if (rs->buf[0] == 'l' && offset + i > 0)
6285 finished_object = xstrdup (object_name);
6286 finished_annex = xstrdup (annex ? annex : "");
6287 finished_offset = offset + i;
6294 remote_xfer_partial (struct target_ops *ops, enum target_object object,
6295 const char *annex, gdb_byte *readbuf,
6296 const gdb_byte *writebuf, ULONGEST offset, LONGEST len)
6298 struct remote_state *rs;
6303 set_general_thread (inferior_ptid);
6305 rs = get_remote_state ();
6307 /* Handle memory using the standard memory routines. */
6308 if (object == TARGET_OBJECT_MEMORY)
6313 /* If the remote target is connected but not running, we should
6314 pass this request down to a lower stratum (e.g. the executable
6316 if (!target_has_execution)
6319 if (writebuf != NULL)
6320 xfered = remote_write_bytes (offset, writebuf, len);
6322 xfered = remote_read_bytes (offset, readbuf, len);
6326 else if (xfered == 0 && errno == 0)
6332 /* Handle SPU memory using qxfer packets. */
6333 if (object == TARGET_OBJECT_SPU)
6336 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
6337 &remote_protocol_packets
6338 [PACKET_qXfer_spu_read]);
6340 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
6341 &remote_protocol_packets
6342 [PACKET_qXfer_spu_write]);
6345 /* Only handle flash writes. */
6346 if (writebuf != NULL)
6352 case TARGET_OBJECT_FLASH:
6353 xfered = remote_flash_write (ops, offset, len, writebuf);
6357 else if (xfered == 0 && errno == 0)
6367 /* Map pre-existing objects onto letters. DO NOT do this for new
6368 objects!!! Instead specify new query packets. */
6371 case TARGET_OBJECT_AVR:
6375 case TARGET_OBJECT_AUXV:
6376 gdb_assert (annex == NULL);
6377 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
6378 &remote_protocol_packets[PACKET_qXfer_auxv]);
6380 case TARGET_OBJECT_AVAILABLE_FEATURES:
6381 return remote_read_qxfer
6382 (ops, "features", annex, readbuf, offset, len,
6383 &remote_protocol_packets[PACKET_qXfer_features]);
6385 case TARGET_OBJECT_LIBRARIES:
6386 return remote_read_qxfer
6387 (ops, "libraries", annex, readbuf, offset, len,
6388 &remote_protocol_packets[PACKET_qXfer_libraries]);
6390 case TARGET_OBJECT_MEMORY_MAP:
6391 gdb_assert (annex == NULL);
6392 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
6393 &remote_protocol_packets[PACKET_qXfer_memory_map]);
6399 /* Note: a zero OFFSET and LEN can be used to query the minimum
6401 if (offset == 0 && len == 0)
6402 return (get_remote_packet_size ());
6403 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
6404 large enough let the caller deal with it. */
6405 if (len < get_remote_packet_size ())
6407 len = get_remote_packet_size ();
6409 /* Except for querying the minimum buffer size, target must be open. */
6411 error (_("remote query is only available after target open"));
6413 gdb_assert (annex != NULL);
6414 gdb_assert (readbuf != NULL);
6420 /* We used one buffer char for the remote protocol q command and
6421 another for the query type. As the remote protocol encapsulation
6422 uses 4 chars plus one extra in case we are debugging
6423 (remote_debug), we have PBUFZIZ - 7 left to pack the query
6426 while (annex[i] && (i < (get_remote_packet_size () - 8)))
6428 /* Bad caller may have sent forbidden characters. */
6429 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
6434 gdb_assert (annex[i] == '\0');
6436 i = putpkt (rs->buf);
6440 getpkt (&rs->buf, &rs->buf_size, 0);
6441 strcpy ((char *) readbuf, rs->buf);
6443 return strlen ((char *) readbuf);
6447 remote_search_memory (struct target_ops* ops,
6448 CORE_ADDR start_addr, ULONGEST search_space_len,
6449 const gdb_byte *pattern, ULONGEST pattern_len,
6450 CORE_ADDR *found_addrp)
6452 struct remote_state *rs = get_remote_state ();
6453 int max_size = get_memory_write_packet_size ();
6454 struct packet_config *packet =
6455 &remote_protocol_packets[PACKET_qSearch_memory];
6456 /* number of packet bytes used to encode the pattern,
6457 this could be more than PATTERN_LEN due to escape characters */
6458 int escaped_pattern_len;
6459 /* amount of pattern that was encodable in the packet */
6460 int used_pattern_len;
6463 ULONGEST found_addr;
6465 /* Don't go to the target if we don't have to.
6466 This is done before checking packet->support to avoid the possibility that
6467 a success for this edge case means the facility works in general. */
6468 if (pattern_len > search_space_len)
6470 if (pattern_len == 0)
6472 *found_addrp = start_addr;
6476 /* If we already know the packet isn't supported, fall back to the simple
6477 way of searching memory. */
6479 if (packet->support == PACKET_DISABLE)
6481 /* Target doesn't provided special support, fall back and use the
6482 standard support (copy memory and do the search here). */
6483 return simple_search_memory (ops, start_addr, search_space_len,
6484 pattern, pattern_len, found_addrp);
6487 /* Insert header. */
6488 i = snprintf (rs->buf, max_size,
6489 "qSearch:memory:%s;%s;",
6490 paddr_nz (start_addr),
6491 phex_nz (search_space_len, sizeof (search_space_len)));
6492 max_size -= (i + 1);
6494 /* Escape as much data as fits into rs->buf. */
6495 escaped_pattern_len =
6496 remote_escape_output (pattern, pattern_len, (rs->buf + i),
6497 &used_pattern_len, max_size);
6499 /* Bail if the pattern is too large. */
6500 if (used_pattern_len != pattern_len)
6501 error ("Pattern is too large to transmit to remote target.");
6503 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
6504 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
6505 || packet_ok (rs->buf, packet) != PACKET_OK)
6507 /* The request may not have worked because the command is not
6508 supported. If so, fall back to the simple way. */
6509 if (packet->support == PACKET_DISABLE)
6511 return simple_search_memory (ops, start_addr, search_space_len,
6512 pattern, pattern_len, found_addrp);
6517 if (rs->buf[0] == '0')
6519 else if (rs->buf[0] == '1')
6522 if (rs->buf[1] != ',')
6523 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
6524 unpack_varlen_hex (rs->buf + 2, &found_addr);
6525 *found_addrp = found_addr;
6528 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
6534 remote_rcmd (char *command,
6535 struct ui_file *outbuf)
6537 struct remote_state *rs = get_remote_state ();
6541 error (_("remote rcmd is only available after target open"));
6543 /* Send a NULL command across as an empty command. */
6544 if (command == NULL)
6547 /* The query prefix. */
6548 strcpy (rs->buf, "qRcmd,");
6549 p = strchr (rs->buf, '\0');
6551 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/) > get_remote_packet_size ())
6552 error (_("\"monitor\" command ``%s'' is too long."), command);
6554 /* Encode the actual command. */
6555 bin2hex ((gdb_byte *) command, p, 0);
6557 if (putpkt (rs->buf) < 0)
6558 error (_("Communication problem with target."));
6560 /* get/display the response */
6565 /* XXX - see also tracepoint.c:remote_get_noisy_reply(). */
6567 getpkt (&rs->buf, &rs->buf_size, 0);
6570 error (_("Target does not support this command."));
6571 if (buf[0] == 'O' && buf[1] != 'K')
6573 remote_console_output (buf + 1); /* 'O' message from stub. */
6576 if (strcmp (buf, "OK") == 0)
6578 if (strlen (buf) == 3 && buf[0] == 'E'
6579 && isdigit (buf[1]) && isdigit (buf[2]))
6581 error (_("Protocol error with Rcmd"));
6583 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
6585 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
6586 fputc_unfiltered (c, outbuf);
6592 static VEC(mem_region_s) *
6593 remote_memory_map (struct target_ops *ops)
6595 VEC(mem_region_s) *result = NULL;
6596 char *text = target_read_stralloc (¤t_target,
6597 TARGET_OBJECT_MEMORY_MAP, NULL);
6601 struct cleanup *back_to = make_cleanup (xfree, text);
6602 result = parse_memory_map (text);
6603 do_cleanups (back_to);
6610 packet_command (char *args, int from_tty)
6612 struct remote_state *rs = get_remote_state ();
6615 error (_("command can only be used with remote target"));
6618 error (_("remote-packet command requires packet text as argument"));
6620 puts_filtered ("sending: ");
6621 print_packet (args);
6622 puts_filtered ("\n");
6625 getpkt (&rs->buf, &rs->buf_size, 0);
6626 puts_filtered ("received: ");
6627 print_packet (rs->buf);
6628 puts_filtered ("\n");
6632 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
6634 static void display_thread_info (struct gdb_ext_thread_info *info);
6636 static void threadset_test_cmd (char *cmd, int tty);
6638 static void threadalive_test (char *cmd, int tty);
6640 static void threadlist_test_cmd (char *cmd, int tty);
6642 int get_and_display_threadinfo (threadref *ref);
6644 static void threadinfo_test_cmd (char *cmd, int tty);
6646 static int thread_display_step (threadref *ref, void *context);
6648 static void threadlist_update_test_cmd (char *cmd, int tty);
6650 static void init_remote_threadtests (void);
6652 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
6655 threadset_test_cmd (char *cmd, int tty)
6657 int sample_thread = SAMPLE_THREAD;
6659 printf_filtered (_("Remote threadset test\n"));
6660 set_general_thread (sample_thread);
6665 threadalive_test (char *cmd, int tty)
6667 int sample_thread = SAMPLE_THREAD;
6668 int pid = ptid_get_pid (inferior_ptid);
6669 ptid_t ptid = ptid_build (pid, 0, sample_thread);
6671 if (remote_thread_alive (ptid))
6672 printf_filtered ("PASS: Thread alive test\n");
6674 printf_filtered ("FAIL: Thread alive test\n");
6677 void output_threadid (char *title, threadref *ref);
6680 output_threadid (char *title, threadref *ref)
6684 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
6686 printf_filtered ("%s %s\n", title, (&hexid[0]));
6690 threadlist_test_cmd (char *cmd, int tty)
6693 threadref nextthread;
6694 int done, result_count;
6695 threadref threadlist[3];
6697 printf_filtered ("Remote Threadlist test\n");
6698 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
6699 &result_count, &threadlist[0]))
6700 printf_filtered ("FAIL: threadlist test\n");
6703 threadref *scan = threadlist;
6704 threadref *limit = scan + result_count;
6706 while (scan < limit)
6707 output_threadid (" thread ", scan++);
6712 display_thread_info (struct gdb_ext_thread_info *info)
6714 output_threadid ("Threadid: ", &info->threadid);
6715 printf_filtered ("Name: %s\n ", info->shortname);
6716 printf_filtered ("State: %s\n", info->display);
6717 printf_filtered ("other: %s\n\n", info->more_display);
6721 get_and_display_threadinfo (threadref *ref)
6725 struct gdb_ext_thread_info threadinfo;
6727 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
6728 | TAG_MOREDISPLAY | TAG_DISPLAY;
6729 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
6730 display_thread_info (&threadinfo);
6735 threadinfo_test_cmd (char *cmd, int tty)
6737 int athread = SAMPLE_THREAD;
6741 int_to_threadref (&thread, athread);
6742 printf_filtered ("Remote Threadinfo test\n");
6743 if (!get_and_display_threadinfo (&thread))
6744 printf_filtered ("FAIL cannot get thread info\n");
6748 thread_display_step (threadref *ref, void *context)
6750 /* output_threadid(" threadstep ",ref); *//* simple test */
6751 return get_and_display_threadinfo (ref);
6755 threadlist_update_test_cmd (char *cmd, int tty)
6757 printf_filtered ("Remote Threadlist update test\n");
6758 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
6762 init_remote_threadtests (void)
6764 add_com ("tlist", class_obscure, threadlist_test_cmd, _("\
6765 Fetch and print the remote list of thread identifiers, one pkt only"));
6766 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
6767 _("Fetch and display info about one thread"));
6768 add_com ("tset", class_obscure, threadset_test_cmd,
6769 _("Test setting to a different thread"));
6770 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
6771 _("Iterate through updating all remote thread info"));
6772 add_com ("talive", class_obscure, threadalive_test,
6773 _(" Remote thread alive test "));
6778 /* Convert a thread ID to a string. Returns the string in a static
6782 remote_pid_to_str (ptid_t ptid)
6784 static char buf[64];
6785 struct remote_state *rs = get_remote_state ();
6787 if (ptid_equal (magic_null_ptid, ptid))
6789 xsnprintf (buf, sizeof buf, "Thread <main>");
6792 else if (remote_multi_process_p (rs)
6793 && ptid_get_tid (ptid) != 0 && ptid_get_pid (ptid) != 0)
6795 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
6796 ptid_get_pid (ptid), ptid_get_tid (ptid));
6799 else if (ptid_get_tid (ptid) != 0)
6801 xsnprintf (buf, sizeof buf, "Thread %ld",
6802 ptid_get_tid (ptid));
6806 return normal_pid_to_str (ptid);
6809 /* Get the address of the thread local variable in OBJFILE which is
6810 stored at OFFSET within the thread local storage for thread PTID. */
6813 remote_get_thread_local_address (ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
6815 if (remote_protocol_packets[PACKET_qGetTLSAddr].support != PACKET_DISABLE)
6817 struct remote_state *rs = get_remote_state ();
6819 char *endp = rs->buf + get_remote_packet_size ();
6820 enum packet_result result;
6822 strcpy (p, "qGetTLSAddr:");
6824 p = write_ptid (p, endp, ptid);
6826 p += hexnumstr (p, offset);
6828 p += hexnumstr (p, lm);
6832 getpkt (&rs->buf, &rs->buf_size, 0);
6833 result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_qGetTLSAddr]);
6834 if (result == PACKET_OK)
6838 unpack_varlen_hex (rs->buf, &result);
6841 else if (result == PACKET_UNKNOWN)
6842 throw_error (TLS_GENERIC_ERROR,
6843 _("Remote target doesn't support qGetTLSAddr packet"));
6845 throw_error (TLS_GENERIC_ERROR,
6846 _("Remote target failed to process qGetTLSAddr request"));
6849 throw_error (TLS_GENERIC_ERROR,
6850 _("TLS not supported or disabled on this target"));
6855 /* Support for inferring a target description based on the current
6856 architecture and the size of a 'g' packet. While the 'g' packet
6857 can have any size (since optional registers can be left off the
6858 end), some sizes are easily recognizable given knowledge of the
6859 approximate architecture. */
6861 struct remote_g_packet_guess
6864 const struct target_desc *tdesc;
6866 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
6867 DEF_VEC_O(remote_g_packet_guess_s);
6869 struct remote_g_packet_data
6871 VEC(remote_g_packet_guess_s) *guesses;
6874 static struct gdbarch_data *remote_g_packet_data_handle;
6877 remote_g_packet_data_init (struct obstack *obstack)
6879 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
6883 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
6884 const struct target_desc *tdesc)
6886 struct remote_g_packet_data *data
6887 = gdbarch_data (gdbarch, remote_g_packet_data_handle);
6888 struct remote_g_packet_guess new_guess, *guess;
6891 gdb_assert (tdesc != NULL);
6894 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
6896 if (guess->bytes == bytes)
6897 internal_error (__FILE__, __LINE__,
6898 "Duplicate g packet description added for size %d",
6901 new_guess.bytes = bytes;
6902 new_guess.tdesc = tdesc;
6903 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
6906 static const struct target_desc *
6907 remote_read_description (struct target_ops *target)
6909 struct remote_g_packet_data *data
6910 = gdbarch_data (target_gdbarch, remote_g_packet_data_handle);
6912 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
6914 struct remote_g_packet_guess *guess;
6916 int bytes = send_g_packet ();
6919 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
6921 if (guess->bytes == bytes)
6922 return guess->tdesc;
6924 /* We discard the g packet. A minor optimization would be to
6925 hold on to it, and fill the register cache once we have selected
6926 an architecture, but it's too tricky to do safely. */
6932 /* Remote file transfer support. This is host-initiated I/O, not
6933 target-initiated; for target-initiated, see remote-fileio.c. */
6935 /* If *LEFT is at least the length of STRING, copy STRING to
6936 *BUFFER, update *BUFFER to point to the new end of the buffer, and
6937 decrease *LEFT. Otherwise raise an error. */
6940 remote_buffer_add_string (char **buffer, int *left, char *string)
6942 int len = strlen (string);
6945 error (_("Packet too long for target."));
6947 memcpy (*buffer, string, len);
6951 /* NUL-terminate the buffer as a convenience, if there is
6957 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
6958 *BUFFER, update *BUFFER to point to the new end of the buffer, and
6959 decrease *LEFT. Otherwise raise an error. */
6962 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
6965 if (2 * len > *left)
6966 error (_("Packet too long for target."));
6968 bin2hex (bytes, *buffer, len);
6972 /* NUL-terminate the buffer as a convenience, if there is
6978 /* If *LEFT is large enough, convert VALUE to hex and add it to
6979 *BUFFER, update *BUFFER to point to the new end of the buffer, and
6980 decrease *LEFT. Otherwise raise an error. */
6983 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
6985 int len = hexnumlen (value);
6988 error (_("Packet too long for target."));
6990 hexnumstr (*buffer, value);
6994 /* NUL-terminate the buffer as a convenience, if there is
7000 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
7001 value, *REMOTE_ERRNO to the remote error number or zero if none
7002 was included, and *ATTACHMENT to point to the start of the annex
7003 if any. The length of the packet isn't needed here; there may
7004 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
7006 Return 0 if the packet could be parsed, -1 if it could not. If
7007 -1 is returned, the other variables may not be initialized. */
7010 remote_hostio_parse_result (char *buffer, int *retcode,
7011 int *remote_errno, char **attachment)
7018 if (buffer[0] != 'F')
7022 *retcode = strtol (&buffer[1], &p, 16);
7023 if (errno != 0 || p == &buffer[1])
7026 /* Check for ",errno". */
7030 *remote_errno = strtol (p + 1, &p2, 16);
7031 if (errno != 0 || p + 1 == p2)
7036 /* Check for ";attachment". If there is no attachment, the
7037 packet should end here. */
7040 *attachment = p + 1;
7043 else if (*p == '\0')
7049 /* Send a prepared I/O packet to the target and read its response.
7050 The prepared packet is in the global RS->BUF before this function
7051 is called, and the answer is there when we return.
7053 COMMAND_BYTES is the length of the request to send, which may include
7054 binary data. WHICH_PACKET is the packet configuration to check
7055 before attempting a packet. If an error occurs, *REMOTE_ERRNO
7056 is set to the error number and -1 is returned. Otherwise the value
7057 returned by the function is returned.
7059 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
7060 attachment is expected; an error will be reported if there's a
7061 mismatch. If one is found, *ATTACHMENT will be set to point into
7062 the packet buffer and *ATTACHMENT_LEN will be set to the
7063 attachment's length. */
7066 remote_hostio_send_command (int command_bytes, int which_packet,
7067 int *remote_errno, char **attachment,
7068 int *attachment_len)
7070 struct remote_state *rs = get_remote_state ();
7071 int ret, bytes_read;
7072 char *attachment_tmp;
7075 || remote_protocol_packets[which_packet].support == PACKET_DISABLE)
7077 *remote_errno = FILEIO_ENOSYS;
7081 putpkt_binary (rs->buf, command_bytes);
7082 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
7084 /* If it timed out, something is wrong. Don't try to parse the
7088 *remote_errno = FILEIO_EINVAL;
7092 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
7095 *remote_errno = FILEIO_EINVAL;
7097 case PACKET_UNKNOWN:
7098 *remote_errno = FILEIO_ENOSYS;
7104 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
7107 *remote_errno = FILEIO_EINVAL;
7111 /* Make sure we saw an attachment if and only if we expected one. */
7112 if ((attachment_tmp == NULL && attachment != NULL)
7113 || (attachment_tmp != NULL && attachment == NULL))
7115 *remote_errno = FILEIO_EINVAL;
7119 /* If an attachment was found, it must point into the packet buffer;
7120 work out how many bytes there were. */
7121 if (attachment_tmp != NULL)
7123 *attachment = attachment_tmp;
7124 *attachment_len = bytes_read - (*attachment - rs->buf);
7130 /* Open FILENAME on the remote target, using FLAGS and MODE. Return a
7131 remote file descriptor, or -1 if an error occurs (and set
7135 remote_hostio_open (const char *filename, int flags, int mode,
7138 struct remote_state *rs = get_remote_state ();
7140 int left = get_remote_packet_size () - 1;
7142 remote_buffer_add_string (&p, &left, "vFile:open:");
7144 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
7146 remote_buffer_add_string (&p, &left, ",");
7148 remote_buffer_add_int (&p, &left, flags);
7149 remote_buffer_add_string (&p, &left, ",");
7151 remote_buffer_add_int (&p, &left, mode);
7153 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
7154 remote_errno, NULL, NULL);
7157 /* Write up to LEN bytes from WRITE_BUF to FD on the remote target.
7158 Return the number of bytes written, or -1 if an error occurs (and
7159 set *REMOTE_ERRNO). */
7162 remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
7163 ULONGEST offset, int *remote_errno)
7165 struct remote_state *rs = get_remote_state ();
7167 int left = get_remote_packet_size ();
7170 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
7172 remote_buffer_add_int (&p, &left, fd);
7173 remote_buffer_add_string (&p, &left, ",");
7175 remote_buffer_add_int (&p, &left, offset);
7176 remote_buffer_add_string (&p, &left, ",");
7178 p += remote_escape_output (write_buf, len, p, &out_len,
7179 get_remote_packet_size () - (p - rs->buf));
7181 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
7182 remote_errno, NULL, NULL);
7185 /* Read up to LEN bytes FD on the remote target into READ_BUF
7186 Return the number of bytes read, or -1 if an error occurs (and
7187 set *REMOTE_ERRNO). */
7190 remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
7191 ULONGEST offset, int *remote_errno)
7193 struct remote_state *rs = get_remote_state ();
7196 int left = get_remote_packet_size ();
7197 int ret, attachment_len;
7200 remote_buffer_add_string (&p, &left, "vFile:pread:");
7202 remote_buffer_add_int (&p, &left, fd);
7203 remote_buffer_add_string (&p, &left, ",");
7205 remote_buffer_add_int (&p, &left, len);
7206 remote_buffer_add_string (&p, &left, ",");
7208 remote_buffer_add_int (&p, &left, offset);
7210 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
7211 remote_errno, &attachment,
7217 read_len = remote_unescape_input (attachment, attachment_len,
7219 if (read_len != ret)
7220 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
7225 /* Close FD on the remote target. Return 0, or -1 if an error occurs
7226 (and set *REMOTE_ERRNO). */
7229 remote_hostio_close (int fd, int *remote_errno)
7231 struct remote_state *rs = get_remote_state ();
7233 int left = get_remote_packet_size () - 1;
7235 remote_buffer_add_string (&p, &left, "vFile:close:");
7237 remote_buffer_add_int (&p, &left, fd);
7239 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
7240 remote_errno, NULL, NULL);
7243 /* Unlink FILENAME on the remote target. Return 0, or -1 if an error
7244 occurs (and set *REMOTE_ERRNO). */
7247 remote_hostio_unlink (const char *filename, int *remote_errno)
7249 struct remote_state *rs = get_remote_state ();
7251 int left = get_remote_packet_size () - 1;
7253 remote_buffer_add_string (&p, &left, "vFile:unlink:");
7255 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
7258 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
7259 remote_errno, NULL, NULL);
7263 remote_fileio_errno_to_host (int errnum)
7287 case FILEIO_ENOTDIR:
7307 case FILEIO_ENAMETOOLONG:
7308 return ENAMETOOLONG;
7314 remote_hostio_error (int errnum)
7316 int host_error = remote_fileio_errno_to_host (errnum);
7318 if (host_error == -1)
7319 error (_("Unknown remote I/O error %d"), errnum);
7321 error (_("Remote I/O error: %s"), safe_strerror (host_error));
7325 fclose_cleanup (void *file)
7331 remote_hostio_close_cleanup (void *opaque)
7333 int fd = *(int *) opaque;
7336 remote_hostio_close (fd, &remote_errno);
7341 remote_bfd_iovec_open (struct bfd *abfd, void *open_closure)
7343 const char *filename = bfd_get_filename (abfd);
7344 int fd, remote_errno;
7347 gdb_assert (remote_filename_p (filename));
7349 fd = remote_hostio_open (filename + 7, FILEIO_O_RDONLY, 0, &remote_errno);
7352 errno = remote_fileio_errno_to_host (remote_errno);
7353 bfd_set_error (bfd_error_system_call);
7357 stream = xmalloc (sizeof (int));
7363 remote_bfd_iovec_close (struct bfd *abfd, void *stream)
7365 int fd = *(int *)stream;
7370 /* Ignore errors on close; these may happen if the remote
7371 connection was already torn down. */
7372 remote_hostio_close (fd, &remote_errno);
7378 remote_bfd_iovec_pread (struct bfd *abfd, void *stream, void *buf,
7379 file_ptr nbytes, file_ptr offset)
7381 int fd = *(int *)stream;
7383 file_ptr pos, bytes;
7386 while (nbytes > pos)
7388 bytes = remote_hostio_pread (fd, (char *)buf + pos, nbytes - pos,
7389 offset + pos, &remote_errno);
7391 /* Success, but no bytes, means end-of-file. */
7395 errno = remote_fileio_errno_to_host (remote_errno);
7396 bfd_set_error (bfd_error_system_call);
7407 remote_bfd_iovec_stat (struct bfd *abfd, void *stream, struct stat *sb)
7409 /* FIXME: We should probably implement remote_hostio_stat. */
7410 sb->st_size = INT_MAX;
7415 remote_filename_p (const char *filename)
7417 return strncmp (filename, "remote:", 7) == 0;
7421 remote_bfd_open (const char *remote_file, const char *target)
7423 return bfd_openr_iovec (remote_file, target,
7424 remote_bfd_iovec_open, NULL,
7425 remote_bfd_iovec_pread,
7426 remote_bfd_iovec_close,
7427 remote_bfd_iovec_stat);
7431 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
7433 struct cleanup *back_to, *close_cleanup;
7434 int retcode, fd, remote_errno, bytes, io_size;
7437 int bytes_in_buffer;
7442 error (_("command can only be used with remote target"));
7444 file = fopen (local_file, "rb");
7446 perror_with_name (local_file);
7447 back_to = make_cleanup (fclose_cleanup, file);
7449 fd = remote_hostio_open (remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
7451 0700, &remote_errno);
7453 remote_hostio_error (remote_errno);
7455 /* Send up to this many bytes at once. They won't all fit in the
7456 remote packet limit, so we'll transfer slightly fewer. */
7457 io_size = get_remote_packet_size ();
7458 buffer = xmalloc (io_size);
7459 make_cleanup (xfree, buffer);
7461 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
7463 bytes_in_buffer = 0;
7466 while (bytes_in_buffer || !saw_eof)
7470 bytes = fread (buffer + bytes_in_buffer, 1, io_size - bytes_in_buffer,
7475 error (_("Error reading %s."), local_file);
7478 /* EOF. Unless there is something still in the
7479 buffer from the last iteration, we are done. */
7481 if (bytes_in_buffer == 0)
7489 bytes += bytes_in_buffer;
7490 bytes_in_buffer = 0;
7492 retcode = remote_hostio_pwrite (fd, buffer, bytes, offset, &remote_errno);
7495 remote_hostio_error (remote_errno);
7496 else if (retcode == 0)
7497 error (_("Remote write of %d bytes returned 0!"), bytes);
7498 else if (retcode < bytes)
7500 /* Short write. Save the rest of the read data for the next
7502 bytes_in_buffer = bytes - retcode;
7503 memmove (buffer, buffer + retcode, bytes_in_buffer);
7509 discard_cleanups (close_cleanup);
7510 if (remote_hostio_close (fd, &remote_errno))
7511 remote_hostio_error (remote_errno);
7514 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
7515 do_cleanups (back_to);
7519 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
7521 struct cleanup *back_to, *close_cleanup;
7522 int retcode, fd, remote_errno, bytes, io_size;
7528 error (_("command can only be used with remote target"));
7530 fd = remote_hostio_open (remote_file, FILEIO_O_RDONLY, 0, &remote_errno);
7532 remote_hostio_error (remote_errno);
7534 file = fopen (local_file, "wb");
7536 perror_with_name (local_file);
7537 back_to = make_cleanup (fclose_cleanup, file);
7539 /* Send up to this many bytes at once. They won't all fit in the
7540 remote packet limit, so we'll transfer slightly fewer. */
7541 io_size = get_remote_packet_size ();
7542 buffer = xmalloc (io_size);
7543 make_cleanup (xfree, buffer);
7545 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
7550 bytes = remote_hostio_pread (fd, buffer, io_size, offset, &remote_errno);
7552 /* Success, but no bytes, means end-of-file. */
7555 remote_hostio_error (remote_errno);
7559 bytes = fwrite (buffer, 1, bytes, file);
7561 perror_with_name (local_file);
7564 discard_cleanups (close_cleanup);
7565 if (remote_hostio_close (fd, &remote_errno))
7566 remote_hostio_error (remote_errno);
7569 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
7570 do_cleanups (back_to);
7574 remote_file_delete (const char *remote_file, int from_tty)
7576 int retcode, remote_errno;
7579 error (_("command can only be used with remote target"));
7581 retcode = remote_hostio_unlink (remote_file, &remote_errno);
7583 remote_hostio_error (remote_errno);
7586 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
7590 remote_put_command (char *args, int from_tty)
7592 struct cleanup *back_to;
7596 error_no_arg (_("file to put"));
7598 argv = gdb_buildargv (args);
7599 back_to = make_cleanup_freeargv (argv);
7600 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
7601 error (_("Invalid parameters to remote put"));
7603 remote_file_put (argv[0], argv[1], from_tty);
7605 do_cleanups (back_to);
7609 remote_get_command (char *args, int from_tty)
7611 struct cleanup *back_to;
7615 error_no_arg (_("file to get"));
7617 argv = gdb_buildargv (args);
7618 back_to = make_cleanup_freeargv (argv);
7619 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
7620 error (_("Invalid parameters to remote get"));
7622 remote_file_get (argv[0], argv[1], from_tty);
7624 do_cleanups (back_to);
7628 remote_delete_command (char *args, int from_tty)
7630 struct cleanup *back_to;
7634 error_no_arg (_("file to delete"));
7636 argv = gdb_buildargv (args);
7637 back_to = make_cleanup_freeargv (argv);
7638 if (argv[0] == NULL || argv[1] != NULL)
7639 error (_("Invalid parameters to remote delete"));
7641 remote_file_delete (argv[0], from_tty);
7643 do_cleanups (back_to);
7647 remote_command (char *args, int from_tty)
7649 help_list (remote_cmdlist, "remote ", -1, gdb_stdout);
7652 static int remote_target_can_reverse = 1;
7655 remote_can_execute_reverse (void)
7657 return remote_target_can_reverse;
7661 init_remote_ops (void)
7663 remote_ops.to_shortname = "remote";
7664 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
7666 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
7667 Specify the serial device it is connected to\n\
7668 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
7669 remote_ops.to_open = remote_open;
7670 remote_ops.to_close = remote_close;
7671 remote_ops.to_detach = remote_detach;
7672 remote_ops.to_disconnect = remote_disconnect;
7673 remote_ops.to_resume = remote_resume;
7674 remote_ops.to_wait = remote_wait;
7675 remote_ops.to_fetch_registers = remote_fetch_registers;
7676 remote_ops.to_store_registers = remote_store_registers;
7677 remote_ops.to_prepare_to_store = remote_prepare_to_store;
7678 remote_ops.deprecated_xfer_memory = remote_xfer_memory;
7679 remote_ops.to_files_info = remote_files_info;
7680 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
7681 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
7682 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
7683 remote_ops.to_stopped_data_address = remote_stopped_data_address;
7684 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
7685 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
7686 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
7687 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
7688 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
7689 remote_ops.to_kill = remote_kill;
7690 remote_ops.to_load = generic_load;
7691 remote_ops.to_mourn_inferior = remote_mourn;
7692 remote_ops.to_thread_alive = remote_thread_alive;
7693 remote_ops.to_find_new_threads = remote_threads_info;
7694 remote_ops.to_pid_to_str = remote_pid_to_str;
7695 remote_ops.to_extra_thread_info = remote_threads_extra_info;
7696 remote_ops.to_stop = remote_stop;
7697 remote_ops.to_xfer_partial = remote_xfer_partial;
7698 remote_ops.to_rcmd = remote_rcmd;
7699 remote_ops.to_log_command = serial_log_command;
7700 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
7701 remote_ops.to_stratum = process_stratum;
7702 remote_ops.to_has_all_memory = 1;
7703 remote_ops.to_has_memory = 1;
7704 remote_ops.to_has_stack = 1;
7705 remote_ops.to_has_registers = 1;
7706 remote_ops.to_has_execution = 1;
7707 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
7708 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
7709 remote_ops.to_magic = OPS_MAGIC;
7710 remote_ops.to_memory_map = remote_memory_map;
7711 remote_ops.to_flash_erase = remote_flash_erase;
7712 remote_ops.to_flash_done = remote_flash_done;
7713 remote_ops.to_read_description = remote_read_description;
7714 remote_ops.to_search_memory = remote_search_memory;
7715 remote_ops.to_can_async_p = remote_can_async_p;
7716 remote_ops.to_is_async_p = remote_is_async_p;
7717 remote_ops.to_async = remote_async;
7718 remote_ops.to_async_mask = remote_async_mask;
7719 remote_ops.to_terminal_inferior = remote_terminal_inferior;
7720 remote_ops.to_terminal_ours = remote_terminal_ours;
7723 /* Set up the extended remote vector by making a copy of the standard
7724 remote vector and adding to it. */
7727 init_extended_remote_ops (void)
7729 extended_remote_ops = remote_ops;
7731 extended_remote_ops.to_shortname = "extended-remote";
7732 extended_remote_ops.to_longname =
7733 "Extended remote serial target in gdb-specific protocol";
7734 extended_remote_ops.to_doc =
7735 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
7736 Specify the serial device it is connected to (e.g. /dev/ttya).";
7737 extended_remote_ops.to_open = extended_remote_open;
7738 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
7739 extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
7740 extended_remote_ops.to_detach = extended_remote_detach;
7741 extended_remote_ops.to_attach = extended_remote_attach;
7742 extended_remote_ops.to_kill = extended_remote_kill;
7746 remote_can_async_p (void)
7748 if (!target_async_permitted)
7749 /* We only enable async when the user specifically asks for it. */
7752 /* We're async whenever the serial device is. */
7753 return remote_async_mask_value && serial_can_async_p (remote_desc);
7757 remote_is_async_p (void)
7759 if (!target_async_permitted)
7760 /* We only enable async when the user specifically asks for it. */
7763 /* We're async whenever the serial device is. */
7764 return remote_async_mask_value && serial_is_async_p (remote_desc);
7767 /* Pass the SERIAL event on and up to the client. One day this code
7768 will be able to delay notifying the client of an event until the
7769 point where an entire packet has been received. */
7771 static void (*async_client_callback) (enum inferior_event_type event_type,
7773 static void *async_client_context;
7774 static serial_event_ftype remote_async_serial_handler;
7777 remote_async_serial_handler (struct serial *scb, void *context)
7779 /* Don't propogate error information up to the client. Instead let
7780 the client find out about the error by querying the target. */
7781 async_client_callback (INF_REG_EVENT, async_client_context);
7785 remote_async (void (*callback) (enum inferior_event_type event_type,
7786 void *context), void *context)
7788 if (remote_async_mask_value == 0)
7789 internal_error (__FILE__, __LINE__,
7790 _("Calling remote_async when async is masked"));
7792 if (callback != NULL)
7794 serial_async (remote_desc, remote_async_serial_handler, NULL);
7795 async_client_callback = callback;
7796 async_client_context = context;
7799 serial_async (remote_desc, NULL, NULL);
7803 remote_async_mask (int new_mask)
7805 int curr_mask = remote_async_mask_value;
7806 remote_async_mask_value = new_mask;
7811 set_remote_cmd (char *args, int from_tty)
7813 help_list (remote_set_cmdlist, "set remote ", -1, gdb_stdout);
7817 show_remote_cmd (char *args, int from_tty)
7819 /* We can't just use cmd_show_list here, because we want to skip
7820 the redundant "show remote Z-packet" and the legacy aliases. */
7821 struct cleanup *showlist_chain;
7822 struct cmd_list_element *list = remote_show_cmdlist;
7824 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
7825 for (; list != NULL; list = list->next)
7826 if (strcmp (list->name, "Z-packet") == 0)
7828 else if (list->type == not_set_cmd)
7829 /* Alias commands are exactly like the original, except they
7830 don't have the normal type. */
7834 struct cleanup *option_chain
7835 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
7836 ui_out_field_string (uiout, "name", list->name);
7837 ui_out_text (uiout, ": ");
7838 if (list->type == show_cmd)
7839 do_setshow_command ((char *) NULL, from_tty, list);
7841 cmd_func (list, NULL, from_tty);
7842 /* Close the tuple. */
7843 do_cleanups (option_chain);
7846 /* Close the tuple. */
7847 do_cleanups (showlist_chain);
7851 /* Function to be called whenever a new objfile (shlib) is detected. */
7853 remote_new_objfile (struct objfile *objfile)
7855 if (remote_desc != 0) /* Have a remote connection. */
7856 remote_check_symbols (objfile);
7860 _initialize_remote (void)
7862 struct remote_state *rs;
7864 /* architecture specific data */
7865 remote_gdbarch_data_handle =
7866 gdbarch_data_register_post_init (init_remote_state);
7867 remote_g_packet_data_handle =
7868 gdbarch_data_register_pre_init (remote_g_packet_data_init);
7870 /* Initialize the per-target state. At the moment there is only one
7871 of these, not one per target. Only one target is active at a
7872 time. The default buffer size is unimportant; it will be expanded
7873 whenever a larger buffer is needed. */
7874 rs = get_remote_state_raw ();
7876 rs->buf = xmalloc (rs->buf_size);
7879 add_target (&remote_ops);
7881 init_extended_remote_ops ();
7882 add_target (&extended_remote_ops);
7884 /* Hook into new objfile notification. */
7885 observer_attach_new_objfile (remote_new_objfile);
7887 /* Set up signal handlers. */
7888 sigint_remote_token =
7889 create_async_signal_handler (async_remote_interrupt, NULL);
7890 sigint_remote_twice_token =
7891 create_async_signal_handler (inferior_event_handler_wrapper, NULL);
7894 init_remote_threadtests ();
7897 /* set/show remote ... */
7899 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
7900 Remote protocol specific variables\n\
7901 Configure various remote-protocol specific variables such as\n\
7902 the packets being used"),
7903 &remote_set_cmdlist, "set remote ",
7904 0 /* allow-unknown */, &setlist);
7905 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
7906 Remote protocol specific variables\n\
7907 Configure various remote-protocol specific variables such as\n\
7908 the packets being used"),
7909 &remote_show_cmdlist, "show remote ",
7910 0 /* allow-unknown */, &showlist);
7912 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
7913 Compare section data on target to the exec file.\n\
7914 Argument is a single section name (default: all loaded sections)."),
7917 add_cmd ("packet", class_maintenance, packet_command, _("\
7918 Send an arbitrary packet to a remote target.\n\
7919 maintenance packet TEXT\n\
7920 If GDB is talking to an inferior via the GDB serial protocol, then\n\
7921 this command sends the string TEXT to the inferior, and displays the\n\
7922 response packet. GDB supplies the initial `$' character, and the\n\
7923 terminating `#' character and checksum."),
7926 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
7927 Set whether to send break if interrupted."), _("\
7928 Show whether to send break if interrupted."), _("\
7929 If set, a break, instead of a cntrl-c, is sent to the remote target."),
7930 NULL, NULL, /* FIXME: i18n: Whether to send break if interrupted is %s. */
7931 &setlist, &showlist);
7933 /* Install commands for configuring memory read/write packets. */
7935 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
7936 Set the maximum number of bytes per memory write packet (deprecated)."),
7938 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
7939 Show the maximum number of bytes per memory write packet (deprecated)."),
7941 add_cmd ("memory-write-packet-size", no_class,
7942 set_memory_write_packet_size, _("\
7943 Set the maximum number of bytes per memory-write packet.\n\
7944 Specify the number of bytes in a packet or 0 (zero) for the\n\
7945 default packet size. The actual limit is further reduced\n\
7946 dependent on the target. Specify ``fixed'' to disable the\n\
7947 further restriction and ``limit'' to enable that restriction."),
7948 &remote_set_cmdlist);
7949 add_cmd ("memory-read-packet-size", no_class,
7950 set_memory_read_packet_size, _("\
7951 Set the maximum number of bytes per memory-read packet.\n\
7952 Specify the number of bytes in a packet or 0 (zero) for the\n\
7953 default packet size. The actual limit is further reduced\n\
7954 dependent on the target. Specify ``fixed'' to disable the\n\
7955 further restriction and ``limit'' to enable that restriction."),
7956 &remote_set_cmdlist);
7957 add_cmd ("memory-write-packet-size", no_class,
7958 show_memory_write_packet_size,
7959 _("Show the maximum number of bytes per memory-write packet."),
7960 &remote_show_cmdlist);
7961 add_cmd ("memory-read-packet-size", no_class,
7962 show_memory_read_packet_size,
7963 _("Show the maximum number of bytes per memory-read packet."),
7964 &remote_show_cmdlist);
7966 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
7967 &remote_hw_watchpoint_limit, _("\
7968 Set the maximum number of target hardware watchpoints."), _("\
7969 Show the maximum number of target hardware watchpoints."), _("\
7970 Specify a negative limit for unlimited."),
7971 NULL, NULL, /* FIXME: i18n: The maximum number of target hardware watchpoints is %s. */
7972 &remote_set_cmdlist, &remote_show_cmdlist);
7973 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
7974 &remote_hw_breakpoint_limit, _("\
7975 Set the maximum number of target hardware breakpoints."), _("\
7976 Show the maximum number of target hardware breakpoints."), _("\
7977 Specify a negative limit for unlimited."),
7978 NULL, NULL, /* FIXME: i18n: The maximum number of target hardware breakpoints is %s. */
7979 &remote_set_cmdlist, &remote_show_cmdlist);
7981 add_setshow_integer_cmd ("remoteaddresssize", class_obscure,
7982 &remote_address_size, _("\
7983 Set the maximum size of the address (in bits) in a memory packet."), _("\
7984 Show the maximum size of the address (in bits) in a memory packet."), NULL,
7986 NULL, /* FIXME: i18n: */
7987 &setlist, &showlist);
7989 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
7990 "X", "binary-download", 1);
7992 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
7993 "vCont", "verbose-resume", 0);
7995 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
7996 "QPassSignals", "pass-signals", 0);
7998 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
7999 "qSymbol", "symbol-lookup", 0);
8001 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
8002 "P", "set-register", 1);
8004 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
8005 "p", "fetch-register", 1);
8007 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
8008 "Z0", "software-breakpoint", 0);
8010 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
8011 "Z1", "hardware-breakpoint", 0);
8013 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
8014 "Z2", "write-watchpoint", 0);
8016 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
8017 "Z3", "read-watchpoint", 0);
8019 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
8020 "Z4", "access-watchpoint", 0);
8022 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
8023 "qXfer:auxv:read", "read-aux-vector", 0);
8025 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
8026 "qXfer:features:read", "target-features", 0);
8028 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
8029 "qXfer:libraries:read", "library-info", 0);
8031 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
8032 "qXfer:memory-map:read", "memory-map", 0);
8034 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
8035 "qXfer:spu:read", "read-spu-object", 0);
8037 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
8038 "qXfer:spu:write", "write-spu-object", 0);
8040 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
8041 "qGetTLSAddr", "get-thread-local-storage-address",
8044 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
8045 "qSupported", "supported-packets", 0);
8047 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
8048 "qSearch:memory", "search-memory", 0);
8050 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
8051 "vFile:open", "hostio-open", 0);
8053 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
8054 "vFile:pread", "hostio-pread", 0);
8056 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
8057 "vFile:pwrite", "hostio-pwrite", 0);
8059 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
8060 "vFile:close", "hostio-close", 0);
8062 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
8063 "vFile:unlink", "hostio-unlink", 0);
8065 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
8066 "vAttach", "attach", 0);
8068 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
8071 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
8072 "QStartNoAckMode", "noack", 0);
8074 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
8075 "vKill", "kill", 0);
8077 /* Keep the old ``set remote Z-packet ...'' working. Each individual
8078 Z sub-packet has its own set and show commands, but users may
8079 have sets to this variable in their .gdbinit files (or in their
8081 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
8082 &remote_Z_packet_detect, _("\
8083 Set use of remote protocol `Z' packets"), _("\
8084 Show use of remote protocol `Z' packets "), _("\
8085 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
8087 set_remote_protocol_Z_packet_cmd,
8088 show_remote_protocol_Z_packet_cmd, /* FIXME: i18n: Use of remote protocol `Z' packets is %s. */
8089 &remote_set_cmdlist, &remote_show_cmdlist);
8091 add_prefix_cmd ("remote", class_files, remote_command, _("\
8092 Manipulate files on the remote system\n\
8093 Transfer files to and from the remote target system."),
8094 &remote_cmdlist, "remote ",
8095 0 /* allow-unknown */, &cmdlist);
8097 add_cmd ("put", class_files, remote_put_command,
8098 _("Copy a local file to the remote system."),
8101 add_cmd ("get", class_files, remote_get_command,
8102 _("Copy a remote file to the local system."),
8105 add_cmd ("delete", class_files, remote_delete_command,
8106 _("Delete a remote file."),
8109 remote_exec_file = xstrdup ("");
8110 add_setshow_string_noescape_cmd ("exec-file", class_files,
8111 &remote_exec_file, _("\
8112 Set the remote pathname for \"run\""), _("\
8113 Show the remote pathname for \"run\""), NULL, NULL, NULL,
8114 &remote_set_cmdlist, &remote_show_cmdlist);
8116 /* Eventually initialize fileio. See fileio.c */
8117 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
8119 /* Take advantage of the fact that the LWP field is not used, to tag
8120 special ptids with it set to != 0. */
8121 magic_null_ptid = ptid_build (42000, 1, -1);
8122 not_sent_ptid = ptid_build (42000, 1, -2);
8123 any_thread_ptid = ptid_build (42000, 1, 0);