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);
82 static int getpkt_or_notif_sane (char **buf, long *sizeof_buf,
85 static void handle_remote_sigint (int);
86 static void handle_remote_sigint_twice (int);
87 static void async_remote_interrupt (gdb_client_data);
88 void async_remote_interrupt_twice (gdb_client_data);
90 static void remote_files_info (struct target_ops *ignore);
92 static void remote_prepare_to_store (struct regcache *regcache);
94 static void remote_fetch_registers (struct regcache *regcache, int regno);
96 static void remote_resume (ptid_t ptid, int step,
97 enum target_signal siggnal);
98 static void remote_open (char *name, int from_tty);
100 static void extended_remote_open (char *name, int from_tty);
102 static void remote_open_1 (char *, int, struct target_ops *, int extended_p);
104 static void remote_close (int quitting);
106 static void remote_store_registers (struct regcache *regcache, int regno);
108 static void remote_mourn (void);
110 static void extended_remote_restart (void);
112 static void extended_remote_mourn (void);
114 static void remote_mourn_1 (struct target_ops *);
116 static void remote_send (char **buf, long *sizeof_buf_p);
118 static int readchar (int timeout);
120 static ptid_t remote_wait (ptid_t ptid,
121 struct target_waitstatus *status);
123 static void remote_kill (void);
125 static int tohex (int nib);
127 static int remote_can_async_p (void);
129 static int remote_is_async_p (void);
131 static void remote_async (void (*callback) (enum inferior_event_type event_type,
132 void *context), void *context);
134 static int remote_async_mask (int new_mask);
136 static void remote_detach (char *args, int from_tty);
138 static void remote_interrupt (int signo);
140 static void remote_interrupt_twice (int signo);
142 static void interrupt_query (void);
144 static void set_general_thread (struct ptid ptid);
145 static void set_continue_thread (struct ptid ptid);
147 static int remote_thread_alive (ptid_t);
149 static void get_offsets (void);
151 static void skip_frame (void);
153 static long read_frame (char **buf_p, long *sizeof_buf);
155 static int hexnumlen (ULONGEST num);
157 static void init_remote_ops (void);
159 static void init_extended_remote_ops (void);
161 static void remote_stop (ptid_t);
163 static int ishex (int ch, int *val);
165 static int stubhex (int ch);
167 static int hexnumstr (char *, ULONGEST);
169 static int hexnumnstr (char *, ULONGEST, int);
171 static CORE_ADDR remote_address_masked (CORE_ADDR);
173 static void print_packet (char *);
175 static unsigned long crc32 (unsigned char *, int, unsigned int);
177 static void compare_sections_command (char *, int);
179 static void packet_command (char *, int);
181 static int stub_unpack_int (char *buff, int fieldlength);
183 static ptid_t remote_current_thread (ptid_t oldptid);
185 static void remote_find_new_threads (void);
187 static void record_currthread (ptid_t currthread);
189 static int fromhex (int a);
191 static int hex2bin (const char *hex, gdb_byte *bin, int count);
193 static int bin2hex (const gdb_byte *bin, char *hex, int count);
195 static int putpkt_binary (char *buf, int cnt);
197 static void check_binary_download (CORE_ADDR addr);
199 struct packet_config;
201 static void show_packet_config_cmd (struct packet_config *config);
203 static void update_packet_config (struct packet_config *config);
205 static void set_remote_protocol_packet_cmd (char *args, int from_tty,
206 struct cmd_list_element *c);
208 static void show_remote_protocol_packet_cmd (struct ui_file *file,
210 struct cmd_list_element *c,
213 static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
214 static ptid_t read_ptid (char *buf, char **obuf);
216 static void remote_query_supported (void);
218 static void remote_check_symbols (struct objfile *objfile);
220 void _initialize_remote (void);
223 static struct stop_reply *stop_reply_xmalloc (void);
224 static void stop_reply_xfree (struct stop_reply *);
225 static void do_stop_reply_xfree (void *arg);
226 static void remote_parse_stop_reply (char *buf, struct stop_reply *);
227 static void push_stop_reply (struct stop_reply *);
228 static void remote_get_pending_stop_replies (void);
229 static void discard_pending_stop_replies (int pid);
230 static int peek_stop_reply (ptid_t ptid);
232 static void remote_async_inferior_event_handler (gdb_client_data);
233 static void remote_async_get_pending_events_handler (gdb_client_data);
235 /* The non-stop remote protocol provisions for one pending stop reply.
236 This is where we keep it until it is acknowledged. */
238 static struct stop_reply *pending_stop_reply = NULL;
242 static struct cmd_list_element *remote_cmdlist;
244 /* For "set remote" and "show remote". */
246 static struct cmd_list_element *remote_set_cmdlist;
247 static struct cmd_list_element *remote_show_cmdlist;
249 /* Description of the remote protocol state for the currently
250 connected target. This is per-target state, and independent of the
251 selected architecture. */
255 /* A buffer to use for incoming packets, and its current size. The
256 buffer is grown dynamically for larger incoming packets.
257 Outgoing packets may also be constructed in this buffer.
258 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
259 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
264 /* If we negotiated packet size explicitly (and thus can bypass
265 heuristics for the largest packet size that will not overflow
266 a buffer in the stub), this will be set to that packet size.
267 Otherwise zero, meaning to use the guessed size. */
268 long explicit_packet_size;
270 /* remote_wait is normally called when the target is running and
271 waits for a stop reply packet. But sometimes we need to call it
272 when the target is already stopped. We can send a "?" packet
273 and have remote_wait read the response. Or, if we already have
274 the response, we can stash it in BUF and tell remote_wait to
275 skip calling getpkt. This flag is set when BUF contains a
276 stop reply packet and the target is not waiting. */
277 int cached_wait_status;
279 /* True, if in no ack mode. That is, neither GDB nor the stub will
280 expect acks from each other. The connection is assumed to be
284 /* True if we're connected in extended remote mode. */
287 /* True if the stub reported support for multi-process
289 int multi_process_aware;
291 /* True if we resumed the target and we're waiting for the target to
292 stop. In the mean time, we can't start another command/query.
293 The remote server wouldn't be ready to process it, so we'd
294 timeout waiting for a reply that would never come and eventually
295 we'd close the connection. This can happen in asynchronous mode
296 because we allow GDB commands while the target is running. */
297 int waiting_for_stop_reply;
299 /* True if the stub reports support for non-stop mode. */
302 /* True if the stub reports support for vCont;t. */
306 /* Returns true if the multi-process extensions are in effect. */
308 remote_multi_process_p (struct remote_state *rs)
310 return rs->extended && rs->multi_process_aware;
313 /* This data could be associated with a target, but we do not always
314 have access to the current target when we need it, so for now it is
315 static. This will be fine for as long as only one target is in use
317 static struct remote_state remote_state;
319 static struct remote_state *
320 get_remote_state_raw (void)
322 return &remote_state;
325 /* Description of the remote protocol for a given architecture. */
329 long offset; /* Offset into G packet. */
330 long regnum; /* GDB's internal register number. */
331 LONGEST pnum; /* Remote protocol register number. */
332 int in_g_packet; /* Always part of G packet. */
333 /* long size in bytes; == register_size (target_gdbarch, regnum);
335 /* char *name; == gdbarch_register_name (target_gdbarch, regnum);
339 struct remote_arch_state
341 /* Description of the remote protocol registers. */
342 long sizeof_g_packet;
344 /* Description of the remote protocol registers indexed by REGNUM
345 (making an array gdbarch_num_regs in size). */
346 struct packet_reg *regs;
348 /* This is the size (in chars) of the first response to the ``g''
349 packet. It is used as a heuristic when determining the maximum
350 size of memory-read and memory-write packets. A target will
351 typically only reserve a buffer large enough to hold the ``g''
352 packet. The size does not include packet overhead (headers and
354 long actual_register_packet_size;
356 /* This is the maximum size (in chars) of a non read/write packet.
357 It is also used as a cap on the size of read/write packets. */
358 long remote_packet_size;
362 /* Handle for retreving the remote protocol data from gdbarch. */
363 static struct gdbarch_data *remote_gdbarch_data_handle;
365 static struct remote_arch_state *
366 get_remote_arch_state (void)
368 return gdbarch_data (target_gdbarch, remote_gdbarch_data_handle);
371 /* Fetch the global remote target state. */
373 static struct remote_state *
374 get_remote_state (void)
376 /* Make sure that the remote architecture state has been
377 initialized, because doing so might reallocate rs->buf. Any
378 function which calls getpkt also needs to be mindful of changes
379 to rs->buf, but this call limits the number of places which run
381 get_remote_arch_state ();
383 return get_remote_state_raw ();
387 compare_pnums (const void *lhs_, const void *rhs_)
389 const struct packet_reg * const *lhs = lhs_;
390 const struct packet_reg * const *rhs = rhs_;
392 if ((*lhs)->pnum < (*rhs)->pnum)
394 else if ((*lhs)->pnum == (*rhs)->pnum)
401 init_remote_state (struct gdbarch *gdbarch)
403 int regnum, num_remote_regs, offset;
404 struct remote_state *rs = get_remote_state_raw ();
405 struct remote_arch_state *rsa;
406 struct packet_reg **remote_regs;
408 rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
410 /* Use the architecture to build a regnum<->pnum table, which will be
411 1:1 unless a feature set specifies otherwise. */
412 rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
413 gdbarch_num_regs (gdbarch),
415 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
417 struct packet_reg *r = &rsa->regs[regnum];
419 if (register_size (gdbarch, regnum) == 0)
420 /* Do not try to fetch zero-sized (placeholder) registers. */
423 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
428 /* Define the g/G packet format as the contents of each register
429 with a remote protocol number, in order of ascending protocol
432 remote_regs = alloca (gdbarch_num_regs (gdbarch)
433 * sizeof (struct packet_reg *));
434 for (num_remote_regs = 0, regnum = 0;
435 regnum < gdbarch_num_regs (gdbarch);
437 if (rsa->regs[regnum].pnum != -1)
438 remote_regs[num_remote_regs++] = &rsa->regs[regnum];
440 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
443 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
445 remote_regs[regnum]->in_g_packet = 1;
446 remote_regs[regnum]->offset = offset;
447 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
450 /* Record the maximum possible size of the g packet - it may turn out
452 rsa->sizeof_g_packet = offset;
454 /* Default maximum number of characters in a packet body. Many
455 remote stubs have a hardwired buffer size of 400 bytes
456 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
457 as the maximum packet-size to ensure that the packet and an extra
458 NUL character can always fit in the buffer. This stops GDB
459 trashing stubs that try to squeeze an extra NUL into what is
460 already a full buffer (As of 1999-12-04 that was most stubs). */
461 rsa->remote_packet_size = 400 - 1;
463 /* This one is filled in when a ``g'' packet is received. */
464 rsa->actual_register_packet_size = 0;
466 /* Should rsa->sizeof_g_packet needs more space than the
467 default, adjust the size accordingly. Remember that each byte is
468 encoded as two characters. 32 is the overhead for the packet
469 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
470 (``$NN:G...#NN'') is a better guess, the below has been padded a
472 if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
473 rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
475 /* Make sure that the packet buffer is plenty big enough for
476 this architecture. */
477 if (rs->buf_size < rsa->remote_packet_size)
479 rs->buf_size = 2 * rsa->remote_packet_size;
480 rs->buf = xrealloc (rs->buf, rs->buf_size);
486 /* Return the current allowed size of a remote packet. This is
487 inferred from the current architecture, and should be used to
488 limit the length of outgoing packets. */
490 get_remote_packet_size (void)
492 struct remote_state *rs = get_remote_state ();
493 struct remote_arch_state *rsa = get_remote_arch_state ();
495 if (rs->explicit_packet_size)
496 return rs->explicit_packet_size;
498 return rsa->remote_packet_size;
501 static struct packet_reg *
502 packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
504 if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch))
508 struct packet_reg *r = &rsa->regs[regnum];
509 gdb_assert (r->regnum == regnum);
514 static struct packet_reg *
515 packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
518 for (i = 0; i < gdbarch_num_regs (target_gdbarch); i++)
520 struct packet_reg *r = &rsa->regs[i];
527 /* FIXME: graces/2002-08-08: These variables should eventually be
528 bound to an instance of the target object (as in gdbarch-tdep()),
529 when such a thing exists. */
531 /* This is set to the data address of the access causing the target
532 to stop for a watchpoint. */
533 static CORE_ADDR remote_watch_data_address;
535 /* This is non-zero if target stopped for a watchpoint. */
536 static int remote_stopped_by_watchpoint_p;
538 static struct target_ops remote_ops;
540 static struct target_ops extended_remote_ops;
542 static int remote_async_mask_value = 1;
544 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
545 ``forever'' still use the normal timeout mechanism. This is
546 currently used by the ASYNC code to guarentee that target reads
547 during the initial connect always time-out. Once getpkt has been
548 modified to return a timeout indication and, in turn
549 remote_wait()/wait_for_inferior() have gained a timeout parameter
551 static int wait_forever_enabled_p = 1;
554 /* This variable chooses whether to send a ^C or a break when the user
555 requests program interruption. Although ^C is usually what remote
556 systems expect, and that is the default here, sometimes a break is
557 preferable instead. */
559 static int remote_break;
561 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
562 remote_open knows that we don't have a file open when the program
564 static struct serial *remote_desc = NULL;
566 /* This variable sets the number of bits in an address that are to be
567 sent in a memory ("M" or "m") packet. Normally, after stripping
568 leading zeros, the entire address would be sent. This variable
569 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
570 initial implementation of remote.c restricted the address sent in
571 memory packets to ``host::sizeof long'' bytes - (typically 32
572 bits). Consequently, for 64 bit targets, the upper 32 bits of an
573 address was never sent. Since fixing this bug may cause a break in
574 some remote targets this variable is principly provided to
575 facilitate backward compatibility. */
577 static int remote_address_size;
579 /* Temporary to track who currently owns the terminal. See
580 remote_terminal_* for more details. */
582 static int remote_async_terminal_ours_p;
584 /* The executable file to use for "run" on the remote side. */
586 static char *remote_exec_file = "";
589 /* User configurable variables for the number of characters in a
590 memory read/write packet. MIN (rsa->remote_packet_size,
591 rsa->sizeof_g_packet) is the default. Some targets need smaller
592 values (fifo overruns, et.al.) and some users need larger values
593 (speed up transfers). The variables ``preferred_*'' (the user
594 request), ``current_*'' (what was actually set) and ``forced_*''
595 (Positive - a soft limit, negative - a hard limit). */
597 struct memory_packet_config
604 /* Compute the current size of a read/write packet. Since this makes
605 use of ``actual_register_packet_size'' the computation is dynamic. */
608 get_memory_packet_size (struct memory_packet_config *config)
610 struct remote_state *rs = get_remote_state ();
611 struct remote_arch_state *rsa = get_remote_arch_state ();
613 /* NOTE: The somewhat arbitrary 16k comes from the knowledge (folk
614 law?) that some hosts don't cope very well with large alloca()
615 calls. Eventually the alloca() code will be replaced by calls to
616 xmalloc() and make_cleanups() allowing this restriction to either
617 be lifted or removed. */
618 #ifndef MAX_REMOTE_PACKET_SIZE
619 #define MAX_REMOTE_PACKET_SIZE 16384
621 /* NOTE: 20 ensures we can write at least one byte. */
622 #ifndef MIN_REMOTE_PACKET_SIZE
623 #define MIN_REMOTE_PACKET_SIZE 20
628 if (config->size <= 0)
629 what_they_get = MAX_REMOTE_PACKET_SIZE;
631 what_they_get = config->size;
635 what_they_get = get_remote_packet_size ();
636 /* Limit the packet to the size specified by the user. */
638 && what_they_get > config->size)
639 what_they_get = config->size;
641 /* Limit it to the size of the targets ``g'' response unless we have
642 permission from the stub to use a larger packet size. */
643 if (rs->explicit_packet_size == 0
644 && rsa->actual_register_packet_size > 0
645 && what_they_get > rsa->actual_register_packet_size)
646 what_they_get = rsa->actual_register_packet_size;
648 if (what_they_get > MAX_REMOTE_PACKET_SIZE)
649 what_they_get = MAX_REMOTE_PACKET_SIZE;
650 if (what_they_get < MIN_REMOTE_PACKET_SIZE)
651 what_they_get = MIN_REMOTE_PACKET_SIZE;
653 /* Make sure there is room in the global buffer for this packet
654 (including its trailing NUL byte). */
655 if (rs->buf_size < what_they_get + 1)
657 rs->buf_size = 2 * what_they_get;
658 rs->buf = xrealloc (rs->buf, 2 * what_they_get);
661 return what_they_get;
664 /* Update the size of a read/write packet. If they user wants
665 something really big then do a sanity check. */
668 set_memory_packet_size (char *args, struct memory_packet_config *config)
670 int fixed_p = config->fixed_p;
671 long size = config->size;
673 error (_("Argument required (integer, `fixed' or `limited')."));
674 else if (strcmp (args, "hard") == 0
675 || strcmp (args, "fixed") == 0)
677 else if (strcmp (args, "soft") == 0
678 || strcmp (args, "limit") == 0)
683 size = strtoul (args, &end, 0);
685 error (_("Invalid %s (bad syntax)."), config->name);
687 /* Instead of explicitly capping the size of a packet to
688 MAX_REMOTE_PACKET_SIZE or dissallowing it, the user is
689 instead allowed to set the size to something arbitrarily
691 if (size > MAX_REMOTE_PACKET_SIZE)
692 error (_("Invalid %s (too large)."), config->name);
696 if (fixed_p && !config->fixed_p)
698 if (! query (_("The target may not be able to correctly handle a %s\n"
699 "of %ld bytes. Change the packet size? "),
701 error (_("Packet size not changed."));
703 /* Update the config. */
704 config->fixed_p = fixed_p;
709 show_memory_packet_size (struct memory_packet_config *config)
711 printf_filtered (_("The %s is %ld. "), config->name, config->size);
713 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
714 get_memory_packet_size (config));
716 printf_filtered (_("Packets are limited to %ld bytes.\n"),
717 get_memory_packet_size (config));
720 static struct memory_packet_config memory_write_packet_config =
722 "memory-write-packet-size",
726 set_memory_write_packet_size (char *args, int from_tty)
728 set_memory_packet_size (args, &memory_write_packet_config);
732 show_memory_write_packet_size (char *args, int from_tty)
734 show_memory_packet_size (&memory_write_packet_config);
738 get_memory_write_packet_size (void)
740 return get_memory_packet_size (&memory_write_packet_config);
743 static struct memory_packet_config memory_read_packet_config =
745 "memory-read-packet-size",
749 set_memory_read_packet_size (char *args, int from_tty)
751 set_memory_packet_size (args, &memory_read_packet_config);
755 show_memory_read_packet_size (char *args, int from_tty)
757 show_memory_packet_size (&memory_read_packet_config);
761 get_memory_read_packet_size (void)
763 long size = get_memory_packet_size (&memory_read_packet_config);
764 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
765 extra buffer size argument before the memory read size can be
766 increased beyond this. */
767 if (size > get_remote_packet_size ())
768 size = get_remote_packet_size ();
773 /* Generic configuration support for packets the stub optionally
774 supports. Allows the user to specify the use of the packet as well
775 as allowing GDB to auto-detect support in the remote stub. */
779 PACKET_SUPPORT_UNKNOWN = 0,
788 enum auto_boolean detect;
789 enum packet_support support;
792 /* Analyze a packet's return value and update the packet config
803 update_packet_config (struct packet_config *config)
805 switch (config->detect)
807 case AUTO_BOOLEAN_TRUE:
808 config->support = PACKET_ENABLE;
810 case AUTO_BOOLEAN_FALSE:
811 config->support = PACKET_DISABLE;
813 case AUTO_BOOLEAN_AUTO:
814 config->support = PACKET_SUPPORT_UNKNOWN;
820 show_packet_config_cmd (struct packet_config *config)
822 char *support = "internal-error";
823 switch (config->support)
829 support = "disabled";
831 case PACKET_SUPPORT_UNKNOWN:
835 switch (config->detect)
837 case AUTO_BOOLEAN_AUTO:
838 printf_filtered (_("Support for the `%s' packet is auto-detected, currently %s.\n"),
839 config->name, support);
841 case AUTO_BOOLEAN_TRUE:
842 case AUTO_BOOLEAN_FALSE:
843 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
844 config->name, support);
850 add_packet_config_cmd (struct packet_config *config, const char *name,
851 const char *title, int legacy)
858 config->title = title;
859 config->detect = AUTO_BOOLEAN_AUTO;
860 config->support = PACKET_SUPPORT_UNKNOWN;
861 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
863 show_doc = xstrprintf ("Show current use of remote protocol `%s' (%s) packet",
865 /* set/show TITLE-packet {auto,on,off} */
866 cmd_name = xstrprintf ("%s-packet", title);
867 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
868 &config->detect, set_doc, show_doc, NULL, /* help_doc */
869 set_remote_protocol_packet_cmd,
870 show_remote_protocol_packet_cmd,
871 &remote_set_cmdlist, &remote_show_cmdlist);
872 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
876 legacy_name = xstrprintf ("%s-packet", name);
877 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
878 &remote_set_cmdlist);
879 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
880 &remote_show_cmdlist);
884 static enum packet_result
885 packet_check_result (const char *buf)
889 /* The stub recognized the packet request. Check that the
890 operation succeeded. */
892 && isxdigit (buf[1]) && isxdigit (buf[2])
894 /* "Enn" - definitly an error. */
897 /* Always treat "E." as an error. This will be used for
898 more verbose error messages, such as E.memtypes. */
899 if (buf[0] == 'E' && buf[1] == '.')
902 /* The packet may or may not be OK. Just assume it is. */
906 /* The stub does not support the packet. */
907 return PACKET_UNKNOWN;
910 static enum packet_result
911 packet_ok (const char *buf, struct packet_config *config)
913 enum packet_result result;
915 result = packet_check_result (buf);
920 /* The stub recognized the packet request. */
921 switch (config->support)
923 case PACKET_SUPPORT_UNKNOWN:
925 fprintf_unfiltered (gdb_stdlog,
926 "Packet %s (%s) is supported\n",
927 config->name, config->title);
928 config->support = PACKET_ENABLE;
931 internal_error (__FILE__, __LINE__,
932 _("packet_ok: attempt to use a disabled packet"));
939 /* The stub does not support the packet. */
940 switch (config->support)
943 if (config->detect == AUTO_BOOLEAN_AUTO)
944 /* If the stub previously indicated that the packet was
945 supported then there is a protocol error.. */
946 error (_("Protocol error: %s (%s) conflicting enabled responses."),
947 config->name, config->title);
949 /* The user set it wrong. */
950 error (_("Enabled packet %s (%s) not recognized by stub"),
951 config->name, config->title);
953 case PACKET_SUPPORT_UNKNOWN:
955 fprintf_unfiltered (gdb_stdlog,
956 "Packet %s (%s) is NOT supported\n",
957 config->name, config->title);
958 config->support = PACKET_DISABLE;
986 PACKET_qXfer_features,
987 PACKET_qXfer_libraries,
988 PACKET_qXfer_memory_map,
989 PACKET_qXfer_spu_read,
990 PACKET_qXfer_spu_write,
994 PACKET_qSearch_memory,
997 PACKET_QStartNoAckMode,
1002 static struct packet_config remote_protocol_packets[PACKET_MAX];
1005 set_remote_protocol_packet_cmd (char *args, int from_tty,
1006 struct cmd_list_element *c)
1008 struct packet_config *packet;
1010 for (packet = remote_protocol_packets;
1011 packet < &remote_protocol_packets[PACKET_MAX];
1014 if (&packet->detect == c->var)
1016 update_packet_config (packet);
1020 internal_error (__FILE__, __LINE__, "Could not find config for %s",
1025 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1026 struct cmd_list_element *c,
1029 struct packet_config *packet;
1031 for (packet = remote_protocol_packets;
1032 packet < &remote_protocol_packets[PACKET_MAX];
1035 if (&packet->detect == c->var)
1037 show_packet_config_cmd (packet);
1041 internal_error (__FILE__, __LINE__, "Could not find config for %s",
1045 /* Should we try one of the 'Z' requests? */
1049 Z_PACKET_SOFTWARE_BP,
1050 Z_PACKET_HARDWARE_BP,
1057 /* For compatibility with older distributions. Provide a ``set remote
1058 Z-packet ...'' command that updates all the Z packet types. */
1060 static enum auto_boolean remote_Z_packet_detect;
1063 set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1064 struct cmd_list_element *c)
1067 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1069 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
1070 update_packet_config (&remote_protocol_packets[PACKET_Z0 + i]);
1075 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1076 struct cmd_list_element *c,
1080 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1082 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
1086 /* Should we try the 'ThreadInfo' query packet?
1088 This variable (NOT available to the user: auto-detect only!)
1089 determines whether GDB will use the new, simpler "ThreadInfo"
1090 query or the older, more complex syntax for thread queries.
1091 This is an auto-detect variable (set to true at each connect,
1092 and set to false when the target fails to recognize it). */
1094 static int use_threadinfo_query;
1095 static int use_threadextra_query;
1097 /* Tokens for use by the asynchronous signal handlers for SIGINT. */
1098 static struct async_signal_handler *sigint_remote_twice_token;
1099 static struct async_signal_handler *sigint_remote_token;
1102 /* Asynchronous signal handle registered as event loop source for
1103 when we have pending events ready to be passed to the core. */
1105 static struct async_event_handler *remote_async_inferior_event_token;
1107 /* Asynchronous signal handle registered as event loop source for when
1108 the remote sent us a %Stop notification. The registered callback
1109 will do a vStopped sequence to pull the rest of the events out of
1110 the remote side into our event queue. */
1112 static struct async_event_handler *remote_async_get_pending_events_token;
1115 static ptid_t magic_null_ptid;
1116 static ptid_t not_sent_ptid;
1117 static ptid_t any_thread_ptid;
1119 /* These are the threads which we last sent to the remote system. The
1120 TID member will be -1 for all or -2 for not sent yet. */
1122 static ptid_t general_thread;
1123 static ptid_t continue_thread;
1126 notice_new_inferiors (ptid_t currthread)
1128 /* When connecting to a target remote, or to a target
1129 extended-remote which already was debugging an inferior, we may
1130 not know about it yet. Add it before adding its child thread, so
1131 notifications are emitted in a sensible order. */
1132 if (!in_inferior_list (ptid_get_pid (currthread)))
1133 add_inferior (ptid_get_pid (currthread));
1135 /* If this is a new thread, add it to GDB's thread list.
1136 If we leave it up to WFI to do this, bad things will happen. */
1138 if (in_thread_list (currthread) && is_exited (currthread))
1140 /* We're seeing an event on a thread id we knew had exited.
1141 This has to be a new thread reusing the old id. Add it. */
1142 add_thread (currthread);
1146 if (!in_thread_list (currthread))
1148 if (ptid_equal (pid_to_ptid (ptid_get_pid (currthread)), inferior_ptid))
1150 /* inferior_ptid has no thread member yet. This can happen
1151 with the vAttach -> remote_wait,"TAAthread:" path if the
1152 stub doesn't support qC. This is the first stop reported
1153 after an attach, so this is the main thread. Update the
1154 ptid in the thread list. */
1155 thread_change_ptid (inferior_ptid, currthread);
1159 if (ptid_equal (magic_null_ptid, inferior_ptid))
1161 /* inferior_ptid is not set yet. This can happen with the
1162 vRun -> remote_wait,"TAAthread:" path if the stub
1163 doesn't support qC. This is the first stop reported
1164 after an attach, so this is the main thread. Update the
1165 ptid in the thread list. */
1166 thread_change_ptid (inferior_ptid, currthread);
1170 /* This is really a new thread. Add it. */
1171 add_thread (currthread);
1175 /* Call this function as a result of
1176 1) A halt indication (T packet) containing a thread id
1177 2) A direct query of currthread
1178 3) Successful execution of set thread
1182 record_currthread (ptid_t currthread)
1184 general_thread = currthread;
1186 if (ptid_equal (currthread, minus_one_ptid))
1187 /* We're just invalidating the local thread mirror. */
1190 notice_new_inferiors (currthread);
1193 static char *last_pass_packet;
1195 /* If 'QPassSignals' is supported, tell the remote stub what signals
1196 it can simply pass through to the inferior without reporting. */
1199 remote_pass_signals (void)
1201 if (remote_protocol_packets[PACKET_QPassSignals].support != PACKET_DISABLE)
1203 char *pass_packet, *p;
1204 int numsigs = (int) TARGET_SIGNAL_LAST;
1207 gdb_assert (numsigs < 256);
1208 for (i = 0; i < numsigs; i++)
1210 if (signal_stop_state (i) == 0
1211 && signal_print_state (i) == 0
1212 && signal_pass_state (i) == 1)
1215 pass_packet = xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
1216 strcpy (pass_packet, "QPassSignals:");
1217 p = pass_packet + strlen (pass_packet);
1218 for (i = 0; i < numsigs; i++)
1220 if (signal_stop_state (i) == 0
1221 && signal_print_state (i) == 0
1222 && signal_pass_state (i) == 1)
1225 *p++ = tohex (i >> 4);
1226 *p++ = tohex (i & 15);
1235 if (!last_pass_packet || strcmp (last_pass_packet, pass_packet))
1237 struct remote_state *rs = get_remote_state ();
1238 char *buf = rs->buf;
1240 putpkt (pass_packet);
1241 getpkt (&rs->buf, &rs->buf_size, 0);
1242 packet_ok (buf, &remote_protocol_packets[PACKET_QPassSignals]);
1243 if (last_pass_packet)
1244 xfree (last_pass_packet);
1245 last_pass_packet = pass_packet;
1248 xfree (pass_packet);
1252 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
1253 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
1254 thread. If GEN is set, set the general thread, if not, then set
1255 the step/continue thread. */
1257 set_thread (struct ptid ptid, int gen)
1259 struct remote_state *rs = get_remote_state ();
1260 ptid_t state = gen ? general_thread : continue_thread;
1261 char *buf = rs->buf;
1262 char *endbuf = rs->buf + get_remote_packet_size ();
1264 if (ptid_equal (state, ptid))
1268 *buf++ = gen ? 'g' : 'c';
1269 if (ptid_equal (ptid, magic_null_ptid))
1270 xsnprintf (buf, endbuf - buf, "0");
1271 else if (ptid_equal (ptid, any_thread_ptid))
1272 xsnprintf (buf, endbuf - buf, "0");
1273 else if (ptid_equal (ptid, minus_one_ptid))
1274 xsnprintf (buf, endbuf - buf, "-1");
1276 write_ptid (buf, endbuf, ptid);
1278 getpkt (&rs->buf, &rs->buf_size, 0);
1280 general_thread = ptid;
1282 continue_thread = ptid;
1286 set_general_thread (struct ptid ptid)
1288 set_thread (ptid, 1);
1292 set_continue_thread (struct ptid ptid)
1294 set_thread (ptid, 0);
1297 /* Change the remote current process. Which thread within the process
1298 ends up selected isn't important, as long as it is the same process
1299 as what INFERIOR_PTID points to.
1301 This comes from that fact that there is no explicit notion of
1302 "selected process" in the protocol. The selected process for
1303 general operations is the process the selected general thread
1307 set_general_process (void)
1309 struct remote_state *rs = get_remote_state ();
1311 /* If the remote can't handle multiple processes, don't bother. */
1312 if (!remote_multi_process_p (rs))
1315 /* We only need to change the remote current thread if it's pointing
1316 at some other process. */
1317 if (ptid_get_pid (general_thread) != ptid_get_pid (inferior_ptid))
1318 set_general_thread (inferior_ptid);
1322 /* Return nonzero if the thread PTID is still alive on the remote
1326 remote_thread_alive (ptid_t ptid)
1328 struct remote_state *rs = get_remote_state ();
1329 int tid = ptid_get_tid (ptid);
1332 if (ptid_equal (ptid, magic_null_ptid))
1333 /* The main thread is always alive. */
1336 if (ptid_get_pid (ptid) != 0 && ptid_get_tid (ptid) == 0)
1337 /* The main thread is always alive. This can happen after a
1338 vAttach, if the remote side doesn't support
1343 endp = rs->buf + get_remote_packet_size ();
1346 write_ptid (p, endp, ptid);
1349 getpkt (&rs->buf, &rs->buf_size, 0);
1350 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
1353 /* About these extended threadlist and threadinfo packets. They are
1354 variable length packets but, the fields within them are often fixed
1355 length. They are redundent enough to send over UDP as is the
1356 remote protocol in general. There is a matching unit test module
1359 #define OPAQUETHREADBYTES 8
1361 /* a 64 bit opaque identifier */
1362 typedef unsigned char threadref[OPAQUETHREADBYTES];
1364 /* WARNING: This threadref data structure comes from the remote O.S.,
1365 libstub protocol encoding, and remote.c. it is not particularly
1368 /* Right now, the internal structure is int. We want it to be bigger.
1372 typedef int gdb_threadref; /* Internal GDB thread reference. */
1374 /* gdb_ext_thread_info is an internal GDB data structure which is
1375 equivalent to the reply of the remote threadinfo packet. */
1377 struct gdb_ext_thread_info
1379 threadref threadid; /* External form of thread reference. */
1380 int active; /* Has state interesting to GDB?
1382 char display[256]; /* Brief state display, name,
1383 blocked/suspended. */
1384 char shortname[32]; /* To be used to name threads. */
1385 char more_display[256]; /* Long info, statistics, queue depth,
1389 /* The volume of remote transfers can be limited by submitting
1390 a mask containing bits specifying the desired information.
1391 Use a union of these values as the 'selection' parameter to
1392 get_thread_info. FIXME: Make these TAG names more thread specific.
1395 #define TAG_THREADID 1
1396 #define TAG_EXISTS 2
1397 #define TAG_DISPLAY 4
1398 #define TAG_THREADNAME 8
1399 #define TAG_MOREDISPLAY 16
1401 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
1403 char *unpack_varlen_hex (char *buff, ULONGEST *result);
1405 static char *unpack_nibble (char *buf, int *val);
1407 static char *pack_nibble (char *buf, int nibble);
1409 static char *pack_hex_byte (char *pkt, int /* unsigned char */ byte);
1411 static char *unpack_byte (char *buf, int *value);
1413 static char *pack_int (char *buf, int value);
1415 static char *unpack_int (char *buf, int *value);
1417 static char *unpack_string (char *src, char *dest, int length);
1419 static char *pack_threadid (char *pkt, threadref *id);
1421 static char *unpack_threadid (char *inbuf, threadref *id);
1423 void int_to_threadref (threadref *id, int value);
1425 static int threadref_to_int (threadref *ref);
1427 static void copy_threadref (threadref *dest, threadref *src);
1429 static int threadmatch (threadref *dest, threadref *src);
1431 static char *pack_threadinfo_request (char *pkt, int mode,
1434 static int remote_unpack_thread_info_response (char *pkt,
1435 threadref *expectedref,
1436 struct gdb_ext_thread_info
1440 static int remote_get_threadinfo (threadref *threadid,
1441 int fieldset, /*TAG mask */
1442 struct gdb_ext_thread_info *info);
1444 static char *pack_threadlist_request (char *pkt, int startflag,
1446 threadref *nextthread);
1448 static int parse_threadlist_response (char *pkt,
1450 threadref *original_echo,
1451 threadref *resultlist,
1454 static int remote_get_threadlist (int startflag,
1455 threadref *nextthread,
1459 threadref *threadlist);
1461 typedef int (*rmt_thread_action) (threadref *ref, void *context);
1463 static int remote_threadlist_iterator (rmt_thread_action stepfunction,
1464 void *context, int looplimit);
1466 static int remote_newthread_step (threadref *ref, void *context);
1469 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
1470 buffer we're allowed to write to. Returns
1471 BUF+CHARACTERS_WRITTEN. */
1474 write_ptid (char *buf, const char *endbuf, ptid_t ptid)
1477 struct remote_state *rs = get_remote_state ();
1479 if (remote_multi_process_p (rs))
1481 pid = ptid_get_pid (ptid);
1483 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
1485 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
1487 tid = ptid_get_tid (ptid);
1489 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
1491 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
1496 /* Extract a PTID from BUF. If non-null, OBUF is set to the to one
1497 passed the last parsed char. Returns null_ptid on error. */
1500 read_ptid (char *buf, char **obuf)
1504 ULONGEST pid = 0, tid = 0;
1509 /* Multi-process ptid. */
1510 pp = unpack_varlen_hex (p + 1, &pid);
1512 error (_("invalid remote ptid: %s\n"), p);
1515 pp = unpack_varlen_hex (p + 1, &tid);
1518 return ptid_build (pid, 0, tid);
1521 /* No multi-process. Just a tid. */
1522 pp = unpack_varlen_hex (p, &tid);
1524 /* Since the stub is not sending a process id, then default to
1525 what's in inferior_ptid. */
1526 pid = ptid_get_pid (inferior_ptid);
1530 return ptid_build (pid, 0, tid);
1533 /* Encode 64 bits in 16 chars of hex. */
1535 static const char hexchars[] = "0123456789abcdef";
1538 ishex (int ch, int *val)
1540 if ((ch >= 'a') && (ch <= 'f'))
1542 *val = ch - 'a' + 10;
1545 if ((ch >= 'A') && (ch <= 'F'))
1547 *val = ch - 'A' + 10;
1550 if ((ch >= '0') && (ch <= '9'))
1561 if (ch >= 'a' && ch <= 'f')
1562 return ch - 'a' + 10;
1563 if (ch >= '0' && ch <= '9')
1565 if (ch >= 'A' && ch <= 'F')
1566 return ch - 'A' + 10;
1571 stub_unpack_int (char *buff, int fieldlength)
1578 nibble = stubhex (*buff++);
1582 retval = retval << 4;
1588 unpack_varlen_hex (char *buff, /* packet to parse */
1592 ULONGEST retval = 0;
1594 while (ishex (*buff, &nibble))
1597 retval = retval << 4;
1598 retval |= nibble & 0x0f;
1605 unpack_nibble (char *buf, int *val)
1607 *val = fromhex (*buf++);
1612 pack_nibble (char *buf, int nibble)
1614 *buf++ = hexchars[(nibble & 0x0f)];
1619 pack_hex_byte (char *pkt, int byte)
1621 *pkt++ = hexchars[(byte >> 4) & 0xf];
1622 *pkt++ = hexchars[(byte & 0xf)];
1627 unpack_byte (char *buf, int *value)
1629 *value = stub_unpack_int (buf, 2);
1634 pack_int (char *buf, int value)
1636 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
1637 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
1638 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
1639 buf = pack_hex_byte (buf, (value & 0xff));
1644 unpack_int (char *buf, int *value)
1646 *value = stub_unpack_int (buf, 8);
1650 #if 0 /* Currently unused, uncomment when needed. */
1651 static char *pack_string (char *pkt, char *string);
1654 pack_string (char *pkt, char *string)
1659 len = strlen (string);
1661 len = 200; /* Bigger than most GDB packets, junk??? */
1662 pkt = pack_hex_byte (pkt, len);
1666 if ((ch == '\0') || (ch == '#'))
1667 ch = '*'; /* Protect encapsulation. */
1672 #endif /* 0 (unused) */
1675 unpack_string (char *src, char *dest, int length)
1684 pack_threadid (char *pkt, threadref *id)
1687 unsigned char *altid;
1689 altid = (unsigned char *) id;
1690 limit = pkt + BUF_THREAD_ID_SIZE;
1692 pkt = pack_hex_byte (pkt, *altid++);
1698 unpack_threadid (char *inbuf, threadref *id)
1701 char *limit = inbuf + BUF_THREAD_ID_SIZE;
1704 altref = (char *) id;
1706 while (inbuf < limit)
1708 x = stubhex (*inbuf++);
1709 y = stubhex (*inbuf++);
1710 *altref++ = (x << 4) | y;
1715 /* Externally, threadrefs are 64 bits but internally, they are still
1716 ints. This is due to a mismatch of specifications. We would like
1717 to use 64bit thread references internally. This is an adapter
1721 int_to_threadref (threadref *id, int value)
1723 unsigned char *scan;
1725 scan = (unsigned char *) id;
1731 *scan++ = (value >> 24) & 0xff;
1732 *scan++ = (value >> 16) & 0xff;
1733 *scan++ = (value >> 8) & 0xff;
1734 *scan++ = (value & 0xff);
1738 threadref_to_int (threadref *ref)
1741 unsigned char *scan;
1747 value = (value << 8) | ((*scan++) & 0xff);
1752 copy_threadref (threadref *dest, threadref *src)
1755 unsigned char *csrc, *cdest;
1757 csrc = (unsigned char *) src;
1758 cdest = (unsigned char *) dest;
1765 threadmatch (threadref *dest, threadref *src)
1767 /* Things are broken right now, so just assume we got a match. */
1769 unsigned char *srcp, *destp;
1771 srcp = (char *) src;
1772 destp = (char *) dest;
1776 result &= (*srcp++ == *destp++) ? 1 : 0;
1783 threadid:1, # always request threadid
1790 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
1793 pack_threadinfo_request (char *pkt, int mode, threadref *id)
1795 *pkt++ = 'q'; /* Info Query */
1796 *pkt++ = 'P'; /* process or thread info */
1797 pkt = pack_int (pkt, mode); /* mode */
1798 pkt = pack_threadid (pkt, id); /* threadid */
1799 *pkt = '\0'; /* terminate */
1803 /* These values tag the fields in a thread info response packet. */
1804 /* Tagging the fields allows us to request specific fields and to
1805 add more fields as time goes by. */
1807 #define TAG_THREADID 1 /* Echo the thread identifier. */
1808 #define TAG_EXISTS 2 /* Is this process defined enough to
1809 fetch registers and its stack? */
1810 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
1811 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
1812 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
1816 remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
1817 struct gdb_ext_thread_info *info)
1819 struct remote_state *rs = get_remote_state ();
1823 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
1826 /* info->threadid = 0; FIXME: implement zero_threadref. */
1828 info->display[0] = '\0';
1829 info->shortname[0] = '\0';
1830 info->more_display[0] = '\0';
1832 /* Assume the characters indicating the packet type have been
1834 pkt = unpack_int (pkt, &mask); /* arg mask */
1835 pkt = unpack_threadid (pkt, &ref);
1838 warning (_("Incomplete response to threadinfo request."));
1839 if (!threadmatch (&ref, expectedref))
1840 { /* This is an answer to a different request. */
1841 warning (_("ERROR RMT Thread info mismatch."));
1844 copy_threadref (&info->threadid, &ref);
1846 /* Loop on tagged fields , try to bail if somthing goes wrong. */
1848 /* Packets are terminated with nulls. */
1849 while ((pkt < limit) && mask && *pkt)
1851 pkt = unpack_int (pkt, &tag); /* tag */
1852 pkt = unpack_byte (pkt, &length); /* length */
1853 if (!(tag & mask)) /* Tags out of synch with mask. */
1855 warning (_("ERROR RMT: threadinfo tag mismatch."));
1859 if (tag == TAG_THREADID)
1863 warning (_("ERROR RMT: length of threadid is not 16."));
1867 pkt = unpack_threadid (pkt, &ref);
1868 mask = mask & ~TAG_THREADID;
1871 if (tag == TAG_EXISTS)
1873 info->active = stub_unpack_int (pkt, length);
1875 mask = mask & ~(TAG_EXISTS);
1878 warning (_("ERROR RMT: 'exists' length too long."));
1884 if (tag == TAG_THREADNAME)
1886 pkt = unpack_string (pkt, &info->shortname[0], length);
1887 mask = mask & ~TAG_THREADNAME;
1890 if (tag == TAG_DISPLAY)
1892 pkt = unpack_string (pkt, &info->display[0], length);
1893 mask = mask & ~TAG_DISPLAY;
1896 if (tag == TAG_MOREDISPLAY)
1898 pkt = unpack_string (pkt, &info->more_display[0], length);
1899 mask = mask & ~TAG_MOREDISPLAY;
1902 warning (_("ERROR RMT: unknown thread info tag."));
1903 break; /* Not a tag we know about. */
1909 remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
1910 struct gdb_ext_thread_info *info)
1912 struct remote_state *rs = get_remote_state ();
1915 pack_threadinfo_request (rs->buf, fieldset, threadid);
1917 getpkt (&rs->buf, &rs->buf_size, 0);
1919 if (rs->buf[0] == '\0')
1922 result = remote_unpack_thread_info_response (rs->buf + 2,
1927 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
1930 pack_threadlist_request (char *pkt, int startflag, int threadcount,
1931 threadref *nextthread)
1933 *pkt++ = 'q'; /* info query packet */
1934 *pkt++ = 'L'; /* Process LIST or threadLIST request */
1935 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
1936 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
1937 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
1942 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
1945 parse_threadlist_response (char *pkt, int result_limit,
1946 threadref *original_echo, threadref *resultlist,
1949 struct remote_state *rs = get_remote_state ();
1951 int count, resultcount, done;
1954 /* Assume the 'q' and 'M chars have been stripped. */
1955 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
1956 /* done parse past here */
1957 pkt = unpack_byte (pkt, &count); /* count field */
1958 pkt = unpack_nibble (pkt, &done);
1959 /* The first threadid is the argument threadid. */
1960 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
1961 while ((count-- > 0) && (pkt < limit))
1963 pkt = unpack_threadid (pkt, resultlist++);
1964 if (resultcount++ >= result_limit)
1973 remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
1974 int *done, int *result_count, threadref *threadlist)
1976 struct remote_state *rs = get_remote_state ();
1977 static threadref echo_nextthread;
1980 /* Trancate result limit to be smaller than the packet size. */
1981 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10) >= get_remote_packet_size ())
1982 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
1984 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
1986 getpkt (&rs->buf, &rs->buf_size, 0);
1988 if (*rs->buf == '\0')
1992 parse_threadlist_response (rs->buf + 2, result_limit, &echo_nextthread,
1995 if (!threadmatch (&echo_nextthread, nextthread))
1997 /* FIXME: This is a good reason to drop the packet. */
1998 /* Possably, there is a duplicate response. */
2000 retransmit immediatly - race conditions
2001 retransmit after timeout - yes
2003 wait for packet, then exit
2005 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
2006 return 0; /* I choose simply exiting. */
2008 if (*result_count <= 0)
2012 warning (_("RMT ERROR : failed to get remote thread list."));
2015 return result; /* break; */
2017 if (*result_count > result_limit)
2020 warning (_("RMT ERROR: threadlist response longer than requested."));
2026 /* This is the interface between remote and threads, remotes upper
2029 /* remote_find_new_threads retrieves the thread list and for each
2030 thread in the list, looks up the thread in GDB's internal list,
2031 adding the thread if it does not already exist. This involves
2032 getting partial thread lists from the remote target so, polling the
2033 quit_flag is required. */
2036 /* About this many threadisds fit in a packet. */
2038 #define MAXTHREADLISTRESULTS 32
2041 remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2044 int done, i, result_count;
2048 static threadref nextthread;
2049 static threadref resultthreadlist[MAXTHREADLISTRESULTS];
2054 if (loopcount++ > looplimit)
2057 warning (_("Remote fetch threadlist -infinite loop-."));
2060 if (!remote_get_threadlist (startflag, &nextthread, MAXTHREADLISTRESULTS,
2061 &done, &result_count, resultthreadlist))
2066 /* Clear for later iterations. */
2068 /* Setup to resume next batch of thread references, set nextthread. */
2069 if (result_count >= 1)
2070 copy_threadref (&nextthread, &resultthreadlist[result_count - 1]);
2072 while (result_count--)
2073 if (!(result = (*stepfunction) (&resultthreadlist[i++], context)))
2080 remote_newthread_step (threadref *ref, void *context)
2082 int pid = ptid_get_pid (inferior_ptid);
2083 ptid_t ptid = ptid_build (pid, 0, threadref_to_int (ref));
2085 if (!in_thread_list (ptid))
2087 return 1; /* continue iterator */
2090 #define CRAZY_MAX_THREADS 1000
2093 remote_current_thread (ptid_t oldpid)
2095 struct remote_state *rs = get_remote_state ();
2101 getpkt (&rs->buf, &rs->buf_size, 0);
2102 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
2103 return read_ptid (&rs->buf[2], NULL);
2108 /* Find new threads for info threads command.
2109 * Original version, using John Metzler's thread protocol.
2113 remote_find_new_threads (void)
2115 remote_threadlist_iterator (remote_newthread_step, 0,
2120 * Find all threads for info threads command.
2121 * Uses new thread protocol contributed by Cisco.
2122 * Falls back and attempts to use the older method (above)
2123 * if the target doesn't respond to the new method.
2127 remote_threads_info (void)
2129 struct remote_state *rs = get_remote_state ();
2133 if (remote_desc == 0) /* paranoia */
2134 error (_("Command can only be used when connected to the remote target."));
2136 if (use_threadinfo_query)
2138 putpkt ("qfThreadInfo");
2139 getpkt (&rs->buf, &rs->buf_size, 0);
2141 if (bufp[0] != '\0') /* q packet recognized */
2143 while (*bufp++ == 'm') /* reply contains one or more TID */
2147 new_thread = read_ptid (bufp, &bufp);
2148 if (!ptid_equal (new_thread, null_ptid)
2149 && (!in_thread_list (new_thread)
2150 || is_exited (new_thread)))
2152 /* When connected to a multi-process aware stub,
2153 "info threads" may show up threads of
2154 inferiors we didn't know about yet. Add them
2155 now, and before adding any of its child
2156 threads, so notifications are emitted in a
2158 if (!in_inferior_list (ptid_get_pid (new_thread)))
2159 add_inferior (ptid_get_pid (new_thread));
2161 add_thread (new_thread);
2163 /* In non-stop mode, we assume new found threads
2164 are running until we proven otherwise with a
2165 stop reply. In all-stop, we can only get
2166 here if all threads are stopped. */
2167 set_executing (new_thread, non_stop ? 1 : 0);
2168 set_running (new_thread, non_stop ? 1 : 0);
2171 while (*bufp++ == ','); /* comma-separated list */
2172 putpkt ("qsThreadInfo");
2173 getpkt (&rs->buf, &rs->buf_size, 0);
2180 /* Only qfThreadInfo is supported in non-stop mode. */
2184 /* Else fall back to old method based on jmetzler protocol. */
2185 use_threadinfo_query = 0;
2186 remote_find_new_threads ();
2191 * Collect a descriptive string about the given thread.
2192 * The target may say anything it wants to about the thread
2193 * (typically info about its blocked / runnable state, name, etc.).
2194 * This string will appear in the info threads display.
2196 * Optional: targets are not required to implement this function.
2200 remote_threads_extra_info (struct thread_info *tp)
2202 struct remote_state *rs = get_remote_state ();
2206 struct gdb_ext_thread_info threadinfo;
2207 static char display_buf[100]; /* arbitrary... */
2208 int n = 0; /* position in display_buf */
2210 if (remote_desc == 0) /* paranoia */
2211 internal_error (__FILE__, __LINE__,
2212 _("remote_threads_extra_info"));
2214 if (ptid_equal (tp->ptid, magic_null_ptid)
2215 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_tid (tp->ptid) == 0))
2216 /* This is the main thread which was added by GDB. The remote
2217 server doesn't know about it. */
2220 if (use_threadextra_query)
2223 char *endb = rs->buf + get_remote_packet_size ();
2225 xsnprintf (b, endb - b, "qThreadExtraInfo,");
2227 write_ptid (b, endb, tp->ptid);
2230 getpkt (&rs->buf, &rs->buf_size, 0);
2231 if (rs->buf[0] != 0)
2233 n = min (strlen (rs->buf) / 2, sizeof (display_buf));
2234 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
2235 display_buf [result] = '\0';
2240 /* If the above query fails, fall back to the old method. */
2241 use_threadextra_query = 0;
2242 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
2243 | TAG_MOREDISPLAY | TAG_DISPLAY;
2244 int_to_threadref (&id, ptid_get_tid (tp->ptid));
2245 if (remote_get_threadinfo (&id, set, &threadinfo))
2246 if (threadinfo.active)
2248 if (*threadinfo.shortname)
2249 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
2250 " Name: %s,", threadinfo.shortname);
2251 if (*threadinfo.display)
2252 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
2253 " State: %s,", threadinfo.display);
2254 if (*threadinfo.more_display)
2255 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
2256 " Priority: %s", threadinfo.more_display);
2260 /* For purely cosmetic reasons, clear up trailing commas. */
2261 if (',' == display_buf[n-1])
2262 display_buf[n-1] = ' ';
2270 /* Restart the remote side; this is an extended protocol operation. */
2273 extended_remote_restart (void)
2275 struct remote_state *rs = get_remote_state ();
2277 /* Send the restart command; for reasons I don't understand the
2278 remote side really expects a number after the "R". */
2279 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
2282 remote_fileio_reset ();
2285 /* Clean up connection to a remote debugger. */
2288 remote_close (int quitting)
2292 /* Unregister the file descriptor from the event loop. */
2293 if (target_is_async_p ())
2294 target_async (NULL, 0);
2295 serial_close (remote_desc);
2299 /* Make sure we don't leave the async SIGINT signal handler
2301 signal (SIGINT, handle_sigint);
2303 /* We don't have a connection to the remote stub anymore. Get rid
2304 of all the inferiors and their threads we were controlling. */
2305 discard_all_inferiors ();
2307 /* We're no longer interested in any of these events. */
2308 discard_pending_stop_replies (-1);
2310 if (remote_async_inferior_event_token)
2311 delete_async_event_handler (&remote_async_inferior_event_token);
2312 if (remote_async_get_pending_events_token)
2313 delete_async_event_handler (&remote_async_get_pending_events_token);
2315 generic_mourn_inferior ();
2318 /* Query the remote side for the text, data and bss offsets. */
2323 struct remote_state *rs = get_remote_state ();
2326 int lose, num_segments = 0, do_sections, do_segments;
2327 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
2328 struct section_offsets *offs;
2329 struct symfile_segment_data *data;
2331 if (symfile_objfile == NULL)
2334 putpkt ("qOffsets");
2335 getpkt (&rs->buf, &rs->buf_size, 0);
2338 if (buf[0] == '\000')
2339 return; /* Return silently. Stub doesn't support
2343 warning (_("Remote failure reply: %s"), buf);
2347 /* Pick up each field in turn. This used to be done with scanf, but
2348 scanf will make trouble if CORE_ADDR size doesn't match
2349 conversion directives correctly. The following code will work
2350 with any size of CORE_ADDR. */
2351 text_addr = data_addr = bss_addr = 0;
2355 if (strncmp (ptr, "Text=", 5) == 0)
2358 /* Don't use strtol, could lose on big values. */
2359 while (*ptr && *ptr != ';')
2360 text_addr = (text_addr << 4) + fromhex (*ptr++);
2362 if (strncmp (ptr, ";Data=", 6) == 0)
2365 while (*ptr && *ptr != ';')
2366 data_addr = (data_addr << 4) + fromhex (*ptr++);
2371 if (!lose && strncmp (ptr, ";Bss=", 5) == 0)
2374 while (*ptr && *ptr != ';')
2375 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
2377 if (bss_addr != data_addr)
2378 warning (_("Target reported unsupported offsets: %s"), buf);
2383 else if (strncmp (ptr, "TextSeg=", 8) == 0)
2386 /* Don't use strtol, could lose on big values. */
2387 while (*ptr && *ptr != ';')
2388 text_addr = (text_addr << 4) + fromhex (*ptr++);
2391 if (strncmp (ptr, ";DataSeg=", 9) == 0)
2394 while (*ptr && *ptr != ';')
2395 data_addr = (data_addr << 4) + fromhex (*ptr++);
2403 error (_("Malformed response to offset query, %s"), buf);
2404 else if (*ptr != '\0')
2405 warning (_("Target reported unsupported offsets: %s"), buf);
2407 offs = ((struct section_offsets *)
2408 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
2409 memcpy (offs, symfile_objfile->section_offsets,
2410 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
2412 data = get_symfile_segment_data (symfile_objfile->obfd);
2413 do_segments = (data != NULL);
2414 do_sections = num_segments == 0;
2416 if (num_segments > 0)
2418 segments[0] = text_addr;
2419 segments[1] = data_addr;
2421 /* If we have two segments, we can still try to relocate everything
2422 by assuming that the .text and .data offsets apply to the whole
2423 text and data segments. Convert the offsets given in the packet
2424 to base addresses for symfile_map_offsets_to_segments. */
2425 else if (data && data->num_segments == 2)
2427 segments[0] = data->segment_bases[0] + text_addr;
2428 segments[1] = data->segment_bases[1] + data_addr;
2431 /* If the object file has only one segment, assume that it is text
2432 rather than data; main programs with no writable data are rare,
2433 but programs with no code are useless. Of course the code might
2434 have ended up in the data segment... to detect that we would need
2435 the permissions here. */
2436 else if (data && data->num_segments == 1)
2438 segments[0] = data->segment_bases[0] + text_addr;
2441 /* There's no way to relocate by segment. */
2447 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
2448 offs, num_segments, segments);
2450 if (ret == 0 && !do_sections)
2451 error (_("Can not handle qOffsets TextSeg response with this symbol file"));
2458 free_symfile_segment_data (data);
2462 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
2464 /* This is a temporary kludge to force data and bss to use the same offsets
2465 because that's what nlmconv does now. The real solution requires changes
2466 to the stub and remote.c that I don't have time to do right now. */
2468 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
2469 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
2472 objfile_relocate (symfile_objfile, offs);
2475 /* Callback for iterate_over_threads. Set the STOP_REQUESTED flags in
2476 threads we know are stopped already. This is used during the
2477 initial remote connection in non-stop mode --- threads that are
2478 reported as already being stopped are left stopped. */
2481 set_stop_requested_callback (struct thread_info *thread, void *data)
2483 /* If we have a stop reply for this thread, it must be stopped. */
2484 if (peek_stop_reply (thread->ptid))
2485 set_stop_requested (thread->ptid, 1);
2490 /* Stub for catch_exception. */
2492 struct start_remote_args
2496 /* The current target. */
2497 struct target_ops *target;
2499 /* Non-zero if this is an extended-remote target. */
2504 remote_start_remote (struct ui_out *uiout, void *opaque)
2506 struct start_remote_args *args = opaque;
2507 struct remote_state *rs = get_remote_state ();
2508 struct packet_config *noack_config;
2509 char *wait_status = NULL;
2511 immediate_quit++; /* Allow user to interrupt it. */
2513 /* Ack any packet which the remote side has already sent. */
2514 serial_write (remote_desc, "+", 1);
2516 /* The first packet we send to the target is the optional "supported
2517 packets" request. If the target can answer this, it will tell us
2518 which later probes to skip. */
2519 remote_query_supported ();
2521 /* Next, we possibly activate noack mode.
2523 If the QStartNoAckMode packet configuration is set to AUTO,
2524 enable noack mode if the stub reported a wish for it with
2527 If set to TRUE, then enable noack mode even if the stub didn't
2528 report it in qSupported. If the stub doesn't reply OK, the
2529 session ends with an error.
2531 If FALSE, then don't activate noack mode, regardless of what the
2532 stub claimed should be the default with qSupported. */
2534 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
2536 if (noack_config->detect == AUTO_BOOLEAN_TRUE
2537 || (noack_config->detect == AUTO_BOOLEAN_AUTO
2538 && noack_config->support == PACKET_ENABLE))
2540 putpkt ("QStartNoAckMode");
2541 getpkt (&rs->buf, &rs->buf_size, 0);
2542 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
2546 if (args->extended_p)
2548 /* Tell the remote that we are using the extended protocol. */
2550 getpkt (&rs->buf, &rs->buf_size, 0);
2553 /* Next, if the target can specify a description, read it. We do
2554 this before anything involving memory or registers. */
2555 target_find_description ();
2559 if (!rs->non_stop_aware)
2560 error (_("Non-stop mode requested, but remote does not support non-stop"));
2562 putpkt ("QNonStop:1");
2563 getpkt (&rs->buf, &rs->buf_size, 0);
2565 if (strcmp (rs->buf, "OK") != 0)
2566 error ("Remote refused setting non-stop mode with: %s", rs->buf);
2568 /* Find about threads and processes the stub is already
2569 controlling. We default to adding them in the running state.
2570 The '?' query below will then tell us about which threads are
2573 /* If we're not using the multi-process extensions, there's no
2574 way to know the pid of the reported threads; use the magic
2576 if (!remote_multi_process_p (rs))
2577 inferior_ptid = magic_null_ptid;
2579 remote_threads_info ();
2581 else if (rs->non_stop_aware)
2583 /* Don't assume that the stub can operate in all-stop mode.
2584 Request it explicitely. */
2585 putpkt ("QNonStop:0");
2586 getpkt (&rs->buf, &rs->buf_size, 0);
2588 if (strcmp (rs->buf, "OK") != 0)
2589 error ("Remote refused setting all-stop mode with: %s", rs->buf);
2592 /* Check whether the target is running now. */
2594 getpkt (&rs->buf, &rs->buf_size, 0);
2598 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
2600 if (args->extended_p)
2602 /* We're connected, but not running. Drop out before we
2603 call start_remote. */
2604 target_mark_exited (args->target);
2608 error (_("The target is not running (try extended-remote?)"));
2612 if (args->extended_p)
2613 target_mark_running (args->target);
2615 /* Save the reply for later. */
2616 wait_status = alloca (strlen (rs->buf) + 1);
2617 strcpy (wait_status, rs->buf);
2620 /* Let the stub know that we want it to return the thread. */
2621 set_continue_thread (minus_one_ptid);
2623 /* Without this, some commands which require an active target
2624 (such as kill) won't work. This variable serves (at least)
2625 double duty as both the pid of the target process (if it has
2626 such), and as a flag indicating that a target is active.
2627 These functions should be split out into seperate variables,
2628 especially since GDB will someday have a notion of debugging
2629 several processes. */
2630 inferior_ptid = magic_null_ptid;
2632 /* Now, if we have thread information, update inferior_ptid. */
2633 inferior_ptid = remote_current_thread (inferior_ptid);
2635 add_inferior (ptid_get_pid (inferior_ptid));
2637 /* Always add the main thread. */
2638 add_thread_silent (inferior_ptid);
2640 get_offsets (); /* Get text, data & bss offsets. */
2642 /* Use the previously fetched status. */
2643 gdb_assert (wait_status != NULL);
2644 strcpy (rs->buf, wait_status);
2645 rs->cached_wait_status = 1;
2648 start_remote (args->from_tty); /* Initialize gdb process mechanisms. */
2652 /* In non-stop, we will either get an "OK", meaning that there
2653 are no stopped threads at this time; or, a regular stop
2654 reply. In the latter case, there may be more than one thread
2655 stopped --- we pull them all out using the vStopped
2657 if (strcmp (rs->buf, "OK") != 0)
2659 struct stop_reply *stop_reply;
2660 struct cleanup *old_chain;
2662 stop_reply = stop_reply_xmalloc ();
2663 old_chain = make_cleanup (do_stop_reply_xfree, stop_reply);
2665 remote_parse_stop_reply (rs->buf, stop_reply);
2666 discard_cleanups (old_chain);
2668 /* get_pending_stop_replies acks this one, and gets the rest
2670 pending_stop_reply = stop_reply;
2671 remote_get_pending_stop_replies ();
2673 /* Make sure that threads that were stopped remain
2675 iterate_over_threads (set_stop_requested_callback, NULL);
2678 if (target_can_async_p ())
2679 target_async (inferior_event_handler, 0);
2681 if (thread_count () == 0)
2683 if (args->extended_p)
2685 /* We're connected, but not running. Drop out before we
2686 call start_remote. */
2687 target_mark_exited (args->target);
2691 error (_("The target is not running (try extended-remote?)"));
2694 if (args->extended_p)
2695 target_mark_running (args->target);
2697 /* Let the stub know that we want it to return the thread. */
2699 /* Force the stub to choose a thread. */
2700 set_general_thread (null_ptid);
2703 inferior_ptid = remote_current_thread (minus_one_ptid);
2704 if (ptid_equal (inferior_ptid, minus_one_ptid))
2705 error (_("remote didn't report the current thread in non-stop mode"));
2707 get_offsets (); /* Get text, data & bss offsets. */
2709 /* In non-stop mode, any cached wait status will be stored in
2710 the stop reply queue. */
2711 gdb_assert (wait_status == NULL);
2714 /* If we connected to a live target, do some additional setup. */
2715 if (target_has_execution)
2717 if (exec_bfd) /* No use without an exec file. */
2718 remote_check_symbols (symfile_objfile);
2722 /* Open a connection to a remote debugger.
2723 NAME is the filename used for communication. */
2726 remote_open (char *name, int from_tty)
2728 remote_open_1 (name, from_tty, &remote_ops, 0);
2731 /* Open a connection to a remote debugger using the extended
2732 remote gdb protocol. NAME is the filename used for communication. */
2735 extended_remote_open (char *name, int from_tty)
2737 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
2740 /* Generic code for opening a connection to a remote target. */
2743 init_all_packet_configs (void)
2746 for (i = 0; i < PACKET_MAX; i++)
2747 update_packet_config (&remote_protocol_packets[i]);
2750 /* Symbol look-up. */
2753 remote_check_symbols (struct objfile *objfile)
2755 struct remote_state *rs = get_remote_state ();
2756 char *msg, *reply, *tmp;
2757 struct minimal_symbol *sym;
2760 if (remote_protocol_packets[PACKET_qSymbol].support == PACKET_DISABLE)
2763 /* Make sure the remote is pointing at the right process. */
2764 set_general_process ();
2766 /* Allocate a message buffer. We can't reuse the input buffer in RS,
2767 because we need both at the same time. */
2768 msg = alloca (get_remote_packet_size ());
2770 /* Invite target to request symbol lookups. */
2772 putpkt ("qSymbol::");
2773 getpkt (&rs->buf, &rs->buf_size, 0);
2774 packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSymbol]);
2777 while (strncmp (reply, "qSymbol:", 8) == 0)
2780 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
2782 sym = lookup_minimal_symbol (msg, NULL, NULL);
2784 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
2787 CORE_ADDR sym_addr = SYMBOL_VALUE_ADDRESS (sym);
2789 /* If this is a function address, return the start of code
2790 instead of any data function descriptor. */
2791 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch,
2795 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
2796 paddr_nz (sym_addr), &reply[8]);
2800 getpkt (&rs->buf, &rs->buf_size, 0);
2805 static struct serial *
2806 remote_serial_open (char *name)
2808 static int udp_warning = 0;
2810 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
2811 of in ser-tcp.c, because it is the remote protocol assuming that the
2812 serial connection is reliable and not the serial connection promising
2814 if (!udp_warning && strncmp (name, "udp:", 4) == 0)
2817 The remote protocol may be unreliable over UDP.\n\
2818 Some events may be lost, rendering further debugging impossible."));
2822 return serial_open (name);
2825 /* This type describes each known response to the qSupported
2827 struct protocol_feature
2829 /* The name of this protocol feature. */
2832 /* The default for this protocol feature. */
2833 enum packet_support default_support;
2835 /* The function to call when this feature is reported, or after
2836 qSupported processing if the feature is not supported.
2837 The first argument points to this structure. The second
2838 argument indicates whether the packet requested support be
2839 enabled, disabled, or probed (or the default, if this function
2840 is being called at the end of processing and this feature was
2841 not reported). The third argument may be NULL; if not NULL, it
2842 is a NUL-terminated string taken from the packet following
2843 this feature's name and an equals sign. */
2844 void (*func) (const struct protocol_feature *, enum packet_support,
2847 /* The corresponding packet for this feature. Only used if
2848 FUNC is remote_supported_packet. */
2853 remote_supported_packet (const struct protocol_feature *feature,
2854 enum packet_support support,
2855 const char *argument)
2859 warning (_("Remote qSupported response supplied an unexpected value for"
2860 " \"%s\"."), feature->name);
2864 if (remote_protocol_packets[feature->packet].support
2865 == PACKET_SUPPORT_UNKNOWN)
2866 remote_protocol_packets[feature->packet].support = support;
2870 remote_packet_size (const struct protocol_feature *feature,
2871 enum packet_support support, const char *value)
2873 struct remote_state *rs = get_remote_state ();
2878 if (support != PACKET_ENABLE)
2881 if (value == NULL || *value == '\0')
2883 warning (_("Remote target reported \"%s\" without a size."),
2889 packet_size = strtol (value, &value_end, 16);
2890 if (errno != 0 || *value_end != '\0' || packet_size < 0)
2892 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
2893 feature->name, value);
2897 if (packet_size > MAX_REMOTE_PACKET_SIZE)
2899 warning (_("limiting remote suggested packet size (%d bytes) to %d"),
2900 packet_size, MAX_REMOTE_PACKET_SIZE);
2901 packet_size = MAX_REMOTE_PACKET_SIZE;
2904 /* Record the new maximum packet size. */
2905 rs->explicit_packet_size = packet_size;
2909 remote_multi_process_feature (const struct protocol_feature *feature,
2910 enum packet_support support, const char *value)
2912 struct remote_state *rs = get_remote_state ();
2913 rs->multi_process_aware = (support == PACKET_ENABLE);
2917 remote_non_stop_feature (const struct protocol_feature *feature,
2918 enum packet_support support, const char *value)
2920 struct remote_state *rs = get_remote_state ();
2921 rs->non_stop_aware = (support == PACKET_ENABLE);
2924 static struct protocol_feature remote_protocol_features[] = {
2925 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
2926 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
2927 PACKET_qXfer_auxv },
2928 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
2929 PACKET_qXfer_features },
2930 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
2931 PACKET_qXfer_libraries },
2932 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
2933 PACKET_qXfer_memory_map },
2934 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
2935 PACKET_qXfer_spu_read },
2936 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
2937 PACKET_qXfer_spu_write },
2938 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
2939 PACKET_QPassSignals },
2940 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
2941 PACKET_QStartNoAckMode },
2942 { "multiprocess", PACKET_DISABLE, remote_multi_process_feature, -1 },
2943 { "QNonStop", PACKET_DISABLE, remote_non_stop_feature, -1 },
2947 remote_query_supported (void)
2949 struct remote_state *rs = get_remote_state ();
2952 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
2954 /* The packet support flags are handled differently for this packet
2955 than for most others. We treat an error, a disabled packet, and
2956 an empty response identically: any features which must be reported
2957 to be used will be automatically disabled. An empty buffer
2958 accomplishes this, since that is also the representation for a list
2959 containing no features. */
2962 if (remote_protocol_packets[PACKET_qSupported].support != PACKET_DISABLE)
2965 putpkt ("qSupported:multiprocess+");
2967 putpkt ("qSupported");
2969 getpkt (&rs->buf, &rs->buf_size, 0);
2971 /* If an error occured, warn, but do not return - just reset the
2972 buffer to empty and go on to disable features. */
2973 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
2976 warning (_("Remote failure reply: %s"), rs->buf);
2981 memset (seen, 0, sizeof (seen));
2986 enum packet_support is_supported;
2987 char *p, *end, *name_end, *value;
2989 /* First separate out this item from the rest of the packet. If
2990 there's another item after this, we overwrite the separator
2991 (terminated strings are much easier to work with). */
2993 end = strchr (p, ';');
2996 end = p + strlen (p);
3006 warning (_("empty item in \"qSupported\" response"));
3011 name_end = strchr (p, '=');
3014 /* This is a name=value entry. */
3015 is_supported = PACKET_ENABLE;
3016 value = name_end + 1;
3025 is_supported = PACKET_ENABLE;
3029 is_supported = PACKET_DISABLE;
3033 is_supported = PACKET_SUPPORT_UNKNOWN;
3037 warning (_("unrecognized item \"%s\" in \"qSupported\" response"), p);
3043 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
3044 if (strcmp (remote_protocol_features[i].name, p) == 0)
3046 const struct protocol_feature *feature;
3049 feature = &remote_protocol_features[i];
3050 feature->func (feature, is_supported, value);
3055 /* If we increased the packet size, make sure to increase the global
3056 buffer size also. We delay this until after parsing the entire
3057 qSupported packet, because this is the same buffer we were
3059 if (rs->buf_size < rs->explicit_packet_size)
3061 rs->buf_size = rs->explicit_packet_size;
3062 rs->buf = xrealloc (rs->buf, rs->buf_size);
3065 /* Handle the defaults for unmentioned features. */
3066 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
3069 const struct protocol_feature *feature;
3071 feature = &remote_protocol_features[i];
3072 feature->func (feature, feature->default_support, NULL);
3078 remote_open_1 (char *name, int from_tty, struct target_ops *target, int extended_p)
3080 struct remote_state *rs = get_remote_state ();
3083 error (_("To open a remote debug connection, you need to specify what\n"
3084 "serial device is attached to the remote system\n"
3085 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
3087 /* See FIXME above. */
3088 if (!target_async_permitted)
3089 wait_forever_enabled_p = 1;
3091 /* If we're connected to a running target, target_preopen will kill it.
3092 But if we're connected to a target system with no running process,
3093 then we will still be connected when it returns. Ask this question
3094 first, before target_preopen has a chance to kill anything. */
3095 if (remote_desc != NULL && !target_has_execution)
3098 || query (_("Already connected to a remote target. Disconnect? ")))
3101 error (_("Still connected."));
3104 target_preopen (from_tty);
3106 unpush_target (target);
3108 /* This time without a query. If we were connected to an
3109 extended-remote target and target_preopen killed the running
3110 process, we may still be connected. If we are starting "target
3111 remote" now, the extended-remote target will not have been
3112 removed by unpush_target. */
3113 if (remote_desc != NULL && !target_has_execution)
3116 /* Make sure we send the passed signals list the next time we resume. */
3117 xfree (last_pass_packet);
3118 last_pass_packet = NULL;
3120 remote_fileio_reset ();
3121 reopen_exec_file ();
3124 remote_desc = remote_serial_open (name);
3126 perror_with_name (name);
3128 if (baud_rate != -1)
3130 if (serial_setbaudrate (remote_desc, baud_rate))
3132 /* The requested speed could not be set. Error out to
3133 top level after closing remote_desc. Take care to
3134 set remote_desc to NULL to avoid closing remote_desc
3136 serial_close (remote_desc);
3138 perror_with_name (name);
3142 serial_raw (remote_desc);
3144 /* If there is something sitting in the buffer we might take it as a
3145 response to a command, which would be bad. */
3146 serial_flush_input (remote_desc);
3150 puts_filtered ("Remote debugging using ");
3151 puts_filtered (name);
3152 puts_filtered ("\n");
3154 push_target (target); /* Switch to using remote target now. */
3156 /* Assume that the target is running, unless we learn otherwise. */
3157 target_mark_running (target);
3159 /* Register extra event sources in the event loop. */
3160 remote_async_inferior_event_token
3161 = create_async_event_handler (remote_async_inferior_event_handler,
3163 remote_async_get_pending_events_token
3164 = create_async_event_handler (remote_async_get_pending_events_handler,
3167 /* Reset the target state; these things will be queried either by
3168 remote_query_supported or as they are needed. */
3169 init_all_packet_configs ();
3170 rs->cached_wait_status = 0;
3171 rs->explicit_packet_size = 0;
3173 rs->multi_process_aware = 0;
3174 rs->extended = extended_p;
3175 rs->non_stop_aware = 0;
3176 rs->waiting_for_stop_reply = 0;
3178 general_thread = not_sent_ptid;
3179 continue_thread = not_sent_ptid;
3181 /* Probe for ability to use "ThreadInfo" query, as required. */
3182 use_threadinfo_query = 1;
3183 use_threadextra_query = 1;
3185 if (target_async_permitted)
3187 /* With this target we start out by owning the terminal. */
3188 remote_async_terminal_ours_p = 1;
3190 /* FIXME: cagney/1999-09-23: During the initial connection it is
3191 assumed that the target is already ready and able to respond to
3192 requests. Unfortunately remote_start_remote() eventually calls
3193 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
3194 around this. Eventually a mechanism that allows
3195 wait_for_inferior() to expect/get timeouts will be
3197 wait_forever_enabled_p = 0;
3200 /* First delete any symbols previously loaded from shared libraries. */
3201 no_shared_libraries (NULL, 0);
3204 init_thread_list ();
3206 /* Start the remote connection. If error() or QUIT, discard this
3207 target (we'd otherwise be in an inconsistent state) and then
3208 propogate the error on up the exception chain. This ensures that
3209 the caller doesn't stumble along blindly assuming that the
3210 function succeeded. The CLI doesn't have this problem but other
3211 UI's, such as MI do.
3213 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
3214 this function should return an error indication letting the
3215 caller restore the previous state. Unfortunately the command
3216 ``target remote'' is directly wired to this function making that
3217 impossible. On a positive note, the CLI side of this problem has
3218 been fixed - the function set_cmd_context() makes it possible for
3219 all the ``target ....'' commands to share a common callback
3220 function. See cli-dump.c. */
3222 struct gdb_exception ex;
3223 struct start_remote_args args;
3225 args.from_tty = from_tty;
3226 args.target = target;
3227 args.extended_p = extended_p;
3229 ex = catch_exception (uiout, remote_start_remote, &args, RETURN_MASK_ALL);
3232 /* Pop the partially set up target - unless something else did
3233 already before throwing the exception. */
3234 if (remote_desc != NULL)
3236 if (target_async_permitted)
3237 wait_forever_enabled_p = 1;
3238 throw_exception (ex);
3242 if (target_async_permitted)
3243 wait_forever_enabled_p = 1;
3246 /* This takes a program previously attached to and detaches it. After
3247 this is done, GDB can be used to debug some other program. We
3248 better not have left any breakpoints in the target program or it'll
3249 die when it hits one. */
3252 remote_detach_1 (char *args, int from_tty, int extended)
3254 int pid = ptid_get_pid (inferior_ptid);
3255 struct remote_state *rs = get_remote_state ();
3258 error (_("Argument given to \"detach\" when remotely debugging."));
3260 if (!target_has_execution)
3261 error (_("No process to detach from."));
3263 /* Tell the remote target to detach. */
3264 if (remote_multi_process_p (rs))
3265 sprintf (rs->buf, "D;%x", pid);
3267 strcpy (rs->buf, "D");
3270 getpkt (&rs->buf, &rs->buf_size, 0);
3272 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
3274 else if (rs->buf[0] == '\0')
3275 error (_("Remote doesn't know how to detach"));
3277 error (_("Can't detach process."));
3281 if (remote_multi_process_p (rs))
3282 printf_filtered (_("Detached from remote %s.\n"),
3283 target_pid_to_str (pid_to_ptid (pid)));
3287 puts_filtered (_("Detached from remote process.\n"));
3289 puts_filtered (_("Ending remote debugging.\n"));
3293 discard_pending_stop_replies (pid);
3294 detach_inferior (pid);
3295 target_mourn_inferior ();
3299 remote_detach (char *args, int from_tty)
3301 remote_detach_1 (args, from_tty, 0);
3305 extended_remote_detach (char *args, int from_tty)
3307 remote_detach_1 (args, from_tty, 1);
3310 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
3313 remote_disconnect (struct target_ops *target, char *args, int from_tty)
3316 error (_("Argument given to \"disconnect\" when remotely debugging."));
3318 /* Make sure we unpush even the extended remote targets; mourn
3319 won't do it. So call remote_mourn_1 directly instead of
3320 target_mourn_inferior. */
3321 remote_mourn_1 (target);
3324 puts_filtered ("Ending remote debugging.\n");
3327 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
3328 be chatty about it. */
3331 extended_remote_attach_1 (struct target_ops *target, char *args, int from_tty)
3333 struct remote_state *rs = get_remote_state ();
3336 char *wait_status = NULL;
3337 struct inferior *inf;
3340 error_no_arg (_("process-id to attach"));
3343 pid = strtol (args, &dummy, 0);
3344 /* Some targets don't set errno on errors, grrr! */
3345 if (pid == 0 && args == dummy)
3346 error (_("Illegal process-id: %s."), args);
3348 if (remote_protocol_packets[PACKET_vAttach].support == PACKET_DISABLE)
3349 error (_("This target does not support attaching to a process"));
3351 sprintf (rs->buf, "vAttach;%x", pid);
3353 getpkt (&rs->buf, &rs->buf_size, 0);
3355 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vAttach]) == PACKET_OK)
3358 printf_unfiltered (_("Attached to %s\n"),
3359 target_pid_to_str (pid_to_ptid (pid)));
3363 /* Save the reply for later. */
3364 wait_status = alloca (strlen (rs->buf) + 1);
3365 strcpy (wait_status, rs->buf);
3367 else if (strcmp (rs->buf, "OK") != 0)
3368 error (_("Attaching to %s failed with: %s"),
3369 target_pid_to_str (pid_to_ptid (pid)),
3372 else if (remote_protocol_packets[PACKET_vAttach].support == PACKET_DISABLE)
3373 error (_("This target does not support attaching to a process"));
3375 error (_("Attaching to %s failed"),
3376 target_pid_to_str (pid_to_ptid (pid)));
3378 target_mark_running (target);
3379 inferior_ptid = pid_to_ptid (pid);
3381 /* Now, if we have thread information, update inferior_ptid. */
3382 inferior_ptid = remote_current_thread (inferior_ptid);
3384 inf = add_inferior (pid);
3385 inf->attach_flag = 1;
3388 /* Get list of threads. */
3389 remote_threads_info ();
3391 /* Add the main thread to the thread list. */
3392 add_thread_silent (inferior_ptid);
3394 /* Next, if the target can specify a description, read it. We do
3395 this before anything involving memory or registers. */
3396 target_find_description ();
3400 /* Use the previously fetched status. */
3401 gdb_assert (wait_status != NULL);
3403 if (target_can_async_p ())
3405 struct stop_reply *stop_reply;
3406 struct cleanup *old_chain;
3408 stop_reply = stop_reply_xmalloc ();
3409 old_chain = make_cleanup (do_stop_reply_xfree, stop_reply);
3410 remote_parse_stop_reply (wait_status, stop_reply);
3411 discard_cleanups (old_chain);
3412 push_stop_reply (stop_reply);
3414 target_async (inferior_event_handler, 0);
3418 gdb_assert (wait_status != NULL);
3419 strcpy (rs->buf, wait_status);
3420 rs->cached_wait_status = 1;
3424 gdb_assert (wait_status == NULL);
3428 extended_remote_attach (char *args, int from_tty)
3430 extended_remote_attach_1 (&extended_remote_ops, args, from_tty);
3433 /* Convert hex digit A to a number. */
3438 if (a >= '0' && a <= '9')
3440 else if (a >= 'a' && a <= 'f')
3441 return a - 'a' + 10;
3442 else if (a >= 'A' && a <= 'F')
3443 return a - 'A' + 10;
3445 error (_("Reply contains invalid hex digit %d"), a);
3449 hex2bin (const char *hex, gdb_byte *bin, int count)
3453 for (i = 0; i < count; i++)
3455 if (hex[0] == 0 || hex[1] == 0)
3457 /* Hex string is short, or of uneven length.
3458 Return the count that has been converted so far. */
3461 *bin++ = fromhex (hex[0]) * 16 + fromhex (hex[1]);
3467 /* Convert number NIB to a hex digit. */
3475 return 'a' + nib - 10;
3479 bin2hex (const gdb_byte *bin, char *hex, int count)
3482 /* May use a length, or a nul-terminated string as input. */
3484 count = strlen ((char *) bin);
3486 for (i = 0; i < count; i++)
3488 *hex++ = tohex ((*bin >> 4) & 0xf);
3489 *hex++ = tohex (*bin++ & 0xf);
3495 /* Check for the availability of vCont. This function should also check
3499 remote_vcont_probe (struct remote_state *rs)
3503 strcpy (rs->buf, "vCont?");
3505 getpkt (&rs->buf, &rs->buf_size, 0);
3508 /* Make sure that the features we assume are supported. */
3509 if (strncmp (buf, "vCont", 5) == 0)
3512 int support_s, support_S, support_c, support_C;
3518 rs->support_vCont_t = 0;
3519 while (p && *p == ';')
3522 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
3524 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
3526 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
3528 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
3530 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
3531 rs->support_vCont_t = 1;
3533 p = strchr (p, ';');
3536 /* If s, S, c, and C are not all supported, we can't use vCont. Clearing
3537 BUF will make packet_ok disable the packet. */
3538 if (!support_s || !support_S || !support_c || !support_C)
3542 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
3545 /* Resume the remote inferior by using a "vCont" packet. The thread
3546 to be resumed is PTID; STEP and SIGGNAL indicate whether the
3547 resumed thread should be single-stepped and/or signalled. If PTID
3548 equals minus_one_ptid, then all threads are resumed; the thread to
3549 be stepped and/or signalled is given in the global INFERIOR_PTID.
3550 This function returns non-zero iff it resumes the inferior.
3552 This function issues a strict subset of all possible vCont commands at the
3556 remote_vcont_resume (ptid_t ptid, int step, enum target_signal siggnal)
3558 struct remote_state *rs = get_remote_state ();
3562 if (remote_protocol_packets[PACKET_vCont].support == PACKET_SUPPORT_UNKNOWN)
3563 remote_vcont_probe (rs);
3565 if (remote_protocol_packets[PACKET_vCont].support == PACKET_DISABLE)
3569 endp = rs->buf + get_remote_packet_size ();
3571 /* If we could generate a wider range of packets, we'd have to worry
3572 about overflowing BUF. Should there be a generic
3573 "multi-part-packet" packet? */
3575 if (ptid_equal (ptid, magic_null_ptid))
3577 /* MAGIC_NULL_PTID means that we don't have any active threads,
3578 so we don't have any TID numbers the inferior will
3579 understand. Make sure to only send forms that do not specify
3581 if (step && siggnal != TARGET_SIGNAL_0)
3582 xsnprintf (p, endp - p, "vCont;S%02x", siggnal);
3584 xsnprintf (p, endp - p, "vCont;s");
3585 else if (siggnal != TARGET_SIGNAL_0)
3586 xsnprintf (p, endp - p, "vCont;C%02x", siggnal);
3588 xsnprintf (p, endp - p, "vCont;c");
3590 else if (ptid_equal (ptid, minus_one_ptid))
3592 /* Resume all threads, with preference for INFERIOR_PTID. */
3593 if (step && siggnal != TARGET_SIGNAL_0)
3595 /* Step inferior_ptid with signal. */
3596 p += xsnprintf (p, endp - p, "vCont;S%02x:", siggnal);
3597 p = write_ptid (p, endp, inferior_ptid);
3598 /* And continue others. */
3599 p += xsnprintf (p, endp - p, ";c");
3603 /* Step inferior_ptid. */
3604 p += xsnprintf (p, endp - p, "vCont;s:");
3605 p = write_ptid (p, endp, inferior_ptid);
3606 /* And continue others. */
3607 p += xsnprintf (p, endp - p, ";c");
3609 else if (siggnal != TARGET_SIGNAL_0)
3611 /* Continue inferior_ptid with signal. */
3612 p += xsnprintf (p, endp - p, "vCont;C%02x:", siggnal);
3613 p = write_ptid (p, endp, inferior_ptid);
3614 /* And continue others. */
3615 p += xsnprintf (p, endp - p, ";c");
3618 xsnprintf (p, endp - p, "vCont;c");
3622 /* Scheduler locking; resume only PTID. */
3623 if (step && siggnal != TARGET_SIGNAL_0)
3625 /* Step ptid with signal. */
3626 p += xsnprintf (p, endp - p, "vCont;S%02x:", siggnal);
3627 p = write_ptid (p, endp, ptid);
3632 p += xsnprintf (p, endp - p, "vCont;s:");
3633 p = write_ptid (p, endp, ptid);
3635 else if (siggnal != TARGET_SIGNAL_0)
3637 /* Continue ptid with signal. */
3638 p += xsnprintf (p, endp - p, "vCont;C%02x:", siggnal);
3639 p = write_ptid (p, endp, ptid);
3643 /* Continue ptid. */
3644 p += xsnprintf (p, endp - p, "vCont;c:");
3645 p = write_ptid (p, endp, ptid);
3649 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
3654 /* In non-stop, the stub replies to vCont with "OK". The stop
3655 reply will be reported asynchronously by means of a `%Stop'
3657 getpkt (&rs->buf, &rs->buf_size, 0);
3658 if (strcmp (rs->buf, "OK") != 0)
3659 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
3665 /* Tell the remote machine to resume. */
3667 static enum target_signal last_sent_signal = TARGET_SIGNAL_0;
3669 static int last_sent_step;
3672 remote_resume (ptid_t ptid, int step, enum target_signal siggnal)
3674 struct remote_state *rs = get_remote_state ();
3677 last_sent_signal = siggnal;
3678 last_sent_step = step;
3680 /* Update the inferior on signals to silently pass, if they've changed. */
3681 remote_pass_signals ();
3683 /* The vCont packet doesn't need to specify threads via Hc. */
3684 if (remote_vcont_resume (ptid, step, siggnal))
3687 /* All other supported resume packets do use Hc, so set the continue
3689 if (ptid_equal (ptid, minus_one_ptid))
3690 set_continue_thread (any_thread_ptid);
3692 set_continue_thread (ptid);
3695 if (execution_direction == EXEC_REVERSE)
3697 /* We don't pass signals to the target in reverse exec mode. */
3698 if (info_verbose && siggnal != TARGET_SIGNAL_0)
3699 warning (" - Can't pass signal %d to target in reverse: ignored.\n",
3701 strcpy (buf, step ? "bs" : "bc");
3703 else if (siggnal != TARGET_SIGNAL_0)
3705 buf[0] = step ? 'S' : 'C';
3706 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
3707 buf[2] = tohex (((int) siggnal) & 0xf);
3711 strcpy (buf, step ? "s" : "c");
3716 /* We are about to start executing the inferior, let's register it
3717 with the event loop. NOTE: this is the one place where all the
3718 execution commands end up. We could alternatively do this in each
3719 of the execution commands in infcmd.c. */
3720 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
3721 into infcmd.c in order to allow inferior function calls to work
3722 NOT asynchronously. */
3723 if (target_can_async_p ())
3724 target_async (inferior_event_handler, 0);
3726 /* We've just told the target to resume. The remote server will
3727 wait for the inferior to stop, and then send a stop reply. In
3728 the mean time, we can't start another command/query ourselves
3729 because the stub wouldn't be ready to process it. This applies
3730 only to the base all-stop protocol, however. In non-stop (which
3731 only supports vCont), the stub replies with an "OK", and is
3732 immediate able to process further serial input. */
3734 rs->waiting_for_stop_reply = 1;
3738 /* Set up the signal handler for SIGINT, while the target is
3739 executing, ovewriting the 'regular' SIGINT signal handler. */
3741 initialize_sigint_signal_handler (void)
3743 signal (SIGINT, handle_remote_sigint);
3746 /* Signal handler for SIGINT, while the target is executing. */
3748 handle_remote_sigint (int sig)
3750 signal (sig, handle_remote_sigint_twice);
3751 mark_async_signal_handler_wrapper (sigint_remote_token);
3754 /* Signal handler for SIGINT, installed after SIGINT has already been
3755 sent once. It will take effect the second time that the user sends
3758 handle_remote_sigint_twice (int sig)
3760 signal (sig, handle_remote_sigint);
3761 mark_async_signal_handler_wrapper (sigint_remote_twice_token);
3764 /* Perform the real interruption of the target execution, in response
3767 async_remote_interrupt (gdb_client_data arg)
3770 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
3772 target_stop (inferior_ptid);
3775 /* Perform interrupt, if the first attempt did not succeed. Just give
3776 up on the target alltogether. */
3778 async_remote_interrupt_twice (gdb_client_data arg)
3781 fprintf_unfiltered (gdb_stdlog, "remote_interrupt_twice called\n");
3786 /* Reinstall the usual SIGINT handlers, after the target has
3789 cleanup_sigint_signal_handler (void *dummy)
3791 signal (SIGINT, handle_sigint);
3794 /* Send ^C to target to halt it. Target will respond, and send us a
3796 static void (*ofunc) (int);
3798 /* The command line interface's stop routine. This function is installed
3799 as a signal handler for SIGINT. The first time a user requests a
3800 stop, we call remote_stop to send a break or ^C. If there is no
3801 response from the target (it didn't stop when the user requested it),
3802 we ask the user if he'd like to detach from the target. */
3804 remote_interrupt (int signo)
3806 /* If this doesn't work, try more severe steps. */
3807 signal (signo, remote_interrupt_twice);
3809 gdb_call_async_signal_handler (sigint_remote_token, 1);
3812 /* The user typed ^C twice. */
3815 remote_interrupt_twice (int signo)
3817 signal (signo, ofunc);
3818 gdb_call_async_signal_handler (sigint_remote_twice_token, 1);
3819 signal (signo, remote_interrupt);
3822 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
3823 thread, all threads of a remote process, or all threads of all
3827 remote_stop_ns (ptid_t ptid)
3829 struct remote_state *rs = get_remote_state ();
3831 char *endp = rs->buf + get_remote_packet_size ();
3832 struct stop_reply *reply, *next;
3834 if (remote_protocol_packets[PACKET_vCont].support == PACKET_SUPPORT_UNKNOWN)
3835 remote_vcont_probe (rs);
3837 if (!rs->support_vCont_t)
3838 error (_("Remote server does not support stopping threads"));
3840 if (ptid_equal (ptid, minus_one_ptid))
3841 p += xsnprintf (p, endp - p, "vCont;t");
3846 /* Step inferior_ptid. */
3847 p += xsnprintf (p, endp - p, "vCont;t:");
3849 if (ptid_is_pid (ptid))
3850 /* All (-1) threads of process. */
3851 nptid = ptid_build (ptid_get_pid (ptid), 0, -1);
3854 /* Small optimization: if we already have a stop reply for
3855 this thread, no use in telling the stub we want this
3857 if (peek_stop_reply (ptid))
3863 p = write_ptid (p, endp, nptid);
3866 /* In non-stop, we get an immediate OK reply. The stop reply will
3867 come in asynchronously by notification. */
3869 getpkt (&rs->buf, &rs->buf_size, 0);
3870 if (strcmp (rs->buf, "OK") != 0)
3871 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
3874 /* All-stop version of target_stop. Sends a break or a ^C to stop the
3875 remote target. It is undefined which thread of which process
3876 reports the stop. */
3879 remote_stop_as (ptid_t ptid)
3881 struct remote_state *rs = get_remote_state ();
3883 /* If the inferior is stopped already, but the core didn't know
3884 about it yet, just ignore the request. The cached wait status
3885 will be collected in remote_wait. */
3886 if (rs->cached_wait_status)
3889 /* Send a break or a ^C, depending on user preference. */
3892 serial_send_break (remote_desc);
3894 serial_write (remote_desc, "\003", 1);
3897 /* This is the generic stop called via the target vector. When a target
3898 interrupt is requested, either by the command line or the GUI, we
3899 will eventually end up here. */
3902 remote_stop (ptid_t ptid)
3905 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
3908 remote_stop_ns (ptid);
3910 remote_stop_as (ptid);
3913 /* Ask the user what to do when an interrupt is received. */
3916 interrupt_query (void)
3918 target_terminal_ours ();
3920 if (target_can_async_p ())
3922 signal (SIGINT, handle_sigint);
3923 deprecated_throw_reason (RETURN_QUIT);
3927 if (query ("Interrupted while waiting for the program.\n\
3928 Give up (and stop debugging it)? "))
3931 deprecated_throw_reason (RETURN_QUIT);
3935 target_terminal_inferior ();
3938 /* Enable/disable target terminal ownership. Most targets can use
3939 terminal groups to control terminal ownership. Remote targets are
3940 different in that explicit transfer of ownership to/from GDB/target
3944 remote_terminal_inferior (void)
3946 if (!target_async_permitted)
3947 /* Nothing to do. */
3950 /* FIXME: cagney/1999-09-27: Shouldn't need to test for
3951 sync_execution here. This function should only be called when
3952 GDB is resuming the inferior in the forground. A background
3953 resume (``run&'') should leave GDB in control of the terminal and
3954 consequently should not call this code. */
3955 if (!sync_execution)
3957 /* FIXME: cagney/1999-09-27: Closely related to the above. Make
3958 calls target_terminal_*() idenpotent. The event-loop GDB talking
3959 to an asynchronous target with a synchronous command calls this
3960 function from both event-top.c and infrun.c/infcmd.c. Once GDB
3961 stops trying to transfer the terminal to the target when it
3962 shouldn't this guard can go away. */
3963 if (!remote_async_terminal_ours_p)
3965 delete_file_handler (input_fd);
3966 remote_async_terminal_ours_p = 0;
3967 initialize_sigint_signal_handler ();
3968 /* NOTE: At this point we could also register our selves as the
3969 recipient of all input. Any characters typed could then be
3970 passed on down to the target. */
3974 remote_terminal_ours (void)
3976 if (!target_async_permitted)
3977 /* Nothing to do. */
3980 /* See FIXME in remote_terminal_inferior. */
3981 if (!sync_execution)
3983 /* See FIXME in remote_terminal_inferior. */
3984 if (remote_async_terminal_ours_p)
3986 cleanup_sigint_signal_handler (NULL);
3987 add_file_handler (input_fd, stdin_event_handler, 0);
3988 remote_async_terminal_ours_p = 1;
3992 remote_console_output (char *msg)
3996 for (p = msg; p[0] && p[1]; p += 2)
3999 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
4002 fputs_unfiltered (tb, gdb_stdtarg);
4004 gdb_flush (gdb_stdtarg);
4007 typedef struct cached_reg
4010 gdb_byte data[MAX_REGISTER_SIZE];
4013 DEF_VEC_O(cached_reg_t);
4017 struct stop_reply *next;
4021 struct target_waitstatus ws;
4023 VEC(cached_reg_t) *regcache;
4025 int stopped_by_watchpoint_p;
4026 CORE_ADDR watch_data_address;
4032 /* The list of already fetched and acknowledged stop events. */
4033 static struct stop_reply *stop_reply_queue;
4035 static struct stop_reply *
4036 stop_reply_xmalloc (void)
4038 struct stop_reply *r = XMALLOC (struct stop_reply);
4044 stop_reply_xfree (struct stop_reply *r)
4048 VEC_free (cached_reg_t, r->regcache);
4053 /* Discard all pending stop replies of inferior PID. If PID is -1,
4054 discard everything. */
4057 discard_pending_stop_replies (int pid)
4059 struct stop_reply *prev = NULL, *reply, *next;
4061 /* Discard the in-flight notification. */
4062 if (pending_stop_reply != NULL
4064 || ptid_get_pid (pending_stop_reply->ptid) == pid))
4066 stop_reply_xfree (pending_stop_reply);
4067 pending_stop_reply = NULL;
4070 /* Discard the stop replies we have already pulled with
4072 for (reply = stop_reply_queue; reply; reply = next)
4076 || ptid_get_pid (reply->ptid) == pid)
4078 if (reply == stop_reply_queue)
4079 stop_reply_queue = reply->next;
4081 prev->next = reply->next;
4083 stop_reply_xfree (reply);
4090 /* Cleanup wrapper. */
4093 do_stop_reply_xfree (void *arg)
4095 struct stop_reply *r = arg;
4096 stop_reply_xfree (r);
4099 /* Look for a queued stop reply belonging to PTID. If one is found,
4100 remove it from the queue, and return it. Returns NULL if none is
4101 found. If there are still queued events left to process, tell the
4102 event loop to get back to target_wait soon. */
4104 static struct stop_reply *
4105 queued_stop_reply (ptid_t ptid)
4107 struct stop_reply *it, *prev;
4108 struct stop_reply head;
4110 head.next = stop_reply_queue;
4115 if (!ptid_equal (ptid, minus_one_ptid))
4116 for (; it; prev = it, it = it->next)
4117 if (ptid_equal (ptid, it->ptid))
4122 prev->next = it->next;
4126 stop_reply_queue = head.next;
4128 if (stop_reply_queue)
4129 /* There's still at least an event left. */
4130 mark_async_event_handler (remote_async_inferior_event_token);
4135 /* Push a fully parsed stop reply in the stop reply queue. Since we
4136 know that we now have at least one queued event left to pass to the
4137 core side, tell the event loop to get back to target_wait soon. */
4140 push_stop_reply (struct stop_reply *new_event)
4142 struct stop_reply *event;
4144 if (stop_reply_queue)
4146 for (event = stop_reply_queue;
4147 event && event->next;
4148 event = event->next)
4151 event->next = new_event;
4154 stop_reply_queue = new_event;
4156 mark_async_event_handler (remote_async_inferior_event_token);
4159 /* Returns true if we have a stop reply for PTID. */
4162 peek_stop_reply (ptid_t ptid)
4164 struct stop_reply *it;
4166 for (it = stop_reply_queue; it; it = it->next)
4167 if (ptid_equal (ptid, it->ptid))
4169 if (it->ws.kind == TARGET_WAITKIND_STOPPED)
4176 /* Parse the stop reply in BUF. Either the function succeeds, and the
4177 result is stored in EVENT, or throws an error. */
4180 remote_parse_stop_reply (char *buf, struct stop_reply *event)
4182 struct remote_arch_state *rsa = get_remote_arch_state ();
4186 event->ptid = null_ptid;
4187 event->ws.kind = TARGET_WAITKIND_IGNORE;
4188 event->ws.value.integer = 0;
4189 event->solibs_changed = 0;
4190 event->replay_event = 0;
4191 event->stopped_by_watchpoint_p = 0;
4192 event->regcache = NULL;
4196 case 'T': /* Status with PC, SP, FP, ... */
4198 gdb_byte regs[MAX_REGISTER_SIZE];
4200 /* Expedited reply, containing Signal, {regno, reg} repeat. */
4201 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
4203 n... = register number
4204 r... = register contents
4207 p = &buf[3]; /* after Txx */
4215 /* If the packet contains a register number, save it in
4216 pnum and set p1 to point to the character following it.
4217 Otherwise p1 points to p. */
4219 /* If this packet is an awatch packet, don't parse the 'a'
4220 as a register number. */
4222 if (strncmp (p, "awatch", strlen("awatch")) != 0)
4224 /* Read the ``P'' register number. */
4225 pnum = strtol (p, &p_temp, 16);
4231 if (p1 == p) /* No register number present here. */
4233 p1 = strchr (p, ':');
4235 error (_("Malformed packet(a) (missing colon): %s\n\
4238 if (strncmp (p, "thread", p1 - p) == 0)
4239 event->ptid = read_ptid (++p1, &p);
4240 else if ((strncmp (p, "watch", p1 - p) == 0)
4241 || (strncmp (p, "rwatch", p1 - p) == 0)
4242 || (strncmp (p, "awatch", p1 - p) == 0))
4244 event->stopped_by_watchpoint_p = 1;
4245 p = unpack_varlen_hex (++p1, &addr);
4246 event->watch_data_address = (CORE_ADDR) addr;
4248 else if (strncmp (p, "library", p1 - p) == 0)
4252 while (*p_temp && *p_temp != ';')
4255 event->solibs_changed = 1;
4258 else if (strncmp (p, "replaylog", p1 - p) == 0)
4260 /* NO_HISTORY event.
4261 p1 will indicate "begin" or "end", but
4262 it makes no difference for now, so ignore it. */
4263 event->replay_event = 1;
4264 p_temp = strchr (p1 + 1, ';');
4270 /* Silently skip unknown optional info. */
4271 p_temp = strchr (p1 + 1, ';');
4278 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
4279 cached_reg_t cached_reg;
4281 cached_reg.num = reg->regnum;
4286 error (_("Malformed packet(b) (missing colon): %s\n\
4292 error (_("Remote sent bad register number %s: %s\n\
4294 phex_nz (pnum, 0), p, buf);
4296 fieldsize = hex2bin (p, cached_reg.data,
4297 register_size (target_gdbarch,
4300 if (fieldsize < register_size (target_gdbarch,
4302 warning (_("Remote reply is too short: %s"), buf);
4304 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
4308 error (_("Remote register badly formatted: %s\nhere: %s"),
4314 case 'S': /* Old style status, just signal only. */
4315 if (event->solibs_changed)
4316 event->ws.kind = TARGET_WAITKIND_LOADED;
4317 else if (event->replay_event)
4318 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
4321 event->ws.kind = TARGET_WAITKIND_STOPPED;
4322 event->ws.value.sig = (enum target_signal)
4323 (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
4326 case 'W': /* Target exited. */
4333 /* GDB used to accept only 2 hex chars here. Stubs should
4334 only send more if they detect GDB supports multi-process
4336 p = unpack_varlen_hex (&buf[1], &value);
4340 /* The remote process exited. */
4341 event->ws.kind = TARGET_WAITKIND_EXITED;
4342 event->ws.value.integer = value;
4346 /* The remote process exited with a signal. */
4347 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
4348 event->ws.value.sig = (enum target_signal) value;
4351 /* If no process is specified, assume inferior_ptid. */
4352 pid = ptid_get_pid (inferior_ptid);
4361 else if (strncmp (p,
4362 "process:", sizeof ("process:") - 1) == 0)
4365 p += sizeof ("process:") - 1;
4366 unpack_varlen_hex (p, &upid);
4370 error (_("unknown stop reply packet: %s"), buf);
4373 error (_("unknown stop reply packet: %s"), buf);
4374 event->ptid = pid_to_ptid (pid);
4379 if (non_stop && ptid_equal (event->ptid, null_ptid))
4380 error (_("No process or thread specified in stop reply: %s"), buf);
4383 /* When the stub wants to tell GDB about a new stop reply, it sends a
4384 stop notification (%Stop). Those can come it at any time, hence,
4385 we have to make sure that any pending putpkt/getpkt sequence we're
4386 making is finished, before querying the stub for more events with
4387 vStopped. E.g., if we started a vStopped sequence immediatelly
4388 upon receiving the %Stop notification, something like this could
4396 1.6) <-- (registers reply to step #1.3)
4398 Obviously, the reply in step #1.6 would be unexpected to a vStopped
4401 To solve this, whenever we parse a %Stop notification sucessfully,
4402 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
4403 doing whatever we were doing:
4409 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
4410 2.5) <-- (registers reply to step #2.3)
4412 Eventualy after step #2.5, we return to the event loop, which
4413 notices there's an event on the
4414 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
4415 associated callback --- the function below. At this point, we're
4416 always safe to start a vStopped sequence. :
4419 2.7) <-- T05 thread:2
4425 remote_get_pending_stop_replies (void)
4427 struct remote_state *rs = get_remote_state ();
4430 if (pending_stop_reply)
4433 putpkt ("vStopped");
4435 /* Now we can rely on it. */
4436 push_stop_reply (pending_stop_reply);
4437 pending_stop_reply = NULL;
4441 getpkt (&rs->buf, &rs->buf_size, 0);
4442 if (strcmp (rs->buf, "OK") == 0)
4446 struct cleanup *old_chain;
4447 struct stop_reply *stop_reply = stop_reply_xmalloc ();
4449 old_chain = make_cleanup (do_stop_reply_xfree, stop_reply);
4450 remote_parse_stop_reply (rs->buf, stop_reply);
4453 putpkt ("vStopped");
4455 if (stop_reply->ws.kind != TARGET_WAITKIND_IGNORE)
4457 /* Now we can rely on it. */
4458 discard_cleanups (old_chain);
4459 push_stop_reply (stop_reply);
4462 /* We got an unknown stop reply. */
4463 do_cleanups (old_chain);
4470 /* Called when it is decided that STOP_REPLY holds the info of the
4471 event that is to be returned to the core. This function always
4472 destroys STOP_REPLY. */
4475 process_stop_reply (struct stop_reply *stop_reply,
4476 struct target_waitstatus *status)
4480 *status = stop_reply->ws;
4481 ptid = stop_reply->ptid;
4483 /* If no thread/process was reported by the stub, assume the current
4485 if (ptid_equal (ptid, null_ptid))
4486 ptid = inferior_ptid;
4488 if (status->kind == TARGET_WAITKIND_EXITED
4489 || status->kind == TARGET_WAITKIND_SIGNALLED)
4491 int pid = ptid_get_pid (ptid);
4492 delete_inferior (pid);
4495 notice_new_inferiors (ptid);
4497 /* Expedited registers. */
4498 if (stop_reply->regcache)
4504 VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
4506 regcache_raw_supply (get_thread_regcache (ptid),
4507 reg->num, reg->data);
4508 VEC_free (cached_reg_t, stop_reply->regcache);
4511 remote_stopped_by_watchpoint_p = stop_reply->stopped_by_watchpoint_p;
4512 remote_watch_data_address = stop_reply->watch_data_address;
4514 stop_reply_xfree (stop_reply);
4518 /* The non-stop mode version of target_wait. */
4521 remote_wait_ns (ptid_t ptid, struct target_waitstatus *status)
4523 struct remote_state *rs = get_remote_state ();
4524 struct remote_arch_state *rsa = get_remote_arch_state ();
4525 ptid_t event_ptid = null_ptid;
4526 struct stop_reply *stop_reply;
4529 /* If in non-stop mode, get out of getpkt even if a
4530 notification is received. */
4532 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
4539 case 'E': /* Error of some sort. */
4540 /* We're out of sync with the target now. Did it continue
4541 or not? We can't tell which thread it was in non-stop,
4542 so just ignore this. */
4543 warning (_("Remote failure reply: %s"), rs->buf);
4545 case 'O': /* Console output. */
4546 remote_console_output (rs->buf + 1);
4549 warning (_("Invalid remote reply: %s"), rs->buf);
4553 /* Acknowledge a pending stop reply that may have arrived in the
4555 if (pending_stop_reply != NULL)
4556 remote_get_pending_stop_replies ();
4558 /* If indeed we noticed a stop reply, we're done. */
4559 stop_reply = queued_stop_reply (ptid);
4560 if (stop_reply != NULL)
4561 return process_stop_reply (stop_reply, status);
4563 /* Still no event. If we're in asynchronous mode, then just
4564 return to the event loop. */
4565 if (remote_is_async_p ())
4567 status->kind = TARGET_WAITKIND_IGNORE;
4568 return minus_one_ptid;
4571 /* Otherwise, asynchronous mode is masked, so do a blocking
4573 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
4578 /* Wait until the remote machine stops, then return, storing status in
4579 STATUS just as `wait' would. */
4582 remote_wait_as (ptid_t ptid, struct target_waitstatus *status)
4584 struct remote_state *rs = get_remote_state ();
4585 struct remote_arch_state *rsa = get_remote_arch_state ();
4586 ptid_t event_ptid = null_ptid;
4588 int solibs_changed = 0;
4590 struct stop_reply *stop_reply;
4592 status->kind = TARGET_WAITKIND_IGNORE;
4593 status->value.integer = 0;
4595 stop_reply = queued_stop_reply (ptid);
4596 if (stop_reply != NULL)
4597 return process_stop_reply (stop_reply, status);
4599 if (rs->cached_wait_status)
4600 /* Use the cached wait status, but only once. */
4601 rs->cached_wait_status = 0;
4606 if (!target_is_async_p ())
4608 ofunc = signal (SIGINT, remote_interrupt);
4609 /* If the user hit C-c before this packet, or between packets,
4610 pretend that it was hit right here. */
4614 remote_interrupt (SIGINT);
4618 /* FIXME: cagney/1999-09-27: If we're in async mode we should
4619 _never_ wait for ever -> test on target_is_async_p().
4620 However, before we do that we need to ensure that the caller
4621 knows how to take the target into/out of async mode. */
4622 ret = getpkt_sane (&rs->buf, &rs->buf_size, wait_forever_enabled_p);
4623 if (!target_is_async_p ())
4624 signal (SIGINT, ofunc);
4629 remote_stopped_by_watchpoint_p = 0;
4631 /* We got something. */
4632 rs->waiting_for_stop_reply = 0;
4636 case 'E': /* Error of some sort. */
4637 /* We're out of sync with the target now. Did it continue or
4638 not? Not is more likely, so report a stop. */
4639 warning (_("Remote failure reply: %s"), buf);
4640 status->kind = TARGET_WAITKIND_STOPPED;
4641 status->value.sig = TARGET_SIGNAL_0;
4643 case 'F': /* File-I/O request. */
4644 remote_fileio_request (buf);
4646 case 'T': case 'S': case 'X': case 'W':
4648 struct stop_reply *stop_reply;
4649 struct cleanup *old_chain;
4651 stop_reply = stop_reply_xmalloc ();
4652 old_chain = make_cleanup (do_stop_reply_xfree, stop_reply);
4653 remote_parse_stop_reply (buf, stop_reply);
4654 discard_cleanups (old_chain);
4655 event_ptid = process_stop_reply (stop_reply, status);
4658 case 'O': /* Console output. */
4659 remote_console_output (buf + 1);
4661 /* The target didn't really stop; keep waiting. */
4662 rs->waiting_for_stop_reply = 1;
4666 if (last_sent_signal != TARGET_SIGNAL_0)
4668 /* Zero length reply means that we tried 'S' or 'C' and the
4669 remote system doesn't support it. */
4670 target_terminal_ours_for_output ();
4672 ("Can't send signals to this remote system. %s not sent.\n",
4673 target_signal_to_name (last_sent_signal));
4674 last_sent_signal = TARGET_SIGNAL_0;
4675 target_terminal_inferior ();
4677 strcpy ((char *) buf, last_sent_step ? "s" : "c");
4678 putpkt ((char *) buf);
4680 /* We just told the target to resume, so a stop reply is in
4682 rs->waiting_for_stop_reply = 1;
4685 /* else fallthrough */
4687 warning (_("Invalid remote reply: %s"), buf);
4689 rs->waiting_for_stop_reply = 1;
4693 if (status->kind == TARGET_WAITKIND_IGNORE)
4694 /* Nothing interesting happened. */
4695 return minus_one_ptid;
4696 else if (status->kind != TARGET_WAITKIND_EXITED
4697 && status->kind != TARGET_WAITKIND_SIGNALLED)
4699 if (!ptid_equal (event_ptid, null_ptid))
4700 record_currthread (event_ptid);
4702 event_ptid = inferior_ptid;
4705 /* A process exit. Invalidate our notion of current thread. */
4706 record_currthread (minus_one_ptid);
4711 /* Wait until the remote machine stops, then return, storing status in
4712 STATUS just as `wait' would. */
4715 remote_wait (ptid_t ptid, struct target_waitstatus *status)
4720 event_ptid = remote_wait_ns (ptid, status);
4723 /* In synchronous mode, keep waiting until the target stops. In
4724 asynchronous mode, always return to the event loop. */
4728 event_ptid = remote_wait_as (ptid, status);
4730 while (status->kind == TARGET_WAITKIND_IGNORE
4731 && !target_can_async_p ());
4734 if (target_can_async_p ())
4736 /* If there are are events left in the queue tell the event loop
4738 if (stop_reply_queue)
4739 mark_async_event_handler (remote_async_inferior_event_token);
4745 /* Fetch a single register using a 'p' packet. */
4748 fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
4750 struct remote_state *rs = get_remote_state ();
4752 char regp[MAX_REGISTER_SIZE];
4755 if (remote_protocol_packets[PACKET_p].support == PACKET_DISABLE)
4758 if (reg->pnum == -1)
4763 p += hexnumstr (p, reg->pnum);
4765 remote_send (&rs->buf, &rs->buf_size);
4769 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
4773 case PACKET_UNKNOWN:
4776 error (_("Could not fetch register \"%s\""),
4777 gdbarch_register_name (get_regcache_arch (regcache), reg->regnum));
4780 /* If this register is unfetchable, tell the regcache. */
4783 regcache_raw_supply (regcache, reg->regnum, NULL);
4787 /* Otherwise, parse and supply the value. */
4793 error (_("fetch_register_using_p: early buf termination"));
4795 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
4798 regcache_raw_supply (regcache, reg->regnum, regp);
4802 /* Fetch the registers included in the target's 'g' packet. */
4805 send_g_packet (void)
4807 struct remote_state *rs = get_remote_state ();
4812 sprintf (rs->buf, "g");
4813 remote_send (&rs->buf, &rs->buf_size);
4815 /* We can get out of synch in various cases. If the first character
4816 in the buffer is not a hex character, assume that has happened
4817 and try to fetch another packet to read. */
4818 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
4819 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
4820 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
4821 && rs->buf[0] != 'x') /* New: unavailable register value. */
4824 fprintf_unfiltered (gdb_stdlog,
4825 "Bad register packet; fetching a new packet\n");
4826 getpkt (&rs->buf, &rs->buf_size, 0);
4829 buf_len = strlen (rs->buf);
4831 /* Sanity check the received packet. */
4832 if (buf_len % 2 != 0)
4833 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
4839 process_g_packet (struct regcache *regcache)
4841 struct gdbarch *gdbarch = get_regcache_arch (regcache);
4842 struct remote_state *rs = get_remote_state ();
4843 struct remote_arch_state *rsa = get_remote_arch_state ();
4848 buf_len = strlen (rs->buf);
4850 /* Further sanity checks, with knowledge of the architecture. */
4851 if (buf_len > 2 * rsa->sizeof_g_packet)
4852 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
4854 /* Save the size of the packet sent to us by the target. It is used
4855 as a heuristic when determining the max size of packets that the
4856 target can safely receive. */
4857 if (rsa->actual_register_packet_size == 0)
4858 rsa->actual_register_packet_size = buf_len;
4860 /* If this is smaller than we guessed the 'g' packet would be,
4861 update our records. A 'g' reply that doesn't include a register's
4862 value implies either that the register is not available, or that
4863 the 'p' packet must be used. */
4864 if (buf_len < 2 * rsa->sizeof_g_packet)
4866 rsa->sizeof_g_packet = buf_len / 2;
4868 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
4870 if (rsa->regs[i].pnum == -1)
4873 if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
4874 rsa->regs[i].in_g_packet = 0;
4876 rsa->regs[i].in_g_packet = 1;
4880 regs = alloca (rsa->sizeof_g_packet);
4882 /* Unimplemented registers read as all bits zero. */
4883 memset (regs, 0, rsa->sizeof_g_packet);
4885 /* Reply describes registers byte by byte, each byte encoded as two
4886 hex characters. Suck them all up, then supply them to the
4887 register cacheing/storage mechanism. */
4890 for (i = 0; i < rsa->sizeof_g_packet; i++)
4892 if (p[0] == 0 || p[1] == 0)
4893 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
4894 internal_error (__FILE__, __LINE__,
4895 "unexpected end of 'g' packet reply");
4897 if (p[0] == 'x' && p[1] == 'x')
4898 regs[i] = 0; /* 'x' */
4900 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
4906 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
4908 struct packet_reg *r = &rsa->regs[i];
4911 if (r->offset * 2 >= strlen (rs->buf))
4912 /* This shouldn't happen - we adjusted in_g_packet above. */
4913 internal_error (__FILE__, __LINE__,
4914 "unexpected end of 'g' packet reply");
4915 else if (rs->buf[r->offset * 2] == 'x')
4917 gdb_assert (r->offset * 2 < strlen (rs->buf));
4918 /* The register isn't available, mark it as such (at
4919 the same time setting the value to zero). */
4920 regcache_raw_supply (regcache, r->regnum, NULL);
4923 regcache_raw_supply (regcache, r->regnum,
4931 fetch_registers_using_g (struct regcache *regcache)
4934 process_g_packet (regcache);
4938 remote_fetch_registers (struct regcache *regcache, int regnum)
4940 struct remote_state *rs = get_remote_state ();
4941 struct remote_arch_state *rsa = get_remote_arch_state ();
4944 set_general_thread (inferior_ptid);
4948 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
4949 gdb_assert (reg != NULL);
4951 /* If this register might be in the 'g' packet, try that first -
4952 we are likely to read more than one register. If this is the
4953 first 'g' packet, we might be overly optimistic about its
4954 contents, so fall back to 'p'. */
4955 if (reg->in_g_packet)
4957 fetch_registers_using_g (regcache);
4958 if (reg->in_g_packet)
4962 if (fetch_register_using_p (regcache, reg))
4965 /* This register is not available. */
4966 regcache_raw_supply (regcache, reg->regnum, NULL);
4971 fetch_registers_using_g (regcache);
4973 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
4974 if (!rsa->regs[i].in_g_packet)
4975 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
4977 /* This register is not available. */
4978 regcache_raw_supply (regcache, i, NULL);
4982 /* Prepare to store registers. Since we may send them all (using a
4983 'G' request), we have to read out the ones we don't want to change
4987 remote_prepare_to_store (struct regcache *regcache)
4989 struct remote_arch_state *rsa = get_remote_arch_state ();
4991 gdb_byte buf[MAX_REGISTER_SIZE];
4993 /* Make sure the entire registers array is valid. */
4994 switch (remote_protocol_packets[PACKET_P].support)
4996 case PACKET_DISABLE:
4997 case PACKET_SUPPORT_UNKNOWN:
4998 /* Make sure all the necessary registers are cached. */
4999 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
5000 if (rsa->regs[i].in_g_packet)
5001 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
5008 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
5009 packet was not recognized. */
5012 store_register_using_P (const struct regcache *regcache, struct packet_reg *reg)
5014 struct gdbarch *gdbarch = get_regcache_arch (regcache);
5015 struct remote_state *rs = get_remote_state ();
5016 struct remote_arch_state *rsa = get_remote_arch_state ();
5017 /* Try storing a single register. */
5018 char *buf = rs->buf;
5019 gdb_byte regp[MAX_REGISTER_SIZE];
5022 if (remote_protocol_packets[PACKET_P].support == PACKET_DISABLE)
5025 if (reg->pnum == -1)
5028 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
5029 p = buf + strlen (buf);
5030 regcache_raw_collect (regcache, reg->regnum, regp);
5031 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
5032 remote_send (&rs->buf, &rs->buf_size);
5034 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
5039 error (_("Could not write register \"%s\""),
5040 gdbarch_register_name (gdbarch, reg->regnum));
5041 case PACKET_UNKNOWN:
5044 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
5048 /* Store register REGNUM, or all registers if REGNUM == -1, from the
5049 contents of the register cache buffer. FIXME: ignores errors. */
5052 store_registers_using_G (const struct regcache *regcache)
5054 struct remote_state *rs = get_remote_state ();
5055 struct remote_arch_state *rsa = get_remote_arch_state ();
5059 /* Extract all the registers in the regcache copying them into a
5063 regs = alloca (rsa->sizeof_g_packet);
5064 memset (regs, 0, rsa->sizeof_g_packet);
5065 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
5067 struct packet_reg *r = &rsa->regs[i];
5069 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
5073 /* Command describes registers byte by byte,
5074 each byte encoded as two hex characters. */
5077 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
5079 bin2hex (regs, p, rsa->sizeof_g_packet);
5080 remote_send (&rs->buf, &rs->buf_size);
5083 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
5084 of the register cache buffer. FIXME: ignores errors. */
5087 remote_store_registers (struct regcache *regcache, int regnum)
5089 struct remote_state *rs = get_remote_state ();
5090 struct remote_arch_state *rsa = get_remote_arch_state ();
5093 set_general_thread (inferior_ptid);
5097 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
5098 gdb_assert (reg != NULL);
5100 /* Always prefer to store registers using the 'P' packet if
5101 possible; we often change only a small number of registers.
5102 Sometimes we change a larger number; we'd need help from a
5103 higher layer to know to use 'G'. */
5104 if (store_register_using_P (regcache, reg))
5107 /* For now, don't complain if we have no way to write the
5108 register. GDB loses track of unavailable registers too
5109 easily. Some day, this may be an error. We don't have
5110 any way to read the register, either... */
5111 if (!reg->in_g_packet)
5114 store_registers_using_G (regcache);
5118 store_registers_using_G (regcache);
5120 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
5121 if (!rsa->regs[i].in_g_packet)
5122 if (!store_register_using_P (regcache, &rsa->regs[i]))
5123 /* See above for why we do not issue an error here. */
5128 /* Return the number of hex digits in num. */
5131 hexnumlen (ULONGEST num)
5135 for (i = 0; num != 0; i++)
5141 /* Set BUF to the minimum number of hex digits representing NUM. */
5144 hexnumstr (char *buf, ULONGEST num)
5146 int len = hexnumlen (num);
5147 return hexnumnstr (buf, num, len);
5151 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
5154 hexnumnstr (char *buf, ULONGEST num, int width)
5160 for (i = width - 1; i >= 0; i--)
5162 buf[i] = "0123456789abcdef"[(num & 0xf)];
5169 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
5172 remote_address_masked (CORE_ADDR addr)
5174 int address_size = remote_address_size;
5175 /* If "remoteaddresssize" was not set, default to target address size. */
5177 address_size = gdbarch_addr_bit (target_gdbarch);
5179 if (address_size > 0
5180 && address_size < (sizeof (ULONGEST) * 8))
5182 /* Only create a mask when that mask can safely be constructed
5183 in a ULONGEST variable. */
5185 mask = (mask << address_size) - 1;
5191 /* Convert BUFFER, binary data at least LEN bytes long, into escaped
5192 binary data in OUT_BUF. Set *OUT_LEN to the length of the data
5193 encoded in OUT_BUF, and return the number of bytes in OUT_BUF
5194 (which may be more than *OUT_LEN due to escape characters). The
5195 total number of bytes in the output buffer will be at most
5199 remote_escape_output (const gdb_byte *buffer, int len,
5200 gdb_byte *out_buf, int *out_len,
5203 int input_index, output_index;
5206 for (input_index = 0; input_index < len; input_index++)
5208 gdb_byte b = buffer[input_index];
5210 if (b == '$' || b == '#' || b == '}')
5212 /* These must be escaped. */
5213 if (output_index + 2 > out_maxlen)
5215 out_buf[output_index++] = '}';
5216 out_buf[output_index++] = b ^ 0x20;
5220 if (output_index + 1 > out_maxlen)
5222 out_buf[output_index++] = b;
5226 *out_len = input_index;
5227 return output_index;
5230 /* Convert BUFFER, escaped data LEN bytes long, into binary data
5231 in OUT_BUF. Return the number of bytes written to OUT_BUF.
5232 Raise an error if the total number of bytes exceeds OUT_MAXLEN.
5234 This function reverses remote_escape_output. It allows more
5235 escaped characters than that function does, in particular because
5236 '*' must be escaped to avoid the run-length encoding processing
5237 in reading packets. */
5240 remote_unescape_input (const gdb_byte *buffer, int len,
5241 gdb_byte *out_buf, int out_maxlen)
5243 int input_index, output_index;
5248 for (input_index = 0; input_index < len; input_index++)
5250 gdb_byte b = buffer[input_index];
5252 if (output_index + 1 > out_maxlen)
5254 warning (_("Received too much data from remote target;"
5255 " ignoring overflow."));
5256 return output_index;
5261 out_buf[output_index++] = b ^ 0x20;
5267 out_buf[output_index++] = b;
5271 error (_("Unmatched escape character in target response."));
5273 return output_index;
5276 /* Determine whether the remote target supports binary downloading.
5277 This is accomplished by sending a no-op memory write of zero length
5278 to the target at the specified address. It does not suffice to send
5279 the whole packet, since many stubs strip the eighth bit and
5280 subsequently compute a wrong checksum, which causes real havoc with
5283 NOTE: This can still lose if the serial line is not eight-bit
5284 clean. In cases like this, the user should clear "remote
5288 check_binary_download (CORE_ADDR addr)
5290 struct remote_state *rs = get_remote_state ();
5292 switch (remote_protocol_packets[PACKET_X].support)
5294 case PACKET_DISABLE:
5298 case PACKET_SUPPORT_UNKNOWN:
5304 p += hexnumstr (p, (ULONGEST) addr);
5306 p += hexnumstr (p, (ULONGEST) 0);
5310 putpkt_binary (rs->buf, (int) (p - rs->buf));
5311 getpkt (&rs->buf, &rs->buf_size, 0);
5313 if (rs->buf[0] == '\0')
5316 fprintf_unfiltered (gdb_stdlog,
5317 "binary downloading NOT suppported by target\n");
5318 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
5323 fprintf_unfiltered (gdb_stdlog,
5324 "binary downloading suppported by target\n");
5325 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
5332 /* Write memory data directly to the remote machine.
5333 This does not inform the data cache; the data cache uses this.
5334 HEADER is the starting part of the packet.
5335 MEMADDR is the address in the remote memory space.
5336 MYADDR is the address of the buffer in our space.
5337 LEN is the number of bytes.
5338 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
5339 should send data as binary ('X'), or hex-encoded ('M').
5341 The function creates packet of the form
5342 <HEADER><ADDRESS>,<LENGTH>:<DATA>
5344 where encoding of <DATA> is termined by PACKET_FORMAT.
5346 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
5349 Returns the number of bytes transferred, or 0 (setting errno) for
5350 error. Only transfer a single packet. */
5353 remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
5354 const gdb_byte *myaddr, int len,
5355 char packet_format, int use_length)
5357 struct remote_state *rs = get_remote_state ();
5367 if (packet_format != 'X' && packet_format != 'M')
5368 internal_error (__FILE__, __LINE__,
5369 "remote_write_bytes_aux: bad packet format");
5374 payload_size = get_memory_write_packet_size ();
5376 /* The packet buffer will be large enough for the payload;
5377 get_memory_packet_size ensures this. */
5380 /* Compute the size of the actual payload by subtracting out the
5381 packet header and footer overhead: "$M<memaddr>,<len>:...#nn".
5383 payload_size -= strlen ("$,:#NN");
5385 /* The comma won't be used. */
5387 header_length = strlen (header);
5388 payload_size -= header_length;
5389 payload_size -= hexnumlen (memaddr);
5391 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
5393 strcat (rs->buf, header);
5394 p = rs->buf + strlen (header);
5396 /* Compute a best guess of the number of bytes actually transfered. */
5397 if (packet_format == 'X')
5399 /* Best guess at number of bytes that will fit. */
5400 todo = min (len, payload_size);
5402 payload_size -= hexnumlen (todo);
5403 todo = min (todo, payload_size);
5407 /* Num bytes that will fit. */
5408 todo = min (len, payload_size / 2);
5410 payload_size -= hexnumlen (todo);
5411 todo = min (todo, payload_size / 2);
5415 internal_error (__FILE__, __LINE__,
5416 _("minumum packet size too small to write data"));
5418 /* If we already need another packet, then try to align the end
5419 of this packet to a useful boundary. */
5420 if (todo > 2 * REMOTE_ALIGN_WRITES && todo < len)
5421 todo = ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
5423 /* Append "<memaddr>". */
5424 memaddr = remote_address_masked (memaddr);
5425 p += hexnumstr (p, (ULONGEST) memaddr);
5432 /* Append <len>. Retain the location/size of <len>. It may need to
5433 be adjusted once the packet body has been created. */
5435 plenlen = hexnumstr (p, (ULONGEST) todo);
5443 /* Append the packet body. */
5444 if (packet_format == 'X')
5446 /* Binary mode. Send target system values byte by byte, in
5447 increasing byte addresses. Only escape certain critical
5449 payload_length = remote_escape_output (myaddr, todo, p, &nr_bytes,
5452 /* If not all TODO bytes fit, then we'll need another packet. Make
5453 a second try to keep the end of the packet aligned. Don't do
5454 this if the packet is tiny. */
5455 if (nr_bytes < todo && nr_bytes > 2 * REMOTE_ALIGN_WRITES)
5459 new_nr_bytes = (((memaddr + nr_bytes) & ~(REMOTE_ALIGN_WRITES - 1))
5461 if (new_nr_bytes != nr_bytes)
5462 payload_length = remote_escape_output (myaddr, new_nr_bytes,
5467 p += payload_length;
5468 if (use_length && nr_bytes < todo)
5470 /* Escape chars have filled up the buffer prematurely,
5471 and we have actually sent fewer bytes than planned.
5472 Fix-up the length field of the packet. Use the same
5473 number of characters as before. */
5474 plen += hexnumnstr (plen, (ULONGEST) nr_bytes, plenlen);
5475 *plen = ':'; /* overwrite \0 from hexnumnstr() */
5480 /* Normal mode: Send target system values byte by byte, in
5481 increasing byte addresses. Each byte is encoded as a two hex
5483 nr_bytes = bin2hex (myaddr, p, todo);
5487 putpkt_binary (rs->buf, (int) (p - rs->buf));
5488 getpkt (&rs->buf, &rs->buf_size, 0);
5490 if (rs->buf[0] == 'E')
5492 /* There is no correspondance between what the remote protocol
5493 uses for errors and errno codes. We would like a cleaner way
5494 of representing errors (big enough to include errno codes,
5495 bfd_error codes, and others). But for now just return EIO. */
5500 /* Return NR_BYTES, not TODO, in case escape chars caused us to send
5501 fewer bytes than we'd planned. */
5505 /* Write memory data directly to the remote machine.
5506 This does not inform the data cache; the data cache uses this.
5507 MEMADDR is the address in the remote memory space.
5508 MYADDR is the address of the buffer in our space.
5509 LEN is the number of bytes.
5511 Returns number of bytes transferred, or 0 (setting errno) for
5512 error. Only transfer a single packet. */
5515 remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, int len)
5517 char *packet_format = 0;
5519 /* Check whether the target supports binary download. */
5520 check_binary_download (memaddr);
5522 switch (remote_protocol_packets[PACKET_X].support)
5525 packet_format = "X";
5527 case PACKET_DISABLE:
5528 packet_format = "M";
5530 case PACKET_SUPPORT_UNKNOWN:
5531 internal_error (__FILE__, __LINE__,
5532 _("remote_write_bytes: bad internal state"));
5534 internal_error (__FILE__, __LINE__, _("bad switch"));
5537 return remote_write_bytes_aux (packet_format,
5538 memaddr, myaddr, len, packet_format[0], 1);
5541 /* Read memory data directly from the remote machine.
5542 This does not use the data cache; the data cache uses this.
5543 MEMADDR is the address in the remote memory space.
5544 MYADDR is the address of the buffer in our space.
5545 LEN is the number of bytes.
5547 Returns number of bytes transferred, or 0 for error. */
5549 /* NOTE: cagney/1999-10-18: This function (and its siblings in other
5550 remote targets) shouldn't attempt to read the entire buffer.
5551 Instead it should read a single packet worth of data and then
5552 return the byte size of that packet to the caller. The caller (its
5553 caller and its callers caller ;-) already contains code for
5554 handling partial reads. */
5557 remote_read_bytes (CORE_ADDR memaddr, gdb_byte *myaddr, int len)
5559 struct remote_state *rs = get_remote_state ();
5560 int max_buf_size; /* Max size of packet output buffer. */
5566 max_buf_size = get_memory_read_packet_size ();
5567 /* The packet buffer will be large enough for the payload;
5568 get_memory_packet_size ensures this. */
5577 todo = min (len, max_buf_size / 2); /* num bytes that will fit */
5579 /* construct "m"<memaddr>","<len>" */
5580 /* sprintf (rs->buf, "m%lx,%x", (unsigned long) memaddr, todo); */
5581 memaddr = remote_address_masked (memaddr);
5584 p += hexnumstr (p, (ULONGEST) memaddr);
5586 p += hexnumstr (p, (ULONGEST) todo);
5590 getpkt (&rs->buf, &rs->buf_size, 0);
5592 if (rs->buf[0] == 'E'
5593 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
5594 && rs->buf[3] == '\0')
5596 /* There is no correspondance between what the remote
5597 protocol uses for errors and errno codes. We would like
5598 a cleaner way of representing errors (big enough to
5599 include errno codes, bfd_error codes, and others). But
5600 for now just return EIO. */
5605 /* Reply describes memory byte by byte,
5606 each byte encoded as two hex characters. */
5609 if ((i = hex2bin (p, myaddr, todo)) < todo)
5611 /* Reply is short. This means that we were able to read
5612 only part of what we wanted to. */
5613 return i + (origlen - len);
5623 /* Remote notification handler. */
5626 handle_notification (char *buf, size_t length)
5628 if (strncmp (buf, "Stop:", 5) == 0)
5630 if (pending_stop_reply)
5631 /* We've already parsed the in-flight stop-reply, but the stub
5632 for some reason thought we didn't, possibly due to timeout
5633 on its side. Just ignore it. */
5637 struct cleanup *old_chain;
5638 struct stop_reply *reply = stop_reply_xmalloc ();
5639 old_chain = make_cleanup (do_stop_reply_xfree, reply);
5641 remote_parse_stop_reply (buf + 5, reply);
5643 discard_cleanups (old_chain);
5645 /* Be careful to only set it after parsing, since an error
5646 may be thrown then. */
5647 pending_stop_reply = reply;
5649 /* Notify the event loop there's a stop reply to acknowledge
5650 and that there may be more events to fetch. */
5651 mark_async_event_handler (remote_async_get_pending_events_token);
5655 /* We ignore notifications we don't recognize, for compatibility
5656 with newer stubs. */
5661 /* Read or write LEN bytes from inferior memory at MEMADDR,
5662 transferring to or from debugger address BUFFER. Write to inferior
5663 if SHOULD_WRITE is nonzero. Returns length of data written or
5664 read; 0 for error. TARGET is unused. */
5667 remote_xfer_memory (CORE_ADDR mem_addr, gdb_byte *buffer, int mem_len,
5668 int should_write, struct mem_attrib *attrib,
5669 struct target_ops *target)
5673 set_general_thread (inferior_ptid);
5676 res = remote_write_bytes (mem_addr, buffer, mem_len);
5678 res = remote_read_bytes (mem_addr, buffer, mem_len);
5683 /* Sends a packet with content determined by the printf format string
5684 FORMAT and the remaining arguments, then gets the reply. Returns
5685 whether the packet was a success, a failure, or unknown. */
5688 remote_send_printf (const char *format, ...)
5690 struct remote_state *rs = get_remote_state ();
5691 int max_size = get_remote_packet_size ();
5694 va_start (ap, format);
5697 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
5698 internal_error (__FILE__, __LINE__, "Too long remote packet.");
5700 if (putpkt (rs->buf) < 0)
5701 error (_("Communication problem with target."));
5704 getpkt (&rs->buf, &rs->buf_size, 0);
5706 return packet_check_result (rs->buf);
5710 restore_remote_timeout (void *p)
5712 int value = *(int *)p;
5713 remote_timeout = value;
5716 /* Flash writing can take quite some time. We'll set
5717 effectively infinite timeout for flash operations.
5718 In future, we'll need to decide on a better approach. */
5719 static const int remote_flash_timeout = 1000;
5722 remote_flash_erase (struct target_ops *ops,
5723 ULONGEST address, LONGEST length)
5725 int saved_remote_timeout = remote_timeout;
5726 enum packet_result ret;
5728 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
5729 &saved_remote_timeout);
5730 remote_timeout = remote_flash_timeout;
5732 ret = remote_send_printf ("vFlashErase:%s,%s",
5737 case PACKET_UNKNOWN:
5738 error (_("Remote target does not support flash erase"));
5740 error (_("Error erasing flash with vFlashErase packet"));
5745 do_cleanups (back_to);
5749 remote_flash_write (struct target_ops *ops,
5750 ULONGEST address, LONGEST length,
5751 const gdb_byte *data)
5753 int saved_remote_timeout = remote_timeout;
5755 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
5756 &saved_remote_timeout);
5758 remote_timeout = remote_flash_timeout;
5759 ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length, 'X', 0);
5760 do_cleanups (back_to);
5766 remote_flash_done (struct target_ops *ops)
5768 int saved_remote_timeout = remote_timeout;
5770 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
5771 &saved_remote_timeout);
5773 remote_timeout = remote_flash_timeout;
5774 ret = remote_send_printf ("vFlashDone");
5775 do_cleanups (back_to);
5779 case PACKET_UNKNOWN:
5780 error (_("Remote target does not support vFlashDone"));
5782 error (_("Error finishing flash operation"));
5789 remote_files_info (struct target_ops *ignore)
5791 puts_filtered ("Debugging a target over a serial line.\n");
5794 /* Stuff for dealing with the packets which are part of this protocol.
5795 See comment at top of file for details. */
5797 /* Read a single character from the remote end. */
5800 readchar (int timeout)
5804 ch = serial_readchar (remote_desc, timeout);
5809 switch ((enum serial_rc) ch)
5813 error (_("Remote connection closed"));
5816 perror_with_name (_("Remote communication error"));
5818 case SERIAL_TIMEOUT:
5824 /* Send the command in *BUF to the remote machine, and read the reply
5825 into *BUF. Report an error if we get an error reply. Resize
5826 *BUF using xrealloc if necessary to hold the result, and update
5830 remote_send (char **buf,
5834 getpkt (buf, sizeof_buf, 0);
5836 if ((*buf)[0] == 'E')
5837 error (_("Remote failure reply: %s"), *buf);
5840 /* Display a null-terminated packet on stdout, for debugging, using C
5844 print_packet (char *buf)
5846 puts_filtered ("\"");
5847 fputstr_filtered (buf, '"', gdb_stdout);
5848 puts_filtered ("\"");
5854 return putpkt_binary (buf, strlen (buf));
5857 /* Send a packet to the remote machine, with error checking. The data
5858 of the packet is in BUF. The string in BUF can be at most
5859 get_remote_packet_size () - 5 to account for the $, # and checksum,
5860 and for a possible /0 if we are debugging (remote_debug) and want
5861 to print the sent packet as a string. */
5864 putpkt_binary (char *buf, int cnt)
5866 struct remote_state *rs = get_remote_state ();
5868 unsigned char csum = 0;
5869 char *buf2 = alloca (cnt + 6);
5875 /* Catch cases like trying to read memory or listing threads while
5876 we're waiting for a stop reply. The remote server wouldn't be
5877 ready to handle this request, so we'd hang and timeout. We don't
5878 have to worry about this in synchronous mode, because in that
5879 case it's not possible to issue a command while the target is
5880 running. This is not a problem in non-stop mode, because in that
5881 case, the stub is always ready to process serial input. */
5882 if (!non_stop && target_can_async_p () && rs->waiting_for_stop_reply)
5883 error (_("Cannot execute this command while the target is running."));
5885 /* We're sending out a new packet. Make sure we don't look at a
5886 stale cached response. */
5887 rs->cached_wait_status = 0;
5889 /* Copy the packet into buffer BUF2, encapsulating it
5890 and giving it a checksum. */
5895 for (i = 0; i < cnt; i++)
5901 *p++ = tohex ((csum >> 4) & 0xf);
5902 *p++ = tohex (csum & 0xf);
5904 /* Send it over and over until we get a positive ack. */
5908 int started_error_output = 0;
5913 fprintf_unfiltered (gdb_stdlog, "Sending packet: ");
5914 fputstrn_unfiltered (buf2, p - buf2, 0, gdb_stdlog);
5915 fprintf_unfiltered (gdb_stdlog, "...");
5916 gdb_flush (gdb_stdlog);
5918 if (serial_write (remote_desc, buf2, p - buf2))
5919 perror_with_name (_("putpkt: write failed"));
5921 /* If this is a no acks version of the remote protocol, send the
5922 packet and move on. */
5926 /* Read until either a timeout occurs (-2) or '+' is read.
5927 Handle any notification that arrives in the mean time. */
5930 ch = readchar (remote_timeout);
5938 case SERIAL_TIMEOUT:
5941 if (started_error_output)
5943 putchar_unfiltered ('\n');
5944 started_error_output = 0;
5953 fprintf_unfiltered (gdb_stdlog, "Ack\n");
5957 fprintf_unfiltered (gdb_stdlog, "Nak\n");
5958 case SERIAL_TIMEOUT:
5962 break; /* Retransmit buffer. */
5966 fprintf_unfiltered (gdb_stdlog,
5967 "Packet instead of Ack, ignoring it\n");
5968 /* It's probably an old response sent because an ACK
5969 was lost. Gobble up the packet and ack it so it
5970 doesn't get retransmitted when we resend this
5973 serial_write (remote_desc, "+", 1);
5974 continue; /* Now, go look for +. */
5981 /* If we got a notification, handle it, and go back to looking
5983 /* We've found the start of a notification. Now
5984 collect the data. */
5985 val = read_frame (&rs->buf, &rs->buf_size);
5990 fprintf_unfiltered (gdb_stdlog, " Notification received: ");
5991 fputstrn_unfiltered (rs->buf, val, 0, gdb_stdlog);
5992 fprintf_unfiltered (gdb_stdlog, "\n");
5994 handle_notification (rs->buf, val);
5995 /* We're in sync now, rewait for the ack. */
6002 if (!started_error_output)
6004 started_error_output = 1;
6005 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
6007 fputc_unfiltered (ch & 0177, gdb_stdlog);
6008 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
6017 if (!started_error_output)
6019 started_error_output = 1;
6020 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
6022 fputc_unfiltered (ch & 0177, gdb_stdlog);
6026 break; /* Here to retransmit. */
6030 /* This is wrong. If doing a long backtrace, the user should be
6031 able to get out next time we call QUIT, without anything as
6032 violent as interrupt_query. If we want to provide a way out of
6033 here without getting to the next QUIT, it should be based on
6034 hitting ^C twice as in remote_wait. */
6045 /* Come here after finding the start of a frame when we expected an
6046 ack. Do our best to discard the rest of this packet. */
6055 c = readchar (remote_timeout);
6058 case SERIAL_TIMEOUT:
6059 /* Nothing we can do. */
6062 /* Discard the two bytes of checksum and stop. */
6063 c = readchar (remote_timeout);
6065 c = readchar (remote_timeout);
6068 case '*': /* Run length encoding. */
6069 /* Discard the repeat count. */
6070 c = readchar (remote_timeout);
6075 /* A regular character. */
6081 /* Come here after finding the start of the frame. Collect the rest
6082 into *BUF, verifying the checksum, length, and handling run-length
6083 compression. NUL terminate the buffer. If there is not enough room,
6084 expand *BUF using xrealloc.
6086 Returns -1 on error, number of characters in buffer (ignoring the
6087 trailing NULL) on success. (could be extended to return one of the
6088 SERIAL status indications). */
6091 read_frame (char **buf_p,
6098 struct remote_state *rs = get_remote_state ();
6105 c = readchar (remote_timeout);
6108 case SERIAL_TIMEOUT:
6110 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
6114 fputs_filtered ("Saw new packet start in middle of old one\n",
6116 return -1; /* Start a new packet, count retries. */
6119 unsigned char pktcsum;
6125 check_0 = readchar (remote_timeout);
6127 check_1 = readchar (remote_timeout);
6129 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
6132 fputs_filtered ("Timeout in checksum, retrying\n",
6136 else if (check_0 < 0 || check_1 < 0)
6139 fputs_filtered ("Communication error in checksum\n",
6144 /* Don't recompute the checksum; with no ack packets we
6145 don't have any way to indicate a packet retransmission
6150 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
6151 if (csum == pktcsum)
6156 fprintf_filtered (gdb_stdlog,
6157 "Bad checksum, sentsum=0x%x, csum=0x%x, buf=",
6159 fputstrn_filtered (buf, bc, 0, gdb_stdlog);
6160 fputs_filtered ("\n", gdb_stdlog);
6162 /* Number of characters in buffer ignoring trailing
6166 case '*': /* Run length encoding. */
6171 c = readchar (remote_timeout);
6173 repeat = c - ' ' + 3; /* Compute repeat count. */
6175 /* The character before ``*'' is repeated. */
6177 if (repeat > 0 && repeat <= 255 && bc > 0)
6179 if (bc + repeat - 1 >= *sizeof_buf - 1)
6181 /* Make some more room in the buffer. */
6182 *sizeof_buf += repeat;
6183 *buf_p = xrealloc (*buf_p, *sizeof_buf);
6187 memset (&buf[bc], buf[bc - 1], repeat);
6193 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
6197 if (bc >= *sizeof_buf - 1)
6199 /* Make some more room in the buffer. */
6201 *buf_p = xrealloc (*buf_p, *sizeof_buf);
6212 /* Read a packet from the remote machine, with error checking, and
6213 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
6214 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
6215 rather than timing out; this is used (in synchronous mode) to wait
6216 for a target that is is executing user code to stop. */
6217 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
6218 don't have to change all the calls to getpkt to deal with the
6219 return value, because at the moment I don't know what the right
6220 thing to do it for those. */
6228 timed_out = getpkt_sane (buf, sizeof_buf, forever);
6232 /* Read a packet from the remote machine, with error checking, and
6233 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
6234 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
6235 rather than timing out; this is used (in synchronous mode) to wait
6236 for a target that is is executing user code to stop. If FOREVER ==
6237 0, this function is allowed to time out gracefully and return an
6238 indication of this to the caller. Otherwise return the number of
6239 bytes read. If EXPECTING_NOTIF, consider receiving a notification
6240 enough reason to return to the caller. */
6243 getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
6244 int expecting_notif)
6246 struct remote_state *rs = get_remote_state ();
6252 /* We're reading a new response. Make sure we don't look at a
6253 previously cached response. */
6254 rs->cached_wait_status = 0;
6256 strcpy (*buf, "timeout");
6259 timeout = watchdog > 0 ? watchdog : -1;
6260 else if (expecting_notif)
6261 timeout = 0; /* There should already be a char in the buffer. If
6264 timeout = remote_timeout;
6268 /* Process any number of notifications, and then return when
6272 /* If we get a timeout or bad checksm, retry up to MAX_TRIES
6274 for (tries = 1; tries <= MAX_TRIES; tries++)
6276 /* This can loop forever if the remote side sends us
6277 characters continuously, but if it pauses, we'll get
6278 SERIAL_TIMEOUT from readchar because of timeout. Then
6279 we'll count that as a retry.
6281 Note that even when forever is set, we will only wait
6282 forever prior to the start of a packet. After that, we
6283 expect characters to arrive at a brisk pace. They should
6284 show up within remote_timeout intervals. */
6286 c = readchar (timeout);
6287 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
6289 if (c == SERIAL_TIMEOUT)
6291 if (expecting_notif)
6292 return -1; /* Don't complain, it's normal to not get
6293 anything in this case. */
6295 if (forever) /* Watchdog went off? Kill the target. */
6299 error (_("Watchdog timeout has expired. Target detached."));
6302 fputs_filtered ("Timed out.\n", gdb_stdlog);
6306 /* We've found the start of a packet or notification.
6307 Now collect the data. */
6308 val = read_frame (buf, sizeof_buf);
6313 serial_write (remote_desc, "-", 1);
6316 if (tries > MAX_TRIES)
6318 /* We have tried hard enough, and just can't receive the
6319 packet/notification. Give up. */
6320 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
6322 /* Skip the ack char if we're in no-ack mode. */
6323 if (!rs->noack_mode)
6324 serial_write (remote_desc, "+", 1);
6328 /* If we got an ordinary packet, return that to our caller. */
6333 fprintf_unfiltered (gdb_stdlog, "Packet received: ");
6334 fputstrn_unfiltered (*buf, val, 0, gdb_stdlog);
6335 fprintf_unfiltered (gdb_stdlog, "\n");
6338 /* Skip the ack char if we're in no-ack mode. */
6339 if (!rs->noack_mode)
6340 serial_write (remote_desc, "+", 1);
6344 /* If we got a notification, handle it, and go back to looking
6348 gdb_assert (c == '%');
6352 fprintf_unfiltered (gdb_stdlog, " Notification received: ");
6353 fputstrn_unfiltered (*buf, val, 0, gdb_stdlog);
6354 fprintf_unfiltered (gdb_stdlog, "\n");
6357 handle_notification (*buf, val);
6359 /* Notifications require no acknowledgement. */
6361 if (expecting_notif)
6368 getpkt_sane (char **buf, long *sizeof_buf, int forever)
6370 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0);
6374 getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever)
6376 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1);
6383 /* Use catch_errors so the user can quit from gdb even when we
6384 aren't on speaking terms with the remote system. */
6385 catch_errors ((catch_errors_ftype *) putpkt, "k", "", RETURN_MASK_ERROR);
6387 /* Don't wait for it to die. I'm not really sure it matters whether
6388 we do or not. For the existing stubs, kill is a noop. */
6389 target_mourn_inferior ();
6393 remote_vkill (int pid, struct remote_state *rs)
6395 if (remote_protocol_packets[PACKET_vKill].support == PACKET_DISABLE)
6398 /* Tell the remote target to detach. */
6399 sprintf (rs->buf, "vKill;%x", pid);
6401 getpkt (&rs->buf, &rs->buf_size, 0);
6403 if (packet_ok (rs->buf,
6404 &remote_protocol_packets[PACKET_vKill]) == PACKET_OK)
6406 else if (remote_protocol_packets[PACKET_vKill].support == PACKET_DISABLE)
6413 extended_remote_kill (void)
6416 int pid = ptid_get_pid (inferior_ptid);
6417 struct remote_state *rs = get_remote_state ();
6419 res = remote_vkill (pid, rs);
6420 if (res == -1 && !remote_multi_process_p (rs))
6422 /* Don't try 'k' on a multi-process aware stub -- it has no way
6423 to specify the pid. */
6427 getpkt (&rs->buf, &rs->buf_size, 0);
6428 if (rs->buf[0] != 'O' || rs->buf[0] != 'K')
6431 /* Don't wait for it to die. I'm not really sure it matters whether
6432 we do or not. For the existing stubs, kill is a noop. */
6438 error (_("Can't kill process"));
6440 delete_inferior (pid);
6441 target_mourn_inferior ();
6447 remote_mourn_1 (&remote_ops);
6450 /* Worker function for remote_mourn. */
6452 remote_mourn_1 (struct target_ops *target)
6454 unpush_target (target);
6456 /* remote_close takes care of cleaning up. */
6460 select_new_thread_callback (struct thread_info *th, void* data)
6462 if (!is_exited (th->ptid))
6464 switch_to_thread (th->ptid);
6465 printf_filtered (_("[Switching to %s]\n"),
6466 target_pid_to_str (inferior_ptid));
6473 extended_remote_mourn_1 (struct target_ops *target)
6475 struct remote_state *rs = get_remote_state ();
6477 /* In case we got here due to an error, but we're going to stay
6479 rs->waiting_for_stop_reply = 0;
6481 /* We're no longer interested in these events. */
6482 discard_pending_stop_replies (ptid_get_pid (inferior_ptid));
6484 /* Unlike "target remote", we do not want to unpush the target; then
6485 the next time the user says "run", we won't be connected. */
6487 if (have_inferiors ())
6489 extern void nullify_last_target_wait_ptid ();
6490 /* Multi-process case. The current process has exited, but
6491 there are other processes to debug. Switch to the first
6493 iterate_over_threads (select_new_thread_callback, NULL);
6494 nullify_last_target_wait_ptid ();
6498 struct remote_state *rs = get_remote_state ();
6500 /* Call common code to mark the inferior as not running. */
6501 generic_mourn_inferior ();
6502 if (!remote_multi_process_p (rs))
6504 /* Check whether the target is running now - some remote stubs
6505 automatically restart after kill. */
6507 getpkt (&rs->buf, &rs->buf_size, 0);
6509 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
6511 /* Assume that the target has been restarted. Set inferior_ptid
6512 so that bits of core GDB realizes there's something here, e.g.,
6513 so that the user can say "kill" again. */
6514 inferior_ptid = magic_null_ptid;
6518 /* Mark this (still pushed) target as not executable until we
6520 target_mark_exited (target);
6524 /* Always remove execution if this was the last process. */
6525 target_mark_exited (target);
6530 extended_remote_mourn (void)
6532 extended_remote_mourn_1 (&extended_remote_ops);
6536 extended_remote_run (char *args)
6538 struct remote_state *rs = get_remote_state ();
6542 /* If the user has disabled vRun support, or we have detected that
6543 support is not available, do not try it. */
6544 if (remote_protocol_packets[PACKET_vRun].support == PACKET_DISABLE)
6547 strcpy (rs->buf, "vRun;");
6548 len = strlen (rs->buf);
6550 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
6551 error (_("Remote file name too long for run packet"));
6552 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len, 0);
6554 gdb_assert (args != NULL);
6557 struct cleanup *back_to;
6561 argv = gdb_buildargv (args);
6562 back_to = make_cleanup ((void (*) (void *)) freeargv, argv);
6563 for (i = 0; argv[i] != NULL; i++)
6565 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
6566 error (_("Argument list too long for run packet"));
6567 rs->buf[len++] = ';';
6568 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len, 0);
6570 do_cleanups (back_to);
6573 rs->buf[len++] = '\0';
6576 getpkt (&rs->buf, &rs->buf_size, 0);
6578 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]) == PACKET_OK)
6580 /* We have a wait response; we don't need it, though. All is well. */
6583 else if (remote_protocol_packets[PACKET_vRun].support == PACKET_DISABLE)
6584 /* It wasn't disabled before, but it is now. */
6588 if (remote_exec_file[0] == '\0')
6589 error (_("Running the default executable on the remote target failed; "
6590 "try \"set remote exec-file\"?"));
6592 error (_("Running \"%s\" on the remote target failed"),
6597 /* In the extended protocol we want to be able to do things like
6598 "run" and have them basically work as expected. So we need
6599 a special create_inferior function. We support changing the
6600 executable file and the command line arguments, but not the
6604 extended_remote_create_inferior_1 (char *exec_file, char *args,
6605 char **env, int from_tty)
6607 /* If running asynchronously, register the target file descriptor
6608 with the event loop. */
6609 if (target_can_async_p ())
6610 target_async (inferior_event_handler, 0);
6612 /* Now restart the remote server. */
6613 if (extended_remote_run (args) == -1)
6615 /* vRun was not supported. Fail if we need it to do what the
6617 if (remote_exec_file[0])
6618 error (_("Remote target does not support \"set remote exec-file\""));
6620 error (_("Remote target does not support \"set args\" or run <ARGS>"));
6622 /* Fall back to "R". */
6623 extended_remote_restart ();
6626 /* Clean up from the last time we ran, before we mark the target
6627 running again. This will mark breakpoints uninserted, and
6628 get_offsets may insert breakpoints. */
6629 init_thread_list ();
6630 init_wait_for_inferior ();
6632 /* Now mark the inferior as running before we do anything else. */
6633 inferior_ptid = magic_null_ptid;
6635 /* Now, if we have thread information, update inferior_ptid. */
6636 inferior_ptid = remote_current_thread (inferior_ptid);
6638 add_inferior (ptid_get_pid (inferior_ptid));
6639 add_thread_silent (inferior_ptid);
6641 target_mark_running (&extended_remote_ops);
6643 /* Get updated offsets, if the stub uses qOffsets. */
6648 extended_remote_create_inferior (char *exec_file, char *args,
6649 char **env, int from_tty)
6651 extended_remote_create_inferior_1 (exec_file, args, env, from_tty);
6655 /* Insert a breakpoint. On targets that have software breakpoint
6656 support, we ask the remote target to do the work; on targets
6657 which don't, we insert a traditional memory breakpoint. */
6660 remote_insert_breakpoint (struct bp_target_info *bp_tgt)
6662 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
6663 If it succeeds, then set the support to PACKET_ENABLE. If it
6664 fails, and the user has explicitly requested the Z support then
6665 report an error, otherwise, mark it disabled and go on. */
6667 if (remote_protocol_packets[PACKET_Z0].support != PACKET_DISABLE)
6669 CORE_ADDR addr = bp_tgt->placed_address;
6670 struct remote_state *rs;
6674 gdbarch_breakpoint_from_pc (target_gdbarch, &addr, &bpsize);
6676 rs = get_remote_state ();
6682 addr = (ULONGEST) remote_address_masked (addr);
6683 p += hexnumstr (p, addr);
6684 sprintf (p, ",%d", bpsize);
6687 getpkt (&rs->buf, &rs->buf_size, 0);
6689 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
6694 bp_tgt->placed_address = addr;
6695 bp_tgt->placed_size = bpsize;
6697 case PACKET_UNKNOWN:
6702 return memory_insert_breakpoint (bp_tgt);
6706 remote_remove_breakpoint (struct bp_target_info *bp_tgt)
6708 CORE_ADDR addr = bp_tgt->placed_address;
6709 struct remote_state *rs = get_remote_state ();
6712 if (remote_protocol_packets[PACKET_Z0].support != PACKET_DISABLE)
6720 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
6721 p += hexnumstr (p, addr);
6722 sprintf (p, ",%d", bp_tgt->placed_size);
6725 getpkt (&rs->buf, &rs->buf_size, 0);
6727 return (rs->buf[0] == 'E');
6730 return memory_remove_breakpoint (bp_tgt);
6734 watchpoint_to_Z_packet (int type)
6739 return Z_PACKET_WRITE_WP;
6742 return Z_PACKET_READ_WP;
6745 return Z_PACKET_ACCESS_WP;
6748 internal_error (__FILE__, __LINE__,
6749 _("hw_bp_to_z: bad watchpoint type %d"), type);
6754 remote_insert_watchpoint (CORE_ADDR addr, int len, int type)
6756 struct remote_state *rs = get_remote_state ();
6758 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
6760 if (remote_protocol_packets[PACKET_Z0 + packet].support == PACKET_DISABLE)
6763 sprintf (rs->buf, "Z%x,", packet);
6764 p = strchr (rs->buf, '\0');
6765 addr = remote_address_masked (addr);
6766 p += hexnumstr (p, (ULONGEST) addr);
6767 sprintf (p, ",%x", len);
6770 getpkt (&rs->buf, &rs->buf_size, 0);
6772 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
6775 case PACKET_UNKNOWN:
6780 internal_error (__FILE__, __LINE__,
6781 _("remote_insert_watchpoint: reached end of function"));
6786 remote_remove_watchpoint (CORE_ADDR addr, int len, int type)
6788 struct remote_state *rs = get_remote_state ();
6790 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
6792 if (remote_protocol_packets[PACKET_Z0 + packet].support == PACKET_DISABLE)
6795 sprintf (rs->buf, "z%x,", packet);
6796 p = strchr (rs->buf, '\0');
6797 addr = remote_address_masked (addr);
6798 p += hexnumstr (p, (ULONGEST) addr);
6799 sprintf (p, ",%x", len);
6801 getpkt (&rs->buf, &rs->buf_size, 0);
6803 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
6806 case PACKET_UNKNOWN:
6811 internal_error (__FILE__, __LINE__,
6812 _("remote_remove_watchpoint: reached end of function"));
6816 int remote_hw_watchpoint_limit = -1;
6817 int remote_hw_breakpoint_limit = -1;
6820 remote_check_watch_resources (int type, int cnt, int ot)
6822 if (type == bp_hardware_breakpoint)
6824 if (remote_hw_breakpoint_limit == 0)
6826 else if (remote_hw_breakpoint_limit < 0)
6828 else if (cnt <= remote_hw_breakpoint_limit)
6833 if (remote_hw_watchpoint_limit == 0)
6835 else if (remote_hw_watchpoint_limit < 0)
6839 else if (cnt <= remote_hw_watchpoint_limit)
6846 remote_stopped_by_watchpoint (void)
6848 return remote_stopped_by_watchpoint_p;
6852 remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
6855 if (remote_stopped_by_watchpoint ())
6857 *addr_p = remote_watch_data_address;
6866 remote_insert_hw_breakpoint (struct bp_target_info *bp_tgt)
6869 struct remote_state *rs;
6872 /* The length field should be set to the size of a breakpoint
6873 instruction, even though we aren't inserting one ourselves. */
6875 gdbarch_breakpoint_from_pc
6876 (target_gdbarch, &bp_tgt->placed_address, &bp_tgt->placed_size);
6878 if (remote_protocol_packets[PACKET_Z1].support == PACKET_DISABLE)
6881 rs = get_remote_state ();
6888 addr = remote_address_masked (bp_tgt->placed_address);
6889 p += hexnumstr (p, (ULONGEST) addr);
6890 sprintf (p, ",%x", bp_tgt->placed_size);
6893 getpkt (&rs->buf, &rs->buf_size, 0);
6895 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
6898 case PACKET_UNKNOWN:
6903 internal_error (__FILE__, __LINE__,
6904 _("remote_insert_hw_breakpoint: reached end of function"));
6909 remote_remove_hw_breakpoint (struct bp_target_info *bp_tgt)
6912 struct remote_state *rs = get_remote_state ();
6915 if (remote_protocol_packets[PACKET_Z1].support == PACKET_DISABLE)
6922 addr = remote_address_masked (bp_tgt->placed_address);
6923 p += hexnumstr (p, (ULONGEST) addr);
6924 sprintf (p, ",%x", bp_tgt->placed_size);
6927 getpkt (&rs->buf, &rs->buf_size, 0);
6929 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
6932 case PACKET_UNKNOWN:
6937 internal_error (__FILE__, __LINE__,
6938 _("remote_remove_hw_breakpoint: reached end of function"));
6941 /* Table used by the crc32 function to calcuate the checksum. */
6943 static unsigned long crc32_table[256] =
6946 static unsigned long
6947 crc32 (unsigned char *buf, int len, unsigned int crc)
6949 if (!crc32_table[1])
6951 /* Initialize the CRC table and the decoding table. */
6955 for (i = 0; i < 256; i++)
6957 for (c = i << 24, j = 8; j > 0; --j)
6958 c = c & 0x80000000 ? (c << 1) ^ 0x04c11db7 : (c << 1);
6965 crc = (crc << 8) ^ crc32_table[((crc >> 24) ^ *buf) & 255];
6971 /* compare-sections command
6973 With no arguments, compares each loadable section in the exec bfd
6974 with the same memory range on the target, and reports mismatches.
6975 Useful for verifying the image on the target against the exec file.
6976 Depends on the target understanding the new "qCRC:" request. */
6978 /* FIXME: cagney/1999-10-26: This command should be broken down into a
6979 target method (target verify memory) and generic version of the
6980 actual command. This will allow other high-level code (especially
6981 generic_load()) to make use of this target functionality. */
6984 compare_sections_command (char *args, int from_tty)
6986 struct remote_state *rs = get_remote_state ();
6988 unsigned long host_crc, target_crc;
6989 extern bfd *exec_bfd;
6990 struct cleanup *old_chain;
6993 const char *sectname;
7000 error (_("command cannot be used without an exec file"));
7001 if (!current_target.to_shortname ||
7002 strcmp (current_target.to_shortname, "remote") != 0)
7003 error (_("command can only be used with remote target"));
7005 for (s = exec_bfd->sections; s; s = s->next)
7007 if (!(s->flags & SEC_LOAD))
7008 continue; /* skip non-loadable section */
7010 size = bfd_get_section_size (s);
7012 continue; /* skip zero-length section */
7014 sectname = bfd_get_section_name (exec_bfd, s);
7015 if (args && strcmp (args, sectname) != 0)
7016 continue; /* not the section selected by user */
7018 matched = 1; /* do this section */
7020 /* FIXME: assumes lma can fit into long. */
7021 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
7022 (long) lma, (long) size);
7025 /* Be clever; compute the host_crc before waiting for target
7027 sectdata = xmalloc (size);
7028 old_chain = make_cleanup (xfree, sectdata);
7029 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
7030 host_crc = crc32 ((unsigned char *) sectdata, size, 0xffffffff);
7032 getpkt (&rs->buf, &rs->buf_size, 0);
7033 if (rs->buf[0] == 'E')
7034 error (_("target memory fault, section %s, range 0x%s -- 0x%s"),
7035 sectname, paddr (lma), paddr (lma + size));
7036 if (rs->buf[0] != 'C')
7037 error (_("remote target does not support this operation"));
7039 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
7040 target_crc = target_crc * 16 + fromhex (*tmp);
7042 printf_filtered ("Section %s, range 0x%s -- 0x%s: ",
7043 sectname, paddr (lma), paddr (lma + size));
7044 if (host_crc == target_crc)
7045 printf_filtered ("matched.\n");
7048 printf_filtered ("MIS-MATCHED!\n");
7052 do_cleanups (old_chain);
7055 warning (_("One or more sections of the remote executable does not match\n\
7056 the loaded file\n"));
7057 if (args && !matched)
7058 printf_filtered (_("No loaded section named '%s'.\n"), args);
7061 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
7062 into remote target. The number of bytes written to the remote
7063 target is returned, or -1 for error. */
7066 remote_write_qxfer (struct target_ops *ops, const char *object_name,
7067 const char *annex, const gdb_byte *writebuf,
7068 ULONGEST offset, LONGEST len,
7069 struct packet_config *packet)
7074 struct remote_state *rs = get_remote_state ();
7075 int max_size = get_memory_write_packet_size ();
7077 if (packet->support == PACKET_DISABLE)
7080 /* Insert header. */
7081 i = snprintf (rs->buf, max_size,
7082 "qXfer:%s:write:%s:%s:",
7083 object_name, annex ? annex : "",
7084 phex_nz (offset, sizeof offset));
7085 max_size -= (i + 1);
7087 /* Escape as much data as fits into rs->buf. */
7088 buf_len = remote_escape_output
7089 (writebuf, len, (rs->buf + i), &max_size, max_size);
7091 if (putpkt_binary (rs->buf, i + buf_len) < 0
7092 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
7093 || packet_ok (rs->buf, packet) != PACKET_OK)
7096 unpack_varlen_hex (rs->buf, &n);
7100 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
7101 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
7102 number of bytes read is returned, or 0 for EOF, or -1 for error.
7103 The number of bytes read may be less than LEN without indicating an
7104 EOF. PACKET is checked and updated to indicate whether the remote
7105 target supports this object. */
7108 remote_read_qxfer (struct target_ops *ops, const char *object_name,
7110 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
7111 struct packet_config *packet)
7113 static char *finished_object;
7114 static char *finished_annex;
7115 static ULONGEST finished_offset;
7117 struct remote_state *rs = get_remote_state ();
7118 unsigned int total = 0;
7119 LONGEST i, n, packet_len;
7121 if (packet->support == PACKET_DISABLE)
7124 /* Check whether we've cached an end-of-object packet that matches
7126 if (finished_object)
7128 if (strcmp (object_name, finished_object) == 0
7129 && strcmp (annex ? annex : "", finished_annex) == 0
7130 && offset == finished_offset)
7133 /* Otherwise, we're now reading something different. Discard
7135 xfree (finished_object);
7136 xfree (finished_annex);
7137 finished_object = NULL;
7138 finished_annex = NULL;
7141 /* Request only enough to fit in a single packet. The actual data
7142 may not, since we don't know how much of it will need to be escaped;
7143 the target is free to respond with slightly less data. We subtract
7144 five to account for the response type and the protocol frame. */
7145 n = min (get_remote_packet_size () - 5, len);
7146 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
7147 object_name, annex ? annex : "",
7148 phex_nz (offset, sizeof offset),
7149 phex_nz (n, sizeof n));
7150 i = putpkt (rs->buf);
7155 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
7156 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
7159 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
7160 error (_("Unknown remote qXfer reply: %s"), rs->buf);
7162 /* 'm' means there is (or at least might be) more data after this
7163 batch. That does not make sense unless there's at least one byte
7164 of data in this reply. */
7165 if (rs->buf[0] == 'm' && packet_len == 1)
7166 error (_("Remote qXfer reply contained no data."));
7168 /* Got some data. */
7169 i = remote_unescape_input (rs->buf + 1, packet_len - 1, readbuf, n);
7171 /* 'l' is an EOF marker, possibly including a final block of data,
7172 or possibly empty. If we have the final block of a non-empty
7173 object, record this fact to bypass a subsequent partial read. */
7174 if (rs->buf[0] == 'l' && offset + i > 0)
7176 finished_object = xstrdup (object_name);
7177 finished_annex = xstrdup (annex ? annex : "");
7178 finished_offset = offset + i;
7185 remote_xfer_partial (struct target_ops *ops, enum target_object object,
7186 const char *annex, gdb_byte *readbuf,
7187 const gdb_byte *writebuf, ULONGEST offset, LONGEST len)
7189 struct remote_state *rs;
7194 set_general_thread (inferior_ptid);
7196 rs = get_remote_state ();
7198 /* Handle memory using the standard memory routines. */
7199 if (object == TARGET_OBJECT_MEMORY)
7204 /* If the remote target is connected but not running, we should
7205 pass this request down to a lower stratum (e.g. the executable
7207 if (!target_has_execution)
7210 if (writebuf != NULL)
7211 xfered = remote_write_bytes (offset, writebuf, len);
7213 xfered = remote_read_bytes (offset, readbuf, len);
7217 else if (xfered == 0 && errno == 0)
7223 /* Handle SPU memory using qxfer packets. */
7224 if (object == TARGET_OBJECT_SPU)
7227 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
7228 &remote_protocol_packets
7229 [PACKET_qXfer_spu_read]);
7231 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
7232 &remote_protocol_packets
7233 [PACKET_qXfer_spu_write]);
7236 /* Only handle flash writes. */
7237 if (writebuf != NULL)
7243 case TARGET_OBJECT_FLASH:
7244 xfered = remote_flash_write (ops, offset, len, writebuf);
7248 else if (xfered == 0 && errno == 0)
7258 /* Map pre-existing objects onto letters. DO NOT do this for new
7259 objects!!! Instead specify new query packets. */
7262 case TARGET_OBJECT_AVR:
7266 case TARGET_OBJECT_AUXV:
7267 gdb_assert (annex == NULL);
7268 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
7269 &remote_protocol_packets[PACKET_qXfer_auxv]);
7271 case TARGET_OBJECT_AVAILABLE_FEATURES:
7272 return remote_read_qxfer
7273 (ops, "features", annex, readbuf, offset, len,
7274 &remote_protocol_packets[PACKET_qXfer_features]);
7276 case TARGET_OBJECT_LIBRARIES:
7277 return remote_read_qxfer
7278 (ops, "libraries", annex, readbuf, offset, len,
7279 &remote_protocol_packets[PACKET_qXfer_libraries]);
7281 case TARGET_OBJECT_MEMORY_MAP:
7282 gdb_assert (annex == NULL);
7283 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
7284 &remote_protocol_packets[PACKET_qXfer_memory_map]);
7290 /* Note: a zero OFFSET and LEN can be used to query the minimum
7292 if (offset == 0 && len == 0)
7293 return (get_remote_packet_size ());
7294 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
7295 large enough let the caller deal with it. */
7296 if (len < get_remote_packet_size ())
7298 len = get_remote_packet_size ();
7300 /* Except for querying the minimum buffer size, target must be open. */
7302 error (_("remote query is only available after target open"));
7304 gdb_assert (annex != NULL);
7305 gdb_assert (readbuf != NULL);
7311 /* We used one buffer char for the remote protocol q command and
7312 another for the query type. As the remote protocol encapsulation
7313 uses 4 chars plus one extra in case we are debugging
7314 (remote_debug), we have PBUFZIZ - 7 left to pack the query
7317 while (annex[i] && (i < (get_remote_packet_size () - 8)))
7319 /* Bad caller may have sent forbidden characters. */
7320 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
7325 gdb_assert (annex[i] == '\0');
7327 i = putpkt (rs->buf);
7331 getpkt (&rs->buf, &rs->buf_size, 0);
7332 strcpy ((char *) readbuf, rs->buf);
7334 return strlen ((char *) readbuf);
7338 remote_search_memory (struct target_ops* ops,
7339 CORE_ADDR start_addr, ULONGEST search_space_len,
7340 const gdb_byte *pattern, ULONGEST pattern_len,
7341 CORE_ADDR *found_addrp)
7343 struct remote_state *rs = get_remote_state ();
7344 int max_size = get_memory_write_packet_size ();
7345 struct packet_config *packet =
7346 &remote_protocol_packets[PACKET_qSearch_memory];
7347 /* number of packet bytes used to encode the pattern,
7348 this could be more than PATTERN_LEN due to escape characters */
7349 int escaped_pattern_len;
7350 /* amount of pattern that was encodable in the packet */
7351 int used_pattern_len;
7354 ULONGEST found_addr;
7356 /* Don't go to the target if we don't have to.
7357 This is done before checking packet->support to avoid the possibility that
7358 a success for this edge case means the facility works in general. */
7359 if (pattern_len > search_space_len)
7361 if (pattern_len == 0)
7363 *found_addrp = start_addr;
7367 /* If we already know the packet isn't supported, fall back to the simple
7368 way of searching memory. */
7370 if (packet->support == PACKET_DISABLE)
7372 /* Target doesn't provided special support, fall back and use the
7373 standard support (copy memory and do the search here). */
7374 return simple_search_memory (ops, start_addr, search_space_len,
7375 pattern, pattern_len, found_addrp);
7378 /* Insert header. */
7379 i = snprintf (rs->buf, max_size,
7380 "qSearch:memory:%s;%s;",
7381 paddr_nz (start_addr),
7382 phex_nz (search_space_len, sizeof (search_space_len)));
7383 max_size -= (i + 1);
7385 /* Escape as much data as fits into rs->buf. */
7386 escaped_pattern_len =
7387 remote_escape_output (pattern, pattern_len, (rs->buf + i),
7388 &used_pattern_len, max_size);
7390 /* Bail if the pattern is too large. */
7391 if (used_pattern_len != pattern_len)
7392 error ("Pattern is too large to transmit to remote target.");
7394 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
7395 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
7396 || packet_ok (rs->buf, packet) != PACKET_OK)
7398 /* The request may not have worked because the command is not
7399 supported. If so, fall back to the simple way. */
7400 if (packet->support == PACKET_DISABLE)
7402 return simple_search_memory (ops, start_addr, search_space_len,
7403 pattern, pattern_len, found_addrp);
7408 if (rs->buf[0] == '0')
7410 else if (rs->buf[0] == '1')
7413 if (rs->buf[1] != ',')
7414 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
7415 unpack_varlen_hex (rs->buf + 2, &found_addr);
7416 *found_addrp = found_addr;
7419 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
7425 remote_rcmd (char *command,
7426 struct ui_file *outbuf)
7428 struct remote_state *rs = get_remote_state ();
7432 error (_("remote rcmd is only available after target open"));
7434 /* Send a NULL command across as an empty command. */
7435 if (command == NULL)
7438 /* The query prefix. */
7439 strcpy (rs->buf, "qRcmd,");
7440 p = strchr (rs->buf, '\0');
7442 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/) > get_remote_packet_size ())
7443 error (_("\"monitor\" command ``%s'' is too long."), command);
7445 /* Encode the actual command. */
7446 bin2hex ((gdb_byte *) command, p, 0);
7448 if (putpkt (rs->buf) < 0)
7449 error (_("Communication problem with target."));
7451 /* get/display the response */
7456 /* XXX - see also tracepoint.c:remote_get_noisy_reply(). */
7458 getpkt (&rs->buf, &rs->buf_size, 0);
7461 error (_("Target does not support this command."));
7462 if (buf[0] == 'O' && buf[1] != 'K')
7464 remote_console_output (buf + 1); /* 'O' message from stub. */
7467 if (strcmp (buf, "OK") == 0)
7469 if (strlen (buf) == 3 && buf[0] == 'E'
7470 && isdigit (buf[1]) && isdigit (buf[2]))
7472 error (_("Protocol error with Rcmd"));
7474 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
7476 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
7477 fputc_unfiltered (c, outbuf);
7483 static VEC(mem_region_s) *
7484 remote_memory_map (struct target_ops *ops)
7486 VEC(mem_region_s) *result = NULL;
7487 char *text = target_read_stralloc (¤t_target,
7488 TARGET_OBJECT_MEMORY_MAP, NULL);
7492 struct cleanup *back_to = make_cleanup (xfree, text);
7493 result = parse_memory_map (text);
7494 do_cleanups (back_to);
7501 packet_command (char *args, int from_tty)
7503 struct remote_state *rs = get_remote_state ();
7506 error (_("command can only be used with remote target"));
7509 error (_("remote-packet command requires packet text as argument"));
7511 puts_filtered ("sending: ");
7512 print_packet (args);
7513 puts_filtered ("\n");
7516 getpkt (&rs->buf, &rs->buf_size, 0);
7517 puts_filtered ("received: ");
7518 print_packet (rs->buf);
7519 puts_filtered ("\n");
7523 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
7525 static void display_thread_info (struct gdb_ext_thread_info *info);
7527 static void threadset_test_cmd (char *cmd, int tty);
7529 static void threadalive_test (char *cmd, int tty);
7531 static void threadlist_test_cmd (char *cmd, int tty);
7533 int get_and_display_threadinfo (threadref *ref);
7535 static void threadinfo_test_cmd (char *cmd, int tty);
7537 static int thread_display_step (threadref *ref, void *context);
7539 static void threadlist_update_test_cmd (char *cmd, int tty);
7541 static void init_remote_threadtests (void);
7543 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
7546 threadset_test_cmd (char *cmd, int tty)
7548 int sample_thread = SAMPLE_THREAD;
7550 printf_filtered (_("Remote threadset test\n"));
7551 set_general_thread (sample_thread);
7556 threadalive_test (char *cmd, int tty)
7558 int sample_thread = SAMPLE_THREAD;
7559 int pid = ptid_get_pid (inferior_ptid);
7560 ptid_t ptid = ptid_build (pid, 0, sample_thread);
7562 if (remote_thread_alive (ptid))
7563 printf_filtered ("PASS: Thread alive test\n");
7565 printf_filtered ("FAIL: Thread alive test\n");
7568 void output_threadid (char *title, threadref *ref);
7571 output_threadid (char *title, threadref *ref)
7575 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
7577 printf_filtered ("%s %s\n", title, (&hexid[0]));
7581 threadlist_test_cmd (char *cmd, int tty)
7584 threadref nextthread;
7585 int done, result_count;
7586 threadref threadlist[3];
7588 printf_filtered ("Remote Threadlist test\n");
7589 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
7590 &result_count, &threadlist[0]))
7591 printf_filtered ("FAIL: threadlist test\n");
7594 threadref *scan = threadlist;
7595 threadref *limit = scan + result_count;
7597 while (scan < limit)
7598 output_threadid (" thread ", scan++);
7603 display_thread_info (struct gdb_ext_thread_info *info)
7605 output_threadid ("Threadid: ", &info->threadid);
7606 printf_filtered ("Name: %s\n ", info->shortname);
7607 printf_filtered ("State: %s\n", info->display);
7608 printf_filtered ("other: %s\n\n", info->more_display);
7612 get_and_display_threadinfo (threadref *ref)
7616 struct gdb_ext_thread_info threadinfo;
7618 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
7619 | TAG_MOREDISPLAY | TAG_DISPLAY;
7620 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
7621 display_thread_info (&threadinfo);
7626 threadinfo_test_cmd (char *cmd, int tty)
7628 int athread = SAMPLE_THREAD;
7632 int_to_threadref (&thread, athread);
7633 printf_filtered ("Remote Threadinfo test\n");
7634 if (!get_and_display_threadinfo (&thread))
7635 printf_filtered ("FAIL cannot get thread info\n");
7639 thread_display_step (threadref *ref, void *context)
7641 /* output_threadid(" threadstep ",ref); *//* simple test */
7642 return get_and_display_threadinfo (ref);
7646 threadlist_update_test_cmd (char *cmd, int tty)
7648 printf_filtered ("Remote Threadlist update test\n");
7649 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
7653 init_remote_threadtests (void)
7655 add_com ("tlist", class_obscure, threadlist_test_cmd, _("\
7656 Fetch and print the remote list of thread identifiers, one pkt only"));
7657 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
7658 _("Fetch and display info about one thread"));
7659 add_com ("tset", class_obscure, threadset_test_cmd,
7660 _("Test setting to a different thread"));
7661 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
7662 _("Iterate through updating all remote thread info"));
7663 add_com ("talive", class_obscure, threadalive_test,
7664 _(" Remote thread alive test "));
7669 /* Convert a thread ID to a string. Returns the string in a static
7673 remote_pid_to_str (ptid_t ptid)
7675 static char buf[64];
7676 struct remote_state *rs = get_remote_state ();
7678 if (ptid_equal (magic_null_ptid, ptid))
7680 xsnprintf (buf, sizeof buf, "Thread <main>");
7683 else if (remote_multi_process_p (rs)
7684 && ptid_get_tid (ptid) != 0 && ptid_get_pid (ptid) != 0)
7686 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
7687 ptid_get_pid (ptid), ptid_get_tid (ptid));
7690 else if (ptid_get_tid (ptid) != 0)
7692 xsnprintf (buf, sizeof buf, "Thread %ld",
7693 ptid_get_tid (ptid));
7697 return normal_pid_to_str (ptid);
7700 /* Get the address of the thread local variable in OBJFILE which is
7701 stored at OFFSET within the thread local storage for thread PTID. */
7704 remote_get_thread_local_address (ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
7706 if (remote_protocol_packets[PACKET_qGetTLSAddr].support != PACKET_DISABLE)
7708 struct remote_state *rs = get_remote_state ();
7710 char *endp = rs->buf + get_remote_packet_size ();
7711 enum packet_result result;
7713 strcpy (p, "qGetTLSAddr:");
7715 p = write_ptid (p, endp, ptid);
7717 p += hexnumstr (p, offset);
7719 p += hexnumstr (p, lm);
7723 getpkt (&rs->buf, &rs->buf_size, 0);
7724 result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_qGetTLSAddr]);
7725 if (result == PACKET_OK)
7729 unpack_varlen_hex (rs->buf, &result);
7732 else if (result == PACKET_UNKNOWN)
7733 throw_error (TLS_GENERIC_ERROR,
7734 _("Remote target doesn't support qGetTLSAddr packet"));
7736 throw_error (TLS_GENERIC_ERROR,
7737 _("Remote target failed to process qGetTLSAddr request"));
7740 throw_error (TLS_GENERIC_ERROR,
7741 _("TLS not supported or disabled on this target"));
7746 /* Support for inferring a target description based on the current
7747 architecture and the size of a 'g' packet. While the 'g' packet
7748 can have any size (since optional registers can be left off the
7749 end), some sizes are easily recognizable given knowledge of the
7750 approximate architecture. */
7752 struct remote_g_packet_guess
7755 const struct target_desc *tdesc;
7757 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
7758 DEF_VEC_O(remote_g_packet_guess_s);
7760 struct remote_g_packet_data
7762 VEC(remote_g_packet_guess_s) *guesses;
7765 static struct gdbarch_data *remote_g_packet_data_handle;
7768 remote_g_packet_data_init (struct obstack *obstack)
7770 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
7774 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
7775 const struct target_desc *tdesc)
7777 struct remote_g_packet_data *data
7778 = gdbarch_data (gdbarch, remote_g_packet_data_handle);
7779 struct remote_g_packet_guess new_guess, *guess;
7782 gdb_assert (tdesc != NULL);
7785 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
7787 if (guess->bytes == bytes)
7788 internal_error (__FILE__, __LINE__,
7789 "Duplicate g packet description added for size %d",
7792 new_guess.bytes = bytes;
7793 new_guess.tdesc = tdesc;
7794 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
7797 static const struct target_desc *
7798 remote_read_description (struct target_ops *target)
7800 struct remote_g_packet_data *data
7801 = gdbarch_data (target_gdbarch, remote_g_packet_data_handle);
7803 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
7805 struct remote_g_packet_guess *guess;
7807 int bytes = send_g_packet ();
7810 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
7812 if (guess->bytes == bytes)
7813 return guess->tdesc;
7815 /* We discard the g packet. A minor optimization would be to
7816 hold on to it, and fill the register cache once we have selected
7817 an architecture, but it's too tricky to do safely. */
7823 /* Remote file transfer support. This is host-initiated I/O, not
7824 target-initiated; for target-initiated, see remote-fileio.c. */
7826 /* If *LEFT is at least the length of STRING, copy STRING to
7827 *BUFFER, update *BUFFER to point to the new end of the buffer, and
7828 decrease *LEFT. Otherwise raise an error. */
7831 remote_buffer_add_string (char **buffer, int *left, char *string)
7833 int len = strlen (string);
7836 error (_("Packet too long for target."));
7838 memcpy (*buffer, string, len);
7842 /* NUL-terminate the buffer as a convenience, if there is
7848 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
7849 *BUFFER, update *BUFFER to point to the new end of the buffer, and
7850 decrease *LEFT. Otherwise raise an error. */
7853 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
7856 if (2 * len > *left)
7857 error (_("Packet too long for target."));
7859 bin2hex (bytes, *buffer, len);
7863 /* NUL-terminate the buffer as a convenience, if there is
7869 /* If *LEFT is large enough, convert VALUE to hex and add it to
7870 *BUFFER, update *BUFFER to point to the new end of the buffer, and
7871 decrease *LEFT. Otherwise raise an error. */
7874 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
7876 int len = hexnumlen (value);
7879 error (_("Packet too long for target."));
7881 hexnumstr (*buffer, value);
7885 /* NUL-terminate the buffer as a convenience, if there is
7891 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
7892 value, *REMOTE_ERRNO to the remote error number or zero if none
7893 was included, and *ATTACHMENT to point to the start of the annex
7894 if any. The length of the packet isn't needed here; there may
7895 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
7897 Return 0 if the packet could be parsed, -1 if it could not. If
7898 -1 is returned, the other variables may not be initialized. */
7901 remote_hostio_parse_result (char *buffer, int *retcode,
7902 int *remote_errno, char **attachment)
7909 if (buffer[0] != 'F')
7913 *retcode = strtol (&buffer[1], &p, 16);
7914 if (errno != 0 || p == &buffer[1])
7917 /* Check for ",errno". */
7921 *remote_errno = strtol (p + 1, &p2, 16);
7922 if (errno != 0 || p + 1 == p2)
7927 /* Check for ";attachment". If there is no attachment, the
7928 packet should end here. */
7931 *attachment = p + 1;
7934 else if (*p == '\0')
7940 /* Send a prepared I/O packet to the target and read its response.
7941 The prepared packet is in the global RS->BUF before this function
7942 is called, and the answer is there when we return.
7944 COMMAND_BYTES is the length of the request to send, which may include
7945 binary data. WHICH_PACKET is the packet configuration to check
7946 before attempting a packet. If an error occurs, *REMOTE_ERRNO
7947 is set to the error number and -1 is returned. Otherwise the value
7948 returned by the function is returned.
7950 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
7951 attachment is expected; an error will be reported if there's a
7952 mismatch. If one is found, *ATTACHMENT will be set to point into
7953 the packet buffer and *ATTACHMENT_LEN will be set to the
7954 attachment's length. */
7957 remote_hostio_send_command (int command_bytes, int which_packet,
7958 int *remote_errno, char **attachment,
7959 int *attachment_len)
7961 struct remote_state *rs = get_remote_state ();
7962 int ret, bytes_read;
7963 char *attachment_tmp;
7966 || remote_protocol_packets[which_packet].support == PACKET_DISABLE)
7968 *remote_errno = FILEIO_ENOSYS;
7972 putpkt_binary (rs->buf, command_bytes);
7973 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
7975 /* If it timed out, something is wrong. Don't try to parse the
7979 *remote_errno = FILEIO_EINVAL;
7983 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
7986 *remote_errno = FILEIO_EINVAL;
7988 case PACKET_UNKNOWN:
7989 *remote_errno = FILEIO_ENOSYS;
7995 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
7998 *remote_errno = FILEIO_EINVAL;
8002 /* Make sure we saw an attachment if and only if we expected one. */
8003 if ((attachment_tmp == NULL && attachment != NULL)
8004 || (attachment_tmp != NULL && attachment == NULL))
8006 *remote_errno = FILEIO_EINVAL;
8010 /* If an attachment was found, it must point into the packet buffer;
8011 work out how many bytes there were. */
8012 if (attachment_tmp != NULL)
8014 *attachment = attachment_tmp;
8015 *attachment_len = bytes_read - (*attachment - rs->buf);
8021 /* Open FILENAME on the remote target, using FLAGS and MODE. Return a
8022 remote file descriptor, or -1 if an error occurs (and set
8026 remote_hostio_open (const char *filename, int flags, int mode,
8029 struct remote_state *rs = get_remote_state ();
8031 int left = get_remote_packet_size () - 1;
8033 remote_buffer_add_string (&p, &left, "vFile:open:");
8035 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
8037 remote_buffer_add_string (&p, &left, ",");
8039 remote_buffer_add_int (&p, &left, flags);
8040 remote_buffer_add_string (&p, &left, ",");
8042 remote_buffer_add_int (&p, &left, mode);
8044 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
8045 remote_errno, NULL, NULL);
8048 /* Write up to LEN bytes from WRITE_BUF to FD on the remote target.
8049 Return the number of bytes written, or -1 if an error occurs (and
8050 set *REMOTE_ERRNO). */
8053 remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
8054 ULONGEST offset, int *remote_errno)
8056 struct remote_state *rs = get_remote_state ();
8058 int left = get_remote_packet_size ();
8061 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
8063 remote_buffer_add_int (&p, &left, fd);
8064 remote_buffer_add_string (&p, &left, ",");
8066 remote_buffer_add_int (&p, &left, offset);
8067 remote_buffer_add_string (&p, &left, ",");
8069 p += remote_escape_output (write_buf, len, p, &out_len,
8070 get_remote_packet_size () - (p - rs->buf));
8072 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
8073 remote_errno, NULL, NULL);
8076 /* Read up to LEN bytes FD on the remote target into READ_BUF
8077 Return the number of bytes read, or -1 if an error occurs (and
8078 set *REMOTE_ERRNO). */
8081 remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
8082 ULONGEST offset, int *remote_errno)
8084 struct remote_state *rs = get_remote_state ();
8087 int left = get_remote_packet_size ();
8088 int ret, attachment_len;
8091 remote_buffer_add_string (&p, &left, "vFile:pread:");
8093 remote_buffer_add_int (&p, &left, fd);
8094 remote_buffer_add_string (&p, &left, ",");
8096 remote_buffer_add_int (&p, &left, len);
8097 remote_buffer_add_string (&p, &left, ",");
8099 remote_buffer_add_int (&p, &left, offset);
8101 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
8102 remote_errno, &attachment,
8108 read_len = remote_unescape_input (attachment, attachment_len,
8110 if (read_len != ret)
8111 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
8116 /* Close FD on the remote target. Return 0, or -1 if an error occurs
8117 (and set *REMOTE_ERRNO). */
8120 remote_hostio_close (int fd, int *remote_errno)
8122 struct remote_state *rs = get_remote_state ();
8124 int left = get_remote_packet_size () - 1;
8126 remote_buffer_add_string (&p, &left, "vFile:close:");
8128 remote_buffer_add_int (&p, &left, fd);
8130 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
8131 remote_errno, NULL, NULL);
8134 /* Unlink FILENAME on the remote target. Return 0, or -1 if an error
8135 occurs (and set *REMOTE_ERRNO). */
8138 remote_hostio_unlink (const char *filename, int *remote_errno)
8140 struct remote_state *rs = get_remote_state ();
8142 int left = get_remote_packet_size () - 1;
8144 remote_buffer_add_string (&p, &left, "vFile:unlink:");
8146 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
8149 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
8150 remote_errno, NULL, NULL);
8154 remote_fileio_errno_to_host (int errnum)
8178 case FILEIO_ENOTDIR:
8198 case FILEIO_ENAMETOOLONG:
8199 return ENAMETOOLONG;
8205 remote_hostio_error (int errnum)
8207 int host_error = remote_fileio_errno_to_host (errnum);
8209 if (host_error == -1)
8210 error (_("Unknown remote I/O error %d"), errnum);
8212 error (_("Remote I/O error: %s"), safe_strerror (host_error));
8216 fclose_cleanup (void *file)
8222 remote_hostio_close_cleanup (void *opaque)
8224 int fd = *(int *) opaque;
8227 remote_hostio_close (fd, &remote_errno);
8232 remote_bfd_iovec_open (struct bfd *abfd, void *open_closure)
8234 const char *filename = bfd_get_filename (abfd);
8235 int fd, remote_errno;
8238 gdb_assert (remote_filename_p (filename));
8240 fd = remote_hostio_open (filename + 7, FILEIO_O_RDONLY, 0, &remote_errno);
8243 errno = remote_fileio_errno_to_host (remote_errno);
8244 bfd_set_error (bfd_error_system_call);
8248 stream = xmalloc (sizeof (int));
8254 remote_bfd_iovec_close (struct bfd *abfd, void *stream)
8256 int fd = *(int *)stream;
8261 /* Ignore errors on close; these may happen if the remote
8262 connection was already torn down. */
8263 remote_hostio_close (fd, &remote_errno);
8269 remote_bfd_iovec_pread (struct bfd *abfd, void *stream, void *buf,
8270 file_ptr nbytes, file_ptr offset)
8272 int fd = *(int *)stream;
8274 file_ptr pos, bytes;
8277 while (nbytes > pos)
8279 bytes = remote_hostio_pread (fd, (char *)buf + pos, nbytes - pos,
8280 offset + pos, &remote_errno);
8282 /* Success, but no bytes, means end-of-file. */
8286 errno = remote_fileio_errno_to_host (remote_errno);
8287 bfd_set_error (bfd_error_system_call);
8298 remote_bfd_iovec_stat (struct bfd *abfd, void *stream, struct stat *sb)
8300 /* FIXME: We should probably implement remote_hostio_stat. */
8301 sb->st_size = INT_MAX;
8306 remote_filename_p (const char *filename)
8308 return strncmp (filename, "remote:", 7) == 0;
8312 remote_bfd_open (const char *remote_file, const char *target)
8314 return bfd_openr_iovec (remote_file, target,
8315 remote_bfd_iovec_open, NULL,
8316 remote_bfd_iovec_pread,
8317 remote_bfd_iovec_close,
8318 remote_bfd_iovec_stat);
8322 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
8324 struct cleanup *back_to, *close_cleanup;
8325 int retcode, fd, remote_errno, bytes, io_size;
8328 int bytes_in_buffer;
8333 error (_("command can only be used with remote target"));
8335 file = fopen (local_file, "rb");
8337 perror_with_name (local_file);
8338 back_to = make_cleanup (fclose_cleanup, file);
8340 fd = remote_hostio_open (remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
8342 0700, &remote_errno);
8344 remote_hostio_error (remote_errno);
8346 /* Send up to this many bytes at once. They won't all fit in the
8347 remote packet limit, so we'll transfer slightly fewer. */
8348 io_size = get_remote_packet_size ();
8349 buffer = xmalloc (io_size);
8350 make_cleanup (xfree, buffer);
8352 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
8354 bytes_in_buffer = 0;
8357 while (bytes_in_buffer || !saw_eof)
8361 bytes = fread (buffer + bytes_in_buffer, 1, io_size - bytes_in_buffer,
8366 error (_("Error reading %s."), local_file);
8369 /* EOF. Unless there is something still in the
8370 buffer from the last iteration, we are done. */
8372 if (bytes_in_buffer == 0)
8380 bytes += bytes_in_buffer;
8381 bytes_in_buffer = 0;
8383 retcode = remote_hostio_pwrite (fd, buffer, bytes, offset, &remote_errno);
8386 remote_hostio_error (remote_errno);
8387 else if (retcode == 0)
8388 error (_("Remote write of %d bytes returned 0!"), bytes);
8389 else if (retcode < bytes)
8391 /* Short write. Save the rest of the read data for the next
8393 bytes_in_buffer = bytes - retcode;
8394 memmove (buffer, buffer + retcode, bytes_in_buffer);
8400 discard_cleanups (close_cleanup);
8401 if (remote_hostio_close (fd, &remote_errno))
8402 remote_hostio_error (remote_errno);
8405 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
8406 do_cleanups (back_to);
8410 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
8412 struct cleanup *back_to, *close_cleanup;
8413 int retcode, fd, remote_errno, bytes, io_size;
8419 error (_("command can only be used with remote target"));
8421 fd = remote_hostio_open (remote_file, FILEIO_O_RDONLY, 0, &remote_errno);
8423 remote_hostio_error (remote_errno);
8425 file = fopen (local_file, "wb");
8427 perror_with_name (local_file);
8428 back_to = make_cleanup (fclose_cleanup, file);
8430 /* Send up to this many bytes at once. They won't all fit in the
8431 remote packet limit, so we'll transfer slightly fewer. */
8432 io_size = get_remote_packet_size ();
8433 buffer = xmalloc (io_size);
8434 make_cleanup (xfree, buffer);
8436 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
8441 bytes = remote_hostio_pread (fd, buffer, io_size, offset, &remote_errno);
8443 /* Success, but no bytes, means end-of-file. */
8446 remote_hostio_error (remote_errno);
8450 bytes = fwrite (buffer, 1, bytes, file);
8452 perror_with_name (local_file);
8455 discard_cleanups (close_cleanup);
8456 if (remote_hostio_close (fd, &remote_errno))
8457 remote_hostio_error (remote_errno);
8460 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
8461 do_cleanups (back_to);
8465 remote_file_delete (const char *remote_file, int from_tty)
8467 int retcode, remote_errno;
8470 error (_("command can only be used with remote target"));
8472 retcode = remote_hostio_unlink (remote_file, &remote_errno);
8474 remote_hostio_error (remote_errno);
8477 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
8481 remote_put_command (char *args, int from_tty)
8483 struct cleanup *back_to;
8487 error_no_arg (_("file to put"));
8489 argv = gdb_buildargv (args);
8490 back_to = make_cleanup_freeargv (argv);
8491 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
8492 error (_("Invalid parameters to remote put"));
8494 remote_file_put (argv[0], argv[1], from_tty);
8496 do_cleanups (back_to);
8500 remote_get_command (char *args, int from_tty)
8502 struct cleanup *back_to;
8506 error_no_arg (_("file to get"));
8508 argv = gdb_buildargv (args);
8509 back_to = make_cleanup_freeargv (argv);
8510 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
8511 error (_("Invalid parameters to remote get"));
8513 remote_file_get (argv[0], argv[1], from_tty);
8515 do_cleanups (back_to);
8519 remote_delete_command (char *args, int from_tty)
8521 struct cleanup *back_to;
8525 error_no_arg (_("file to delete"));
8527 argv = gdb_buildargv (args);
8528 back_to = make_cleanup_freeargv (argv);
8529 if (argv[0] == NULL || argv[1] != NULL)
8530 error (_("Invalid parameters to remote delete"));
8532 remote_file_delete (argv[0], from_tty);
8534 do_cleanups (back_to);
8538 remote_command (char *args, int from_tty)
8540 help_list (remote_cmdlist, "remote ", -1, gdb_stdout);
8543 static int remote_target_can_reverse = 1;
8546 remote_can_execute_reverse (void)
8548 return remote_target_can_reverse;
8552 remote_supports_non_stop (void)
8558 init_remote_ops (void)
8560 remote_ops.to_shortname = "remote";
8561 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
8563 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
8564 Specify the serial device it is connected to\n\
8565 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
8566 remote_ops.to_open = remote_open;
8567 remote_ops.to_close = remote_close;
8568 remote_ops.to_detach = remote_detach;
8569 remote_ops.to_disconnect = remote_disconnect;
8570 remote_ops.to_resume = remote_resume;
8571 remote_ops.to_wait = remote_wait;
8572 remote_ops.to_fetch_registers = remote_fetch_registers;
8573 remote_ops.to_store_registers = remote_store_registers;
8574 remote_ops.to_prepare_to_store = remote_prepare_to_store;
8575 remote_ops.deprecated_xfer_memory = remote_xfer_memory;
8576 remote_ops.to_files_info = remote_files_info;
8577 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
8578 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
8579 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
8580 remote_ops.to_stopped_data_address = remote_stopped_data_address;
8581 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
8582 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
8583 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
8584 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
8585 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
8586 remote_ops.to_kill = remote_kill;
8587 remote_ops.to_load = generic_load;
8588 remote_ops.to_mourn_inferior = remote_mourn;
8589 remote_ops.to_thread_alive = remote_thread_alive;
8590 remote_ops.to_find_new_threads = remote_threads_info;
8591 remote_ops.to_pid_to_str = remote_pid_to_str;
8592 remote_ops.to_extra_thread_info = remote_threads_extra_info;
8593 remote_ops.to_stop = remote_stop;
8594 remote_ops.to_xfer_partial = remote_xfer_partial;
8595 remote_ops.to_rcmd = remote_rcmd;
8596 remote_ops.to_log_command = serial_log_command;
8597 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
8598 remote_ops.to_stratum = process_stratum;
8599 remote_ops.to_has_all_memory = 1;
8600 remote_ops.to_has_memory = 1;
8601 remote_ops.to_has_stack = 1;
8602 remote_ops.to_has_registers = 1;
8603 remote_ops.to_has_execution = 1;
8604 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
8605 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
8606 remote_ops.to_magic = OPS_MAGIC;
8607 remote_ops.to_memory_map = remote_memory_map;
8608 remote_ops.to_flash_erase = remote_flash_erase;
8609 remote_ops.to_flash_done = remote_flash_done;
8610 remote_ops.to_read_description = remote_read_description;
8611 remote_ops.to_search_memory = remote_search_memory;
8612 remote_ops.to_can_async_p = remote_can_async_p;
8613 remote_ops.to_is_async_p = remote_is_async_p;
8614 remote_ops.to_async = remote_async;
8615 remote_ops.to_async_mask = remote_async_mask;
8616 remote_ops.to_terminal_inferior = remote_terminal_inferior;
8617 remote_ops.to_terminal_ours = remote_terminal_ours;
8618 remote_ops.to_supports_non_stop = remote_supports_non_stop;
8621 /* Set up the extended remote vector by making a copy of the standard
8622 remote vector and adding to it. */
8625 init_extended_remote_ops (void)
8627 extended_remote_ops = remote_ops;
8629 extended_remote_ops.to_shortname = "extended-remote";
8630 extended_remote_ops.to_longname =
8631 "Extended remote serial target in gdb-specific protocol";
8632 extended_remote_ops.to_doc =
8633 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
8634 Specify the serial device it is connected to (e.g. /dev/ttya).";
8635 extended_remote_ops.to_open = extended_remote_open;
8636 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
8637 extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
8638 extended_remote_ops.to_detach = extended_remote_detach;
8639 extended_remote_ops.to_attach = extended_remote_attach;
8640 extended_remote_ops.to_kill = extended_remote_kill;
8644 remote_can_async_p (void)
8646 if (!target_async_permitted)
8647 /* We only enable async when the user specifically asks for it. */
8650 /* We're async whenever the serial device is. */
8651 return remote_async_mask_value && serial_can_async_p (remote_desc);
8655 remote_is_async_p (void)
8657 if (!target_async_permitted)
8658 /* We only enable async when the user specifically asks for it. */
8661 /* We're async whenever the serial device is. */
8662 return remote_async_mask_value && serial_is_async_p (remote_desc);
8665 /* Pass the SERIAL event on and up to the client. One day this code
8666 will be able to delay notifying the client of an event until the
8667 point where an entire packet has been received. */
8669 static void (*async_client_callback) (enum inferior_event_type event_type,
8671 static void *async_client_context;
8672 static serial_event_ftype remote_async_serial_handler;
8675 remote_async_serial_handler (struct serial *scb, void *context)
8677 /* Don't propogate error information up to the client. Instead let
8678 the client find out about the error by querying the target. */
8679 async_client_callback (INF_REG_EVENT, async_client_context);
8683 remote_async_inferior_event_handler (gdb_client_data data)
8685 inferior_event_handler (INF_REG_EVENT, NULL);
8689 remote_async_get_pending_events_handler (gdb_client_data data)
8691 remote_get_pending_stop_replies ();
8695 remote_async (void (*callback) (enum inferior_event_type event_type,
8696 void *context), void *context)
8698 if (remote_async_mask_value == 0)
8699 internal_error (__FILE__, __LINE__,
8700 _("Calling remote_async when async is masked"));
8702 if (callback != NULL)
8704 serial_async (remote_desc, remote_async_serial_handler, NULL);
8705 async_client_callback = callback;
8706 async_client_context = context;
8709 serial_async (remote_desc, NULL, NULL);
8713 remote_async_mask (int new_mask)
8715 int curr_mask = remote_async_mask_value;
8716 remote_async_mask_value = new_mask;
8721 set_remote_cmd (char *args, int from_tty)
8723 help_list (remote_set_cmdlist, "set remote ", -1, gdb_stdout);
8727 show_remote_cmd (char *args, int from_tty)
8729 /* We can't just use cmd_show_list here, because we want to skip
8730 the redundant "show remote Z-packet" and the legacy aliases. */
8731 struct cleanup *showlist_chain;
8732 struct cmd_list_element *list = remote_show_cmdlist;
8734 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
8735 for (; list != NULL; list = list->next)
8736 if (strcmp (list->name, "Z-packet") == 0)
8738 else if (list->type == not_set_cmd)
8739 /* Alias commands are exactly like the original, except they
8740 don't have the normal type. */
8744 struct cleanup *option_chain
8745 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
8746 ui_out_field_string (uiout, "name", list->name);
8747 ui_out_text (uiout, ": ");
8748 if (list->type == show_cmd)
8749 do_setshow_command ((char *) NULL, from_tty, list);
8751 cmd_func (list, NULL, from_tty);
8752 /* Close the tuple. */
8753 do_cleanups (option_chain);
8756 /* Close the tuple. */
8757 do_cleanups (showlist_chain);
8761 /* Function to be called whenever a new objfile (shlib) is detected. */
8763 remote_new_objfile (struct objfile *objfile)
8765 if (remote_desc != 0) /* Have a remote connection. */
8766 remote_check_symbols (objfile);
8770 _initialize_remote (void)
8772 struct remote_state *rs;
8774 /* architecture specific data */
8775 remote_gdbarch_data_handle =
8776 gdbarch_data_register_post_init (init_remote_state);
8777 remote_g_packet_data_handle =
8778 gdbarch_data_register_pre_init (remote_g_packet_data_init);
8780 /* Initialize the per-target state. At the moment there is only one
8781 of these, not one per target. Only one target is active at a
8782 time. The default buffer size is unimportant; it will be expanded
8783 whenever a larger buffer is needed. */
8784 rs = get_remote_state_raw ();
8786 rs->buf = xmalloc (rs->buf_size);
8789 add_target (&remote_ops);
8791 init_extended_remote_ops ();
8792 add_target (&extended_remote_ops);
8794 /* Hook into new objfile notification. */
8795 observer_attach_new_objfile (remote_new_objfile);
8797 /* Set up signal handlers. */
8798 sigint_remote_token =
8799 create_async_signal_handler (async_remote_interrupt, NULL);
8800 sigint_remote_twice_token =
8801 create_async_signal_handler (inferior_event_handler_wrapper, NULL);
8804 init_remote_threadtests ();
8807 /* set/show remote ... */
8809 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
8810 Remote protocol specific variables\n\
8811 Configure various remote-protocol specific variables such as\n\
8812 the packets being used"),
8813 &remote_set_cmdlist, "set remote ",
8814 0 /* allow-unknown */, &setlist);
8815 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
8816 Remote protocol specific variables\n\
8817 Configure various remote-protocol specific variables such as\n\
8818 the packets being used"),
8819 &remote_show_cmdlist, "show remote ",
8820 0 /* allow-unknown */, &showlist);
8822 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
8823 Compare section data on target to the exec file.\n\
8824 Argument is a single section name (default: all loaded sections)."),
8827 add_cmd ("packet", class_maintenance, packet_command, _("\
8828 Send an arbitrary packet to a remote target.\n\
8829 maintenance packet TEXT\n\
8830 If GDB is talking to an inferior via the GDB serial protocol, then\n\
8831 this command sends the string TEXT to the inferior, and displays the\n\
8832 response packet. GDB supplies the initial `$' character, and the\n\
8833 terminating `#' character and checksum."),
8836 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
8837 Set whether to send break if interrupted."), _("\
8838 Show whether to send break if interrupted."), _("\
8839 If set, a break, instead of a cntrl-c, is sent to the remote target."),
8840 NULL, NULL, /* FIXME: i18n: Whether to send break if interrupted is %s. */
8841 &setlist, &showlist);
8843 /* Install commands for configuring memory read/write packets. */
8845 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
8846 Set the maximum number of bytes per memory write packet (deprecated)."),
8848 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
8849 Show the maximum number of bytes per memory write packet (deprecated)."),
8851 add_cmd ("memory-write-packet-size", no_class,
8852 set_memory_write_packet_size, _("\
8853 Set the maximum number of bytes per memory-write packet.\n\
8854 Specify the number of bytes in a packet or 0 (zero) for the\n\
8855 default packet size. The actual limit is further reduced\n\
8856 dependent on the target. Specify ``fixed'' to disable the\n\
8857 further restriction and ``limit'' to enable that restriction."),
8858 &remote_set_cmdlist);
8859 add_cmd ("memory-read-packet-size", no_class,
8860 set_memory_read_packet_size, _("\
8861 Set the maximum number of bytes per memory-read packet.\n\
8862 Specify the number of bytes in a packet or 0 (zero) for the\n\
8863 default packet size. The actual limit is further reduced\n\
8864 dependent on the target. Specify ``fixed'' to disable the\n\
8865 further restriction and ``limit'' to enable that restriction."),
8866 &remote_set_cmdlist);
8867 add_cmd ("memory-write-packet-size", no_class,
8868 show_memory_write_packet_size,
8869 _("Show the maximum number of bytes per memory-write packet."),
8870 &remote_show_cmdlist);
8871 add_cmd ("memory-read-packet-size", no_class,
8872 show_memory_read_packet_size,
8873 _("Show the maximum number of bytes per memory-read packet."),
8874 &remote_show_cmdlist);
8876 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
8877 &remote_hw_watchpoint_limit, _("\
8878 Set the maximum number of target hardware watchpoints."), _("\
8879 Show the maximum number of target hardware watchpoints."), _("\
8880 Specify a negative limit for unlimited."),
8881 NULL, NULL, /* FIXME: i18n: The maximum number of target hardware watchpoints is %s. */
8882 &remote_set_cmdlist, &remote_show_cmdlist);
8883 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
8884 &remote_hw_breakpoint_limit, _("\
8885 Set the maximum number of target hardware breakpoints."), _("\
8886 Show the maximum number of target hardware breakpoints."), _("\
8887 Specify a negative limit for unlimited."),
8888 NULL, NULL, /* FIXME: i18n: The maximum number of target hardware breakpoints is %s. */
8889 &remote_set_cmdlist, &remote_show_cmdlist);
8891 add_setshow_integer_cmd ("remoteaddresssize", class_obscure,
8892 &remote_address_size, _("\
8893 Set the maximum size of the address (in bits) in a memory packet."), _("\
8894 Show the maximum size of the address (in bits) in a memory packet."), NULL,
8896 NULL, /* FIXME: i18n: */
8897 &setlist, &showlist);
8899 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
8900 "X", "binary-download", 1);
8902 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
8903 "vCont", "verbose-resume", 0);
8905 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
8906 "QPassSignals", "pass-signals", 0);
8908 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
8909 "qSymbol", "symbol-lookup", 0);
8911 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
8912 "P", "set-register", 1);
8914 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
8915 "p", "fetch-register", 1);
8917 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
8918 "Z0", "software-breakpoint", 0);
8920 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
8921 "Z1", "hardware-breakpoint", 0);
8923 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
8924 "Z2", "write-watchpoint", 0);
8926 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
8927 "Z3", "read-watchpoint", 0);
8929 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
8930 "Z4", "access-watchpoint", 0);
8932 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
8933 "qXfer:auxv:read", "read-aux-vector", 0);
8935 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
8936 "qXfer:features:read", "target-features", 0);
8938 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
8939 "qXfer:libraries:read", "library-info", 0);
8941 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
8942 "qXfer:memory-map:read", "memory-map", 0);
8944 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
8945 "qXfer:spu:read", "read-spu-object", 0);
8947 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
8948 "qXfer:spu:write", "write-spu-object", 0);
8950 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
8951 "qGetTLSAddr", "get-thread-local-storage-address",
8954 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
8955 "qSupported", "supported-packets", 0);
8957 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
8958 "qSearch:memory", "search-memory", 0);
8960 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
8961 "vFile:open", "hostio-open", 0);
8963 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
8964 "vFile:pread", "hostio-pread", 0);
8966 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
8967 "vFile:pwrite", "hostio-pwrite", 0);
8969 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
8970 "vFile:close", "hostio-close", 0);
8972 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
8973 "vFile:unlink", "hostio-unlink", 0);
8975 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
8976 "vAttach", "attach", 0);
8978 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
8981 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
8982 "QStartNoAckMode", "noack", 0);
8984 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
8985 "vKill", "kill", 0);
8987 /* Keep the old ``set remote Z-packet ...'' working. Each individual
8988 Z sub-packet has its own set and show commands, but users may
8989 have sets to this variable in their .gdbinit files (or in their
8991 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
8992 &remote_Z_packet_detect, _("\
8993 Set use of remote protocol `Z' packets"), _("\
8994 Show use of remote protocol `Z' packets "), _("\
8995 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
8997 set_remote_protocol_Z_packet_cmd,
8998 show_remote_protocol_Z_packet_cmd, /* FIXME: i18n: Use of remote protocol `Z' packets is %s. */
8999 &remote_set_cmdlist, &remote_show_cmdlist);
9001 add_prefix_cmd ("remote", class_files, remote_command, _("\
9002 Manipulate files on the remote system\n\
9003 Transfer files to and from the remote target system."),
9004 &remote_cmdlist, "remote ",
9005 0 /* allow-unknown */, &cmdlist);
9007 add_cmd ("put", class_files, remote_put_command,
9008 _("Copy a local file to the remote system."),
9011 add_cmd ("get", class_files, remote_get_command,
9012 _("Copy a remote file to the local system."),
9015 add_cmd ("delete", class_files, remote_delete_command,
9016 _("Delete a remote file."),
9019 remote_exec_file = xstrdup ("");
9020 add_setshow_string_noescape_cmd ("exec-file", class_files,
9021 &remote_exec_file, _("\
9022 Set the remote pathname for \"run\""), _("\
9023 Show the remote pathname for \"run\""), NULL, NULL, NULL,
9024 &remote_set_cmdlist, &remote_show_cmdlist);
9026 /* Eventually initialize fileio. See fileio.c */
9027 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
9029 /* Take advantage of the fact that the LWP field is not used, to tag
9030 special ptids with it set to != 0. */
9031 magic_null_ptid = ptid_build (42000, 1, -1);
9032 not_sent_ptid = ptid_build (42000, 1, -2);
9033 any_thread_ptid = ptid_build (42000, 1, 0);