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, 2009,
5 2010, 2011 Free Software Foundation, Inc.
7 This file is part of GDB.
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 3 of the License, or
12 (at your option) any later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with this program. If not, see <http://www.gnu.org/licenses/>. */
22 /* See the GDB User Guide for details of the GDB remote protocol. */
25 #include "gdb_string.h"
31 #include "exceptions.h"
33 /*#include "terminal.h" */
36 #include "gdb-stabs.h"
37 #include "gdbthread.h"
41 #include "gdb_assert.h"
44 #include "cli/cli-decode.h"
45 #include "cli/cli-setshow.h"
46 #include "target-descriptions.h"
51 #include "event-loop.h"
52 #include "event-top.h"
58 #include "gdbcore.h" /* for exec_bfd */
60 #include "remote-fileio.h"
61 #include "gdb/fileio.h"
63 #include "xml-support.h"
65 #include "memory-map.h"
67 #include "tracepoint.h"
71 /* Temp hacks for tracepoint encoding migration. */
72 static char *target_buf;
73 static long target_buf_size;
75 encode_actions (struct breakpoint *t, struct bp_location *tloc,
76 char ***tdp_actions, char ***stepping_actions);
78 /* The size to align memory write packets, when practical. The protocol
79 does not guarantee any alignment, and gdb will generate short
80 writes and unaligned writes, but even as a best-effort attempt this
81 can improve bulk transfers. For instance, if a write is misaligned
82 relative to the target's data bus, the stub may need to make an extra
83 round trip fetching data from the target. This doesn't make a
84 huge difference, but it's easy to do, so we try to be helpful.
86 The alignment chosen is arbitrary; usually data bus width is
87 important here, not the possibly larger cache line size. */
88 enum { REMOTE_ALIGN_WRITES = 16 };
90 /* Prototypes for local functions. */
91 static void cleanup_sigint_signal_handler (void *dummy);
92 static void initialize_sigint_signal_handler (void);
93 static int getpkt_sane (char **buf, long *sizeof_buf, int forever);
94 static int getpkt_or_notif_sane (char **buf, long *sizeof_buf,
97 static void handle_remote_sigint (int);
98 static void handle_remote_sigint_twice (int);
99 static void async_remote_interrupt (gdb_client_data);
100 void async_remote_interrupt_twice (gdb_client_data);
102 static void remote_files_info (struct target_ops *ignore);
104 static void remote_prepare_to_store (struct regcache *regcache);
106 static void remote_open (char *name, int from_tty);
108 static void extended_remote_open (char *name, int from_tty);
110 static void remote_open_1 (char *, int, struct target_ops *, int extended_p);
112 static void remote_close (int quitting);
114 static void remote_mourn (struct target_ops *ops);
116 static void extended_remote_restart (void);
118 static void extended_remote_mourn (struct target_ops *);
120 static void remote_mourn_1 (struct target_ops *);
122 static void remote_send (char **buf, long *sizeof_buf_p);
124 static int readchar (int timeout);
126 static void remote_kill (struct target_ops *ops);
128 static int tohex (int nib);
130 static int remote_can_async_p (void);
132 static int remote_is_async_p (void);
134 static void remote_async (void (*callback) (enum inferior_event_type event_type,
135 void *context), void *context);
137 static void remote_detach (struct target_ops *ops, char *args, int from_tty);
139 static void remote_interrupt (int signo);
141 static void remote_interrupt_twice (int signo);
143 static void interrupt_query (void);
145 static void set_general_thread (struct ptid ptid);
146 static void set_continue_thread (struct ptid ptid);
148 static void get_offsets (void);
150 static void skip_frame (void);
152 static long read_frame (char **buf_p, long *sizeof_buf);
154 static int hexnumlen (ULONGEST num);
156 static void init_remote_ops (void);
158 static void init_extended_remote_ops (void);
160 static void remote_stop (ptid_t);
162 static int ishex (int ch, int *val);
164 static int stubhex (int ch);
166 static int hexnumstr (char *, ULONGEST);
168 static int hexnumnstr (char *, ULONGEST, int);
170 static CORE_ADDR remote_address_masked (CORE_ADDR);
172 static void print_packet (char *);
174 static void compare_sections_command (char *, int);
176 static void packet_command (char *, int);
178 static int stub_unpack_int (char *buff, int fieldlength);
180 static ptid_t remote_current_thread (ptid_t oldptid);
182 static void remote_find_new_threads (void);
184 static void record_currthread (ptid_t currthread);
186 static int fromhex (int a);
188 extern int hex2bin (const char *hex, gdb_byte *bin, int count);
190 extern int bin2hex (const gdb_byte *bin, char *hex, int count);
192 static int putpkt_binary (char *buf, int cnt);
194 static void check_binary_download (CORE_ADDR addr);
196 struct packet_config;
198 static void show_packet_config_cmd (struct packet_config *config);
200 static void update_packet_config (struct packet_config *config);
202 static void set_remote_protocol_packet_cmd (char *args, int from_tty,
203 struct cmd_list_element *c);
205 static void show_remote_protocol_packet_cmd (struct ui_file *file,
207 struct cmd_list_element *c,
210 static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
211 static ptid_t read_ptid (char *buf, char **obuf);
213 static void remote_set_permissions (void);
216 static int remote_get_trace_status (struct trace_status *ts);
218 static int remote_upload_tracepoints (struct uploaded_tp **utpp);
220 static int remote_upload_trace_state_variables (struct uploaded_tsv **utsvp);
222 static void remote_query_supported (void);
224 static void remote_check_symbols (struct objfile *objfile);
226 void _initialize_remote (void);
229 static struct stop_reply *stop_reply_xmalloc (void);
230 static void stop_reply_xfree (struct stop_reply *);
231 static void do_stop_reply_xfree (void *arg);
232 static void remote_parse_stop_reply (char *buf, struct stop_reply *);
233 static void push_stop_reply (struct stop_reply *);
234 static void remote_get_pending_stop_replies (void);
235 static void discard_pending_stop_replies (int pid);
236 static int peek_stop_reply (ptid_t ptid);
238 static void remote_async_inferior_event_handler (gdb_client_data);
239 static void remote_async_get_pending_events_handler (gdb_client_data);
241 static void remote_terminal_ours (void);
243 static int remote_read_description_p (struct target_ops *target);
245 static void remote_console_output (char *msg);
247 /* The non-stop remote protocol provisions for one pending stop reply.
248 This is where we keep it until it is acknowledged. */
250 static struct stop_reply *pending_stop_reply = NULL;
254 static struct cmd_list_element *remote_cmdlist;
256 /* For "set remote" and "show remote". */
258 static struct cmd_list_element *remote_set_cmdlist;
259 static struct cmd_list_element *remote_show_cmdlist;
261 /* Description of the remote protocol state for the currently
262 connected target. This is per-target state, and independent of the
263 selected architecture. */
267 /* A buffer to use for incoming packets, and its current size. The
268 buffer is grown dynamically for larger incoming packets.
269 Outgoing packets may also be constructed in this buffer.
270 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
271 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
276 /* If we negotiated packet size explicitly (and thus can bypass
277 heuristics for the largest packet size that will not overflow
278 a buffer in the stub), this will be set to that packet size.
279 Otherwise zero, meaning to use the guessed size. */
280 long explicit_packet_size;
282 /* remote_wait is normally called when the target is running and
283 waits for a stop reply packet. But sometimes we need to call it
284 when the target is already stopped. We can send a "?" packet
285 and have remote_wait read the response. Or, if we already have
286 the response, we can stash it in BUF and tell remote_wait to
287 skip calling getpkt. This flag is set when BUF contains a
288 stop reply packet and the target is not waiting. */
289 int cached_wait_status;
291 /* True, if in no ack mode. That is, neither GDB nor the stub will
292 expect acks from each other. The connection is assumed to be
296 /* True if we're connected in extended remote mode. */
299 /* True if the stub reported support for multi-process
301 int multi_process_aware;
303 /* True if we resumed the target and we're waiting for the target to
304 stop. In the mean time, we can't start another command/query.
305 The remote server wouldn't be ready to process it, so we'd
306 timeout waiting for a reply that would never come and eventually
307 we'd close the connection. This can happen in asynchronous mode
308 because we allow GDB commands while the target is running. */
309 int waiting_for_stop_reply;
311 /* True if the stub reports support for non-stop mode. */
314 /* True if the stub reports support for vCont;t. */
317 /* True if the stub reports support for conditional tracepoints. */
318 int cond_tracepoints;
320 /* True if the stub reports support for fast tracepoints. */
321 int fast_tracepoints;
323 /* True if the stub reports support for static tracepoints. */
324 int static_tracepoints;
326 /* True if the stub can continue running a trace while GDB is
328 int disconnected_tracing;
330 /* True if the stub reports support for enabling and disabling
331 tracepoints while a trace experiment is running. */
332 int enable_disable_tracepoints;
334 /* True if the stub can collect strings using tracenz bytecode. */
337 /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
338 responded to that. */
342 /* Private data that we'll store in (struct thread_info)->private. */
343 struct private_thread_info
350 free_private_thread_info (struct private_thread_info *info)
356 /* Returns true if the multi-process extensions are in effect. */
358 remote_multi_process_p (struct remote_state *rs)
360 return rs->extended && rs->multi_process_aware;
363 /* This data could be associated with a target, but we do not always
364 have access to the current target when we need it, so for now it is
365 static. This will be fine for as long as only one target is in use
367 static struct remote_state remote_state;
369 static struct remote_state *
370 get_remote_state_raw (void)
372 return &remote_state;
375 /* Description of the remote protocol for a given architecture. */
379 long offset; /* Offset into G packet. */
380 long regnum; /* GDB's internal register number. */
381 LONGEST pnum; /* Remote protocol register number. */
382 int in_g_packet; /* Always part of G packet. */
383 /* long size in bytes; == register_size (target_gdbarch, regnum);
385 /* char *name; == gdbarch_register_name (target_gdbarch, regnum);
389 struct remote_arch_state
391 /* Description of the remote protocol registers. */
392 long sizeof_g_packet;
394 /* Description of the remote protocol registers indexed by REGNUM
395 (making an array gdbarch_num_regs in size). */
396 struct packet_reg *regs;
398 /* This is the size (in chars) of the first response to the ``g''
399 packet. It is used as a heuristic when determining the maximum
400 size of memory-read and memory-write packets. A target will
401 typically only reserve a buffer large enough to hold the ``g''
402 packet. The size does not include packet overhead (headers and
404 long actual_register_packet_size;
406 /* This is the maximum size (in chars) of a non read/write packet.
407 It is also used as a cap on the size of read/write packets. */
408 long remote_packet_size;
411 long sizeof_pkt = 2000;
413 /* Utility: generate error from an incoming stub packet. */
415 trace_error (char *buf)
418 return; /* not an error msg */
421 case '1': /* malformed packet error */
422 if (*++buf == '0') /* general case: */
423 error (_("remote.c: error in outgoing packet."));
425 error (_("remote.c: error in outgoing packet at field #%ld."),
426 strtol (buf, NULL, 16));
428 error (_("trace API error 0x%s."), ++buf);
430 error (_("Target returns error code '%s'."), buf);
434 /* Utility: wait for reply from stub, while accepting "O" packets. */
436 remote_get_noisy_reply (char **buf_p,
439 do /* Loop on reply from remote stub. */
443 QUIT; /* Allow user to bail out with ^C. */
444 getpkt (buf_p, sizeof_buf, 0);
448 else if (strncmp (buf, "qRelocInsn:", strlen ("qRelocInsn:")) == 0)
451 CORE_ADDR from, to, org_to;
453 int adjusted_size = 0;
454 volatile struct gdb_exception ex;
456 p = buf + strlen ("qRelocInsn:");
457 pp = unpack_varlen_hex (p, &ul);
459 error (_("invalid qRelocInsn packet: %s"), buf);
463 unpack_varlen_hex (p, &ul);
468 TRY_CATCH (ex, RETURN_MASK_ALL)
470 gdbarch_relocate_instruction (target_gdbarch, &to, from);
474 adjusted_size = to - org_to;
476 sprintf (buf, "qRelocInsn:%x", adjusted_size);
479 else if (ex.reason < 0 && ex.error == MEMORY_ERROR)
481 /* Propagate memory errors silently back to the target.
482 The stub may have limited the range of addresses we
483 can write to, for example. */
488 /* Something unexpectedly bad happened. Be verbose so
489 we can tell what, and propagate the error back to the
490 stub, so it doesn't get stuck waiting for a
492 exception_fprintf (gdb_stderr, ex,
493 _("warning: relocating instruction: "));
497 else if (buf[0] == 'O' && buf[1] != 'K')
498 remote_console_output (buf + 1); /* 'O' message from stub */
500 return buf; /* Here's the actual reply. */
505 /* Handle for retreving the remote protocol data from gdbarch. */
506 static struct gdbarch_data *remote_gdbarch_data_handle;
508 static struct remote_arch_state *
509 get_remote_arch_state (void)
511 return gdbarch_data (target_gdbarch, remote_gdbarch_data_handle);
514 /* Fetch the global remote target state. */
516 static struct remote_state *
517 get_remote_state (void)
519 /* Make sure that the remote architecture state has been
520 initialized, because doing so might reallocate rs->buf. Any
521 function which calls getpkt also needs to be mindful of changes
522 to rs->buf, but this call limits the number of places which run
524 get_remote_arch_state ();
526 return get_remote_state_raw ();
530 compare_pnums (const void *lhs_, const void *rhs_)
532 const struct packet_reg * const *lhs = lhs_;
533 const struct packet_reg * const *rhs = rhs_;
535 if ((*lhs)->pnum < (*rhs)->pnum)
537 else if ((*lhs)->pnum == (*rhs)->pnum)
544 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
546 int regnum, num_remote_regs, offset;
547 struct packet_reg **remote_regs;
549 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
551 struct packet_reg *r = ®s[regnum];
553 if (register_size (gdbarch, regnum) == 0)
554 /* Do not try to fetch zero-sized (placeholder) registers. */
557 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
562 /* Define the g/G packet format as the contents of each register
563 with a remote protocol number, in order of ascending protocol
566 remote_regs = alloca (gdbarch_num_regs (gdbarch)
567 * sizeof (struct packet_reg *));
568 for (num_remote_regs = 0, regnum = 0;
569 regnum < gdbarch_num_regs (gdbarch);
571 if (regs[regnum].pnum != -1)
572 remote_regs[num_remote_regs++] = ®s[regnum];
574 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
577 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
579 remote_regs[regnum]->in_g_packet = 1;
580 remote_regs[regnum]->offset = offset;
581 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
587 /* Given the architecture described by GDBARCH, return the remote
588 protocol register's number and the register's offset in the g/G
589 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
590 If the target does not have a mapping for REGNUM, return false,
591 otherwise, return true. */
594 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
595 int *pnum, int *poffset)
598 struct packet_reg *regs;
599 struct cleanup *old_chain;
601 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
603 regs = xcalloc (gdbarch_num_regs (gdbarch), sizeof (struct packet_reg));
604 old_chain = make_cleanup (xfree, regs);
606 sizeof_g_packet = map_regcache_remote_table (gdbarch, regs);
608 *pnum = regs[regnum].pnum;
609 *poffset = regs[regnum].offset;
611 do_cleanups (old_chain);
617 init_remote_state (struct gdbarch *gdbarch)
619 struct remote_state *rs = get_remote_state_raw ();
620 struct remote_arch_state *rsa;
622 rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
624 /* Use the architecture to build a regnum<->pnum table, which will be
625 1:1 unless a feature set specifies otherwise. */
626 rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
627 gdbarch_num_regs (gdbarch),
630 /* Record the maximum possible size of the g packet - it may turn out
632 rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
634 /* Default maximum number of characters in a packet body. Many
635 remote stubs have a hardwired buffer size of 400 bytes
636 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
637 as the maximum packet-size to ensure that the packet and an extra
638 NUL character can always fit in the buffer. This stops GDB
639 trashing stubs that try to squeeze an extra NUL into what is
640 already a full buffer (As of 1999-12-04 that was most stubs). */
641 rsa->remote_packet_size = 400 - 1;
643 /* This one is filled in when a ``g'' packet is received. */
644 rsa->actual_register_packet_size = 0;
646 /* Should rsa->sizeof_g_packet needs more space than the
647 default, adjust the size accordingly. Remember that each byte is
648 encoded as two characters. 32 is the overhead for the packet
649 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
650 (``$NN:G...#NN'') is a better guess, the below has been padded a
652 if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
653 rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
655 /* Make sure that the packet buffer is plenty big enough for
656 this architecture. */
657 if (rs->buf_size < rsa->remote_packet_size)
659 rs->buf_size = 2 * rsa->remote_packet_size;
660 rs->buf = xrealloc (rs->buf, rs->buf_size);
666 /* Return the current allowed size of a remote packet. This is
667 inferred from the current architecture, and should be used to
668 limit the length of outgoing packets. */
670 get_remote_packet_size (void)
672 struct remote_state *rs = get_remote_state ();
673 struct remote_arch_state *rsa = get_remote_arch_state ();
675 if (rs->explicit_packet_size)
676 return rs->explicit_packet_size;
678 return rsa->remote_packet_size;
681 static struct packet_reg *
682 packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
684 if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch))
688 struct packet_reg *r = &rsa->regs[regnum];
690 gdb_assert (r->regnum == regnum);
695 static struct packet_reg *
696 packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
700 for (i = 0; i < gdbarch_num_regs (target_gdbarch); i++)
702 struct packet_reg *r = &rsa->regs[i];
710 /* FIXME: graces/2002-08-08: These variables should eventually be
711 bound to an instance of the target object (as in gdbarch-tdep()),
712 when such a thing exists. */
714 /* This is set to the data address of the access causing the target
715 to stop for a watchpoint. */
716 static CORE_ADDR remote_watch_data_address;
718 /* This is non-zero if target stopped for a watchpoint. */
719 static int remote_stopped_by_watchpoint_p;
721 static struct target_ops remote_ops;
723 static struct target_ops extended_remote_ops;
725 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
726 ``forever'' still use the normal timeout mechanism. This is
727 currently used by the ASYNC code to guarentee that target reads
728 during the initial connect always time-out. Once getpkt has been
729 modified to return a timeout indication and, in turn
730 remote_wait()/wait_for_inferior() have gained a timeout parameter
732 static int wait_forever_enabled_p = 1;
734 /* Allow the user to specify what sequence to send to the remote
735 when he requests a program interruption: Although ^C is usually
736 what remote systems expect (this is the default, here), it is
737 sometimes preferable to send a break. On other systems such
738 as the Linux kernel, a break followed by g, which is Magic SysRq g
739 is required in order to interrupt the execution. */
740 const char interrupt_sequence_control_c[] = "Ctrl-C";
741 const char interrupt_sequence_break[] = "BREAK";
742 const char interrupt_sequence_break_g[] = "BREAK-g";
743 static const char *interrupt_sequence_modes[] =
745 interrupt_sequence_control_c,
746 interrupt_sequence_break,
747 interrupt_sequence_break_g,
750 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
753 show_interrupt_sequence (struct ui_file *file, int from_tty,
754 struct cmd_list_element *c,
757 if (interrupt_sequence_mode == interrupt_sequence_control_c)
758 fprintf_filtered (file,
759 _("Send the ASCII ETX character (Ctrl-c) "
760 "to the remote target to interrupt the "
761 "execution of the program.\n"));
762 else if (interrupt_sequence_mode == interrupt_sequence_break)
763 fprintf_filtered (file,
764 _("send a break signal to the remote target "
765 "to interrupt the execution of the program.\n"));
766 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
767 fprintf_filtered (file,
768 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
769 "the remote target to interrupt the execution "
770 "of Linux kernel.\n"));
772 internal_error (__FILE__, __LINE__,
773 _("Invalid value for interrupt_sequence_mode: %s."),
774 interrupt_sequence_mode);
777 /* This boolean variable specifies whether interrupt_sequence is sent
778 to the remote target when gdb connects to it.
779 This is mostly needed when you debug the Linux kernel: The Linux kernel
780 expects BREAK g which is Magic SysRq g for connecting gdb. */
781 static int interrupt_on_connect = 0;
783 /* This variable is used to implement the "set/show remotebreak" commands.
784 Since these commands are now deprecated in favor of "set/show remote
785 interrupt-sequence", it no longer has any effect on the code. */
786 static int remote_break;
789 set_remotebreak (char *args, int from_tty, struct cmd_list_element *c)
792 interrupt_sequence_mode = interrupt_sequence_break;
794 interrupt_sequence_mode = interrupt_sequence_control_c;
798 show_remotebreak (struct ui_file *file, int from_tty,
799 struct cmd_list_element *c,
804 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
805 remote_open knows that we don't have a file open when the program
807 static struct serial *remote_desc = NULL;
809 /* This variable sets the number of bits in an address that are to be
810 sent in a memory ("M" or "m") packet. Normally, after stripping
811 leading zeros, the entire address would be sent. This variable
812 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
813 initial implementation of remote.c restricted the address sent in
814 memory packets to ``host::sizeof long'' bytes - (typically 32
815 bits). Consequently, for 64 bit targets, the upper 32 bits of an
816 address was never sent. Since fixing this bug may cause a break in
817 some remote targets this variable is principly provided to
818 facilitate backward compatibility. */
820 static int remote_address_size;
822 /* Temporary to track who currently owns the terminal. See
823 remote_terminal_* for more details. */
825 static int remote_async_terminal_ours_p;
827 /* The executable file to use for "run" on the remote side. */
829 static char *remote_exec_file = "";
832 /* User configurable variables for the number of characters in a
833 memory read/write packet. MIN (rsa->remote_packet_size,
834 rsa->sizeof_g_packet) is the default. Some targets need smaller
835 values (fifo overruns, et.al.) and some users need larger values
836 (speed up transfers). The variables ``preferred_*'' (the user
837 request), ``current_*'' (what was actually set) and ``forced_*''
838 (Positive - a soft limit, negative - a hard limit). */
840 struct memory_packet_config
847 /* Compute the current size of a read/write packet. Since this makes
848 use of ``actual_register_packet_size'' the computation is dynamic. */
851 get_memory_packet_size (struct memory_packet_config *config)
853 struct remote_state *rs = get_remote_state ();
854 struct remote_arch_state *rsa = get_remote_arch_state ();
856 /* NOTE: The somewhat arbitrary 16k comes from the knowledge (folk
857 law?) that some hosts don't cope very well with large alloca()
858 calls. Eventually the alloca() code will be replaced by calls to
859 xmalloc() and make_cleanups() allowing this restriction to either
860 be lifted or removed. */
861 #ifndef MAX_REMOTE_PACKET_SIZE
862 #define MAX_REMOTE_PACKET_SIZE 16384
864 /* NOTE: 20 ensures we can write at least one byte. */
865 #ifndef MIN_REMOTE_PACKET_SIZE
866 #define MIN_REMOTE_PACKET_SIZE 20
871 if (config->size <= 0)
872 what_they_get = MAX_REMOTE_PACKET_SIZE;
874 what_they_get = config->size;
878 what_they_get = get_remote_packet_size ();
879 /* Limit the packet to the size specified by the user. */
881 && what_they_get > config->size)
882 what_they_get = config->size;
884 /* Limit it to the size of the targets ``g'' response unless we have
885 permission from the stub to use a larger packet size. */
886 if (rs->explicit_packet_size == 0
887 && rsa->actual_register_packet_size > 0
888 && what_they_get > rsa->actual_register_packet_size)
889 what_they_get = rsa->actual_register_packet_size;
891 if (what_they_get > MAX_REMOTE_PACKET_SIZE)
892 what_they_get = MAX_REMOTE_PACKET_SIZE;
893 if (what_they_get < MIN_REMOTE_PACKET_SIZE)
894 what_they_get = MIN_REMOTE_PACKET_SIZE;
896 /* Make sure there is room in the global buffer for this packet
897 (including its trailing NUL byte). */
898 if (rs->buf_size < what_they_get + 1)
900 rs->buf_size = 2 * what_they_get;
901 rs->buf = xrealloc (rs->buf, 2 * what_they_get);
904 return what_they_get;
907 /* Update the size of a read/write packet. If they user wants
908 something really big then do a sanity check. */
911 set_memory_packet_size (char *args, struct memory_packet_config *config)
913 int fixed_p = config->fixed_p;
914 long size = config->size;
917 error (_("Argument required (integer, `fixed' or `limited')."));
918 else if (strcmp (args, "hard") == 0
919 || strcmp (args, "fixed") == 0)
921 else if (strcmp (args, "soft") == 0
922 || strcmp (args, "limit") == 0)
928 size = strtoul (args, &end, 0);
930 error (_("Invalid %s (bad syntax)."), config->name);
932 /* Instead of explicitly capping the size of a packet to
933 MAX_REMOTE_PACKET_SIZE or dissallowing it, the user is
934 instead allowed to set the size to something arbitrarily
936 if (size > MAX_REMOTE_PACKET_SIZE)
937 error (_("Invalid %s (too large)."), config->name);
941 if (fixed_p && !config->fixed_p)
943 if (! query (_("The target may not be able to correctly handle a %s\n"
944 "of %ld bytes. Change the packet size? "),
946 error (_("Packet size not changed."));
948 /* Update the config. */
949 config->fixed_p = fixed_p;
954 show_memory_packet_size (struct memory_packet_config *config)
956 printf_filtered (_("The %s is %ld. "), config->name, config->size);
958 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
959 get_memory_packet_size (config));
961 printf_filtered (_("Packets are limited to %ld bytes.\n"),
962 get_memory_packet_size (config));
965 static struct memory_packet_config memory_write_packet_config =
967 "memory-write-packet-size",
971 set_memory_write_packet_size (char *args, int from_tty)
973 set_memory_packet_size (args, &memory_write_packet_config);
977 show_memory_write_packet_size (char *args, int from_tty)
979 show_memory_packet_size (&memory_write_packet_config);
983 get_memory_write_packet_size (void)
985 return get_memory_packet_size (&memory_write_packet_config);
988 static struct memory_packet_config memory_read_packet_config =
990 "memory-read-packet-size",
994 set_memory_read_packet_size (char *args, int from_tty)
996 set_memory_packet_size (args, &memory_read_packet_config);
1000 show_memory_read_packet_size (char *args, int from_tty)
1002 show_memory_packet_size (&memory_read_packet_config);
1006 get_memory_read_packet_size (void)
1008 long size = get_memory_packet_size (&memory_read_packet_config);
1010 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1011 extra buffer size argument before the memory read size can be
1012 increased beyond this. */
1013 if (size > get_remote_packet_size ())
1014 size = get_remote_packet_size ();
1019 /* Generic configuration support for packets the stub optionally
1020 supports. Allows the user to specify the use of the packet as well
1021 as allowing GDB to auto-detect support in the remote stub. */
1025 PACKET_SUPPORT_UNKNOWN = 0,
1030 struct packet_config
1034 enum auto_boolean detect;
1035 enum packet_support support;
1038 /* Analyze a packet's return value and update the packet config
1049 update_packet_config (struct packet_config *config)
1051 switch (config->detect)
1053 case AUTO_BOOLEAN_TRUE:
1054 config->support = PACKET_ENABLE;
1056 case AUTO_BOOLEAN_FALSE:
1057 config->support = PACKET_DISABLE;
1059 case AUTO_BOOLEAN_AUTO:
1060 config->support = PACKET_SUPPORT_UNKNOWN;
1066 show_packet_config_cmd (struct packet_config *config)
1068 char *support = "internal-error";
1070 switch (config->support)
1073 support = "enabled";
1075 case PACKET_DISABLE:
1076 support = "disabled";
1078 case PACKET_SUPPORT_UNKNOWN:
1079 support = "unknown";
1082 switch (config->detect)
1084 case AUTO_BOOLEAN_AUTO:
1085 printf_filtered (_("Support for the `%s' packet "
1086 "is auto-detected, currently %s.\n"),
1087 config->name, support);
1089 case AUTO_BOOLEAN_TRUE:
1090 case AUTO_BOOLEAN_FALSE:
1091 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1092 config->name, support);
1098 add_packet_config_cmd (struct packet_config *config, const char *name,
1099 const char *title, int legacy)
1105 config->name = name;
1106 config->title = title;
1107 config->detect = AUTO_BOOLEAN_AUTO;
1108 config->support = PACKET_SUPPORT_UNKNOWN;
1109 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1111 show_doc = xstrprintf ("Show current use of remote "
1112 "protocol `%s' (%s) packet",
1114 /* set/show TITLE-packet {auto,on,off} */
1115 cmd_name = xstrprintf ("%s-packet", title);
1116 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
1117 &config->detect, set_doc,
1118 show_doc, NULL, /* help_doc */
1119 set_remote_protocol_packet_cmd,
1120 show_remote_protocol_packet_cmd,
1121 &remote_set_cmdlist, &remote_show_cmdlist);
1122 /* The command code copies the documentation strings. */
1125 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
1130 legacy_name = xstrprintf ("%s-packet", name);
1131 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1132 &remote_set_cmdlist);
1133 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1134 &remote_show_cmdlist);
1138 static enum packet_result
1139 packet_check_result (const char *buf)
1143 /* The stub recognized the packet request. Check that the
1144 operation succeeded. */
1146 && isxdigit (buf[1]) && isxdigit (buf[2])
1148 /* "Enn" - definitly an error. */
1149 return PACKET_ERROR;
1151 /* Always treat "E." as an error. This will be used for
1152 more verbose error messages, such as E.memtypes. */
1153 if (buf[0] == 'E' && buf[1] == '.')
1154 return PACKET_ERROR;
1156 /* The packet may or may not be OK. Just assume it is. */
1160 /* The stub does not support the packet. */
1161 return PACKET_UNKNOWN;
1164 static enum packet_result
1165 packet_ok (const char *buf, struct packet_config *config)
1167 enum packet_result result;
1169 result = packet_check_result (buf);
1174 /* The stub recognized the packet request. */
1175 switch (config->support)
1177 case PACKET_SUPPORT_UNKNOWN:
1179 fprintf_unfiltered (gdb_stdlog,
1180 "Packet %s (%s) is supported\n",
1181 config->name, config->title);
1182 config->support = PACKET_ENABLE;
1184 case PACKET_DISABLE:
1185 internal_error (__FILE__, __LINE__,
1186 _("packet_ok: attempt to use a disabled packet"));
1192 case PACKET_UNKNOWN:
1193 /* The stub does not support the packet. */
1194 switch (config->support)
1197 if (config->detect == AUTO_BOOLEAN_AUTO)
1198 /* If the stub previously indicated that the packet was
1199 supported then there is a protocol error.. */
1200 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1201 config->name, config->title);
1203 /* The user set it wrong. */
1204 error (_("Enabled packet %s (%s) not recognized by stub"),
1205 config->name, config->title);
1207 case PACKET_SUPPORT_UNKNOWN:
1209 fprintf_unfiltered (gdb_stdlog,
1210 "Packet %s (%s) is NOT supported\n",
1211 config->name, config->title);
1212 config->support = PACKET_DISABLE;
1214 case PACKET_DISABLE:
1236 PACKET_vFile_pwrite,
1238 PACKET_vFile_unlink,
1240 PACKET_qXfer_features,
1241 PACKET_qXfer_libraries,
1242 PACKET_qXfer_memory_map,
1243 PACKET_qXfer_spu_read,
1244 PACKET_qXfer_spu_write,
1245 PACKET_qXfer_osdata,
1246 PACKET_qXfer_threads,
1247 PACKET_qXfer_statictrace_read,
1248 PACKET_qXfer_traceframe_info,
1252 PACKET_QPassSignals,
1253 PACKET_qSearch_memory,
1256 PACKET_QStartNoAckMode,
1258 PACKET_qXfer_siginfo_read,
1259 PACKET_qXfer_siginfo_write,
1261 PACKET_ConditionalTracepoints,
1262 PACKET_FastTracepoints,
1263 PACKET_StaticTracepoints,
1266 PACKET_TracepointSource,
1269 PACKET_QDisableRandomization,
1273 static struct packet_config remote_protocol_packets[PACKET_MAX];
1276 set_remote_protocol_packet_cmd (char *args, int from_tty,
1277 struct cmd_list_element *c)
1279 struct packet_config *packet;
1281 for (packet = remote_protocol_packets;
1282 packet < &remote_protocol_packets[PACKET_MAX];
1285 if (&packet->detect == c->var)
1287 update_packet_config (packet);
1291 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
1296 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1297 struct cmd_list_element *c,
1300 struct packet_config *packet;
1302 for (packet = remote_protocol_packets;
1303 packet < &remote_protocol_packets[PACKET_MAX];
1306 if (&packet->detect == c->var)
1308 show_packet_config_cmd (packet);
1312 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
1316 /* Should we try one of the 'Z' requests? */
1320 Z_PACKET_SOFTWARE_BP,
1321 Z_PACKET_HARDWARE_BP,
1328 /* For compatibility with older distributions. Provide a ``set remote
1329 Z-packet ...'' command that updates all the Z packet types. */
1331 static enum auto_boolean remote_Z_packet_detect;
1334 set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1335 struct cmd_list_element *c)
1339 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1341 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
1342 update_packet_config (&remote_protocol_packets[PACKET_Z0 + i]);
1347 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1348 struct cmd_list_element *c,
1353 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1355 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
1359 /* Should we try the 'ThreadInfo' query packet?
1361 This variable (NOT available to the user: auto-detect only!)
1362 determines whether GDB will use the new, simpler "ThreadInfo"
1363 query or the older, more complex syntax for thread queries.
1364 This is an auto-detect variable (set to true at each connect,
1365 and set to false when the target fails to recognize it). */
1367 static int use_threadinfo_query;
1368 static int use_threadextra_query;
1370 /* Tokens for use by the asynchronous signal handlers for SIGINT. */
1371 static struct async_signal_handler *sigint_remote_twice_token;
1372 static struct async_signal_handler *sigint_remote_token;
1375 /* Asynchronous signal handle registered as event loop source for
1376 when we have pending events ready to be passed to the core. */
1378 static struct async_event_handler *remote_async_inferior_event_token;
1380 /* Asynchronous signal handle registered as event loop source for when
1381 the remote sent us a %Stop notification. The registered callback
1382 will do a vStopped sequence to pull the rest of the events out of
1383 the remote side into our event queue. */
1385 static struct async_event_handler *remote_async_get_pending_events_token;
1388 static ptid_t magic_null_ptid;
1389 static ptid_t not_sent_ptid;
1390 static ptid_t any_thread_ptid;
1392 /* These are the threads which we last sent to the remote system. The
1393 TID member will be -1 for all or -2 for not sent yet. */
1395 static ptid_t general_thread;
1396 static ptid_t continue_thread;
1398 /* This the traceframe which we last selected on the remote system.
1399 It will be -1 if no traceframe is selected. */
1400 static int remote_traceframe_number = -1;
1402 /* Find out if the stub attached to PID (and hence GDB should offer to
1403 detach instead of killing it when bailing out). */
1406 remote_query_attached (int pid)
1408 struct remote_state *rs = get_remote_state ();
1410 if (remote_protocol_packets[PACKET_qAttached].support == PACKET_DISABLE)
1413 if (remote_multi_process_p (rs))
1414 sprintf (rs->buf, "qAttached:%x", pid);
1416 sprintf (rs->buf, "qAttached");
1419 getpkt (&rs->buf, &rs->buf_size, 0);
1421 switch (packet_ok (rs->buf,
1422 &remote_protocol_packets[PACKET_qAttached]))
1425 if (strcmp (rs->buf, "1") == 0)
1429 warning (_("Remote failure reply: %s"), rs->buf);
1431 case PACKET_UNKNOWN:
1438 /* Add PID to GDB's inferior table. Since we can be connected to a
1439 remote system before before knowing about any inferior, mark the
1440 target with execution when we find the first inferior. If ATTACHED
1441 is 1, then we had just attached to this inferior. If it is 0, then
1442 we just created this inferior. If it is -1, then try querying the
1443 remote stub to find out if it had attached to the inferior or
1446 static struct inferior *
1447 remote_add_inferior (int pid, int attached)
1449 struct inferior *inf;
1451 /* Check whether this process we're learning about is to be
1452 considered attached, or if is to be considered to have been
1453 spawned by the stub. */
1455 attached = remote_query_attached (pid);
1457 if (gdbarch_has_global_solist (target_gdbarch))
1459 /* If the target shares code across all inferiors, then every
1460 attach adds a new inferior. */
1461 inf = add_inferior (pid);
1463 /* ... and every inferior is bound to the same program space.
1464 However, each inferior may still have its own address
1466 inf->aspace = maybe_new_address_space ();
1467 inf->pspace = current_program_space;
1471 /* In the traditional debugging scenario, there's a 1-1 match
1472 between program/address spaces. We simply bind the inferior
1473 to the program space's address space. */
1474 inf = current_inferior ();
1475 inferior_appeared (inf, pid);
1478 inf->attach_flag = attached;
1483 /* Add thread PTID to GDB's thread list. Tag it as executing/running
1484 according to RUNNING. */
1487 remote_add_thread (ptid_t ptid, int running)
1491 set_executing (ptid, running);
1492 set_running (ptid, running);
1495 /* Come here when we learn about a thread id from the remote target.
1496 It may be the first time we hear about such thread, so take the
1497 opportunity to add it to GDB's thread list. In case this is the
1498 first time we're noticing its corresponding inferior, add it to
1499 GDB's inferior list as well. */
1502 remote_notice_new_inferior (ptid_t currthread, int running)
1504 /* If this is a new thread, add it to GDB's thread list.
1505 If we leave it up to WFI to do this, bad things will happen. */
1507 if (in_thread_list (currthread) && is_exited (currthread))
1509 /* We're seeing an event on a thread id we knew had exited.
1510 This has to be a new thread reusing the old id. Add it. */
1511 remote_add_thread (currthread, running);
1515 if (!in_thread_list (currthread))
1517 struct inferior *inf = NULL;
1518 int pid = ptid_get_pid (currthread);
1520 if (ptid_is_pid (inferior_ptid)
1521 && pid == ptid_get_pid (inferior_ptid))
1523 /* inferior_ptid has no thread member yet. This can happen
1524 with the vAttach -> remote_wait,"TAAthread:" path if the
1525 stub doesn't support qC. This is the first stop reported
1526 after an attach, so this is the main thread. Update the
1527 ptid in the thread list. */
1528 if (in_thread_list (pid_to_ptid (pid)))
1529 thread_change_ptid (inferior_ptid, currthread);
1532 remote_add_thread (currthread, running);
1533 inferior_ptid = currthread;
1538 if (ptid_equal (magic_null_ptid, inferior_ptid))
1540 /* inferior_ptid is not set yet. This can happen with the
1541 vRun -> remote_wait,"TAAthread:" path if the stub
1542 doesn't support qC. This is the first stop reported
1543 after an attach, so this is the main thread. Update the
1544 ptid in the thread list. */
1545 thread_change_ptid (inferior_ptid, currthread);
1549 /* When connecting to a target remote, or to a target
1550 extended-remote which already was debugging an inferior, we
1551 may not know about it yet. Add it before adding its child
1552 thread, so notifications are emitted in a sensible order. */
1553 if (!in_inferior_list (ptid_get_pid (currthread)))
1554 inf = remote_add_inferior (ptid_get_pid (currthread), -1);
1556 /* This is really a new thread. Add it. */
1557 remote_add_thread (currthread, running);
1559 /* If we found a new inferior, let the common code do whatever
1560 it needs to with it (e.g., read shared libraries, insert
1563 notice_new_inferior (currthread, running, 0);
1567 /* Return the private thread data, creating it if necessary. */
1569 struct private_thread_info *
1570 demand_private_info (ptid_t ptid)
1572 struct thread_info *info = find_thread_ptid (ptid);
1578 info->private = xmalloc (sizeof (*(info->private)));
1579 info->private_dtor = free_private_thread_info;
1580 info->private->core = -1;
1581 info->private->extra = 0;
1584 return info->private;
1587 /* Call this function as a result of
1588 1) A halt indication (T packet) containing a thread id
1589 2) A direct query of currthread
1590 3) Successful execution of set thread */
1593 record_currthread (ptid_t currthread)
1595 general_thread = currthread;
1598 static char *last_pass_packet;
1600 /* If 'QPassSignals' is supported, tell the remote stub what signals
1601 it can simply pass through to the inferior without reporting. */
1604 remote_pass_signals (int numsigs, unsigned char *pass_signals)
1606 if (remote_protocol_packets[PACKET_QPassSignals].support != PACKET_DISABLE)
1608 char *pass_packet, *p;
1611 gdb_assert (numsigs < 256);
1612 for (i = 0; i < numsigs; i++)
1614 if (pass_signals[i])
1617 pass_packet = xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
1618 strcpy (pass_packet, "QPassSignals:");
1619 p = pass_packet + strlen (pass_packet);
1620 for (i = 0; i < numsigs; i++)
1622 if (pass_signals[i])
1625 *p++ = tohex (i >> 4);
1626 *p++ = tohex (i & 15);
1635 if (!last_pass_packet || strcmp (last_pass_packet, pass_packet))
1637 struct remote_state *rs = get_remote_state ();
1638 char *buf = rs->buf;
1640 putpkt (pass_packet);
1641 getpkt (&rs->buf, &rs->buf_size, 0);
1642 packet_ok (buf, &remote_protocol_packets[PACKET_QPassSignals]);
1643 if (last_pass_packet)
1644 xfree (last_pass_packet);
1645 last_pass_packet = pass_packet;
1648 xfree (pass_packet);
1652 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
1653 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
1654 thread. If GEN is set, set the general thread, if not, then set
1655 the step/continue thread. */
1657 set_thread (struct ptid ptid, int gen)
1659 struct remote_state *rs = get_remote_state ();
1660 ptid_t state = gen ? general_thread : continue_thread;
1661 char *buf = rs->buf;
1662 char *endbuf = rs->buf + get_remote_packet_size ();
1664 if (ptid_equal (state, ptid))
1668 *buf++ = gen ? 'g' : 'c';
1669 if (ptid_equal (ptid, magic_null_ptid))
1670 xsnprintf (buf, endbuf - buf, "0");
1671 else if (ptid_equal (ptid, any_thread_ptid))
1672 xsnprintf (buf, endbuf - buf, "0");
1673 else if (ptid_equal (ptid, minus_one_ptid))
1674 xsnprintf (buf, endbuf - buf, "-1");
1676 write_ptid (buf, endbuf, ptid);
1678 getpkt (&rs->buf, &rs->buf_size, 0);
1680 general_thread = ptid;
1682 continue_thread = ptid;
1686 set_general_thread (struct ptid ptid)
1688 set_thread (ptid, 1);
1692 set_continue_thread (struct ptid ptid)
1694 set_thread (ptid, 0);
1697 /* Change the remote current process. Which thread within the process
1698 ends up selected isn't important, as long as it is the same process
1699 as what INFERIOR_PTID points to.
1701 This comes from that fact that there is no explicit notion of
1702 "selected process" in the protocol. The selected process for
1703 general operations is the process the selected general thread
1707 set_general_process (void)
1709 struct remote_state *rs = get_remote_state ();
1711 /* If the remote can't handle multiple processes, don't bother. */
1712 if (!remote_multi_process_p (rs))
1715 /* We only need to change the remote current thread if it's pointing
1716 at some other process. */
1717 if (ptid_get_pid (general_thread) != ptid_get_pid (inferior_ptid))
1718 set_general_thread (inferior_ptid);
1722 /* Return nonzero if the thread PTID is still alive on the remote
1726 remote_thread_alive (struct target_ops *ops, ptid_t ptid)
1728 struct remote_state *rs = get_remote_state ();
1731 if (ptid_equal (ptid, magic_null_ptid))
1732 /* The main thread is always alive. */
1735 if (ptid_get_pid (ptid) != 0 && ptid_get_tid (ptid) == 0)
1736 /* The main thread is always alive. This can happen after a
1737 vAttach, if the remote side doesn't support
1742 endp = rs->buf + get_remote_packet_size ();
1745 write_ptid (p, endp, ptid);
1748 getpkt (&rs->buf, &rs->buf_size, 0);
1749 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
1752 /* About these extended threadlist and threadinfo packets. They are
1753 variable length packets but, the fields within them are often fixed
1754 length. They are redundent enough to send over UDP as is the
1755 remote protocol in general. There is a matching unit test module
1758 #define OPAQUETHREADBYTES 8
1760 /* a 64 bit opaque identifier */
1761 typedef unsigned char threadref[OPAQUETHREADBYTES];
1763 /* WARNING: This threadref data structure comes from the remote O.S.,
1764 libstub protocol encoding, and remote.c. It is not particularly
1767 /* Right now, the internal structure is int. We want it to be bigger.
1768 Plan to fix this. */
1770 typedef int gdb_threadref; /* Internal GDB thread reference. */
1772 /* gdb_ext_thread_info is an internal GDB data structure which is
1773 equivalent to the reply of the remote threadinfo packet. */
1775 struct gdb_ext_thread_info
1777 threadref threadid; /* External form of thread reference. */
1778 int active; /* Has state interesting to GDB?
1780 char display[256]; /* Brief state display, name,
1781 blocked/suspended. */
1782 char shortname[32]; /* To be used to name threads. */
1783 char more_display[256]; /* Long info, statistics, queue depth,
1787 /* The volume of remote transfers can be limited by submitting
1788 a mask containing bits specifying the desired information.
1789 Use a union of these values as the 'selection' parameter to
1790 get_thread_info. FIXME: Make these TAG names more thread specific. */
1792 #define TAG_THREADID 1
1793 #define TAG_EXISTS 2
1794 #define TAG_DISPLAY 4
1795 #define TAG_THREADNAME 8
1796 #define TAG_MOREDISPLAY 16
1798 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
1800 char *unpack_varlen_hex (char *buff, ULONGEST *result);
1802 static char *unpack_nibble (char *buf, int *val);
1804 static char *pack_nibble (char *buf, int nibble);
1806 static char *pack_hex_byte (char *pkt, int /* unsigned char */ byte);
1808 static char *unpack_byte (char *buf, int *value);
1810 static char *pack_int (char *buf, int value);
1812 static char *unpack_int (char *buf, int *value);
1814 static char *unpack_string (char *src, char *dest, int length);
1816 static char *pack_threadid (char *pkt, threadref *id);
1818 static char *unpack_threadid (char *inbuf, threadref *id);
1820 void int_to_threadref (threadref *id, int value);
1822 static int threadref_to_int (threadref *ref);
1824 static void copy_threadref (threadref *dest, threadref *src);
1826 static int threadmatch (threadref *dest, threadref *src);
1828 static char *pack_threadinfo_request (char *pkt, int mode,
1831 static int remote_unpack_thread_info_response (char *pkt,
1832 threadref *expectedref,
1833 struct gdb_ext_thread_info
1837 static int remote_get_threadinfo (threadref *threadid,
1838 int fieldset, /*TAG mask */
1839 struct gdb_ext_thread_info *info);
1841 static char *pack_threadlist_request (char *pkt, int startflag,
1843 threadref *nextthread);
1845 static int parse_threadlist_response (char *pkt,
1847 threadref *original_echo,
1848 threadref *resultlist,
1851 static int remote_get_threadlist (int startflag,
1852 threadref *nextthread,
1856 threadref *threadlist);
1858 typedef int (*rmt_thread_action) (threadref *ref, void *context);
1860 static int remote_threadlist_iterator (rmt_thread_action stepfunction,
1861 void *context, int looplimit);
1863 static int remote_newthread_step (threadref *ref, void *context);
1866 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
1867 buffer we're allowed to write to. Returns
1868 BUF+CHARACTERS_WRITTEN. */
1871 write_ptid (char *buf, const char *endbuf, ptid_t ptid)
1874 struct remote_state *rs = get_remote_state ();
1876 if (remote_multi_process_p (rs))
1878 pid = ptid_get_pid (ptid);
1880 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
1882 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
1884 tid = ptid_get_tid (ptid);
1886 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
1888 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
1893 /* Extract a PTID from BUF. If non-null, OBUF is set to the to one
1894 passed the last parsed char. Returns null_ptid on error. */
1897 read_ptid (char *buf, char **obuf)
1901 ULONGEST pid = 0, tid = 0;
1905 /* Multi-process ptid. */
1906 pp = unpack_varlen_hex (p + 1, &pid);
1908 error (_("invalid remote ptid: %s"), p);
1911 pp = unpack_varlen_hex (p + 1, &tid);
1914 return ptid_build (pid, 0, tid);
1917 /* No multi-process. Just a tid. */
1918 pp = unpack_varlen_hex (p, &tid);
1920 /* Since the stub is not sending a process id, then default to
1921 what's in inferior_ptid, unless it's null at this point. If so,
1922 then since there's no way to know the pid of the reported
1923 threads, use the magic number. */
1924 if (ptid_equal (inferior_ptid, null_ptid))
1925 pid = ptid_get_pid (magic_null_ptid);
1927 pid = ptid_get_pid (inferior_ptid);
1931 return ptid_build (pid, 0, tid);
1934 /* Encode 64 bits in 16 chars of hex. */
1936 static const char hexchars[] = "0123456789abcdef";
1939 ishex (int ch, int *val)
1941 if ((ch >= 'a') && (ch <= 'f'))
1943 *val = ch - 'a' + 10;
1946 if ((ch >= 'A') && (ch <= 'F'))
1948 *val = ch - 'A' + 10;
1951 if ((ch >= '0') && (ch <= '9'))
1962 if (ch >= 'a' && ch <= 'f')
1963 return ch - 'a' + 10;
1964 if (ch >= '0' && ch <= '9')
1966 if (ch >= 'A' && ch <= 'F')
1967 return ch - 'A' + 10;
1972 stub_unpack_int (char *buff, int fieldlength)
1979 nibble = stubhex (*buff++);
1983 retval = retval << 4;
1989 unpack_varlen_hex (char *buff, /* packet to parse */
1993 ULONGEST retval = 0;
1995 while (ishex (*buff, &nibble))
1998 retval = retval << 4;
1999 retval |= nibble & 0x0f;
2006 unpack_nibble (char *buf, int *val)
2008 *val = fromhex (*buf++);
2013 pack_nibble (char *buf, int nibble)
2015 *buf++ = hexchars[(nibble & 0x0f)];
2020 pack_hex_byte (char *pkt, int byte)
2022 *pkt++ = hexchars[(byte >> 4) & 0xf];
2023 *pkt++ = hexchars[(byte & 0xf)];
2028 unpack_byte (char *buf, int *value)
2030 *value = stub_unpack_int (buf, 2);
2035 pack_int (char *buf, int value)
2037 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2038 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2039 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2040 buf = pack_hex_byte (buf, (value & 0xff));
2045 unpack_int (char *buf, int *value)
2047 *value = stub_unpack_int (buf, 8);
2051 #if 0 /* Currently unused, uncomment when needed. */
2052 static char *pack_string (char *pkt, char *string);
2055 pack_string (char *pkt, char *string)
2060 len = strlen (string);
2062 len = 200; /* Bigger than most GDB packets, junk??? */
2063 pkt = pack_hex_byte (pkt, len);
2067 if ((ch == '\0') || (ch == '#'))
2068 ch = '*'; /* Protect encapsulation. */
2073 #endif /* 0 (unused) */
2076 unpack_string (char *src, char *dest, int length)
2085 pack_threadid (char *pkt, threadref *id)
2088 unsigned char *altid;
2090 altid = (unsigned char *) id;
2091 limit = pkt + BUF_THREAD_ID_SIZE;
2093 pkt = pack_hex_byte (pkt, *altid++);
2099 unpack_threadid (char *inbuf, threadref *id)
2102 char *limit = inbuf + BUF_THREAD_ID_SIZE;
2105 altref = (char *) id;
2107 while (inbuf < limit)
2109 x = stubhex (*inbuf++);
2110 y = stubhex (*inbuf++);
2111 *altref++ = (x << 4) | y;
2116 /* Externally, threadrefs are 64 bits but internally, they are still
2117 ints. This is due to a mismatch of specifications. We would like
2118 to use 64bit thread references internally. This is an adapter
2122 int_to_threadref (threadref *id, int value)
2124 unsigned char *scan;
2126 scan = (unsigned char *) id;
2132 *scan++ = (value >> 24) & 0xff;
2133 *scan++ = (value >> 16) & 0xff;
2134 *scan++ = (value >> 8) & 0xff;
2135 *scan++ = (value & 0xff);
2139 threadref_to_int (threadref *ref)
2142 unsigned char *scan;
2148 value = (value << 8) | ((*scan++) & 0xff);
2153 copy_threadref (threadref *dest, threadref *src)
2156 unsigned char *csrc, *cdest;
2158 csrc = (unsigned char *) src;
2159 cdest = (unsigned char *) dest;
2166 threadmatch (threadref *dest, threadref *src)
2168 /* Things are broken right now, so just assume we got a match. */
2170 unsigned char *srcp, *destp;
2172 srcp = (char *) src;
2173 destp = (char *) dest;
2177 result &= (*srcp++ == *destp++) ? 1 : 0;
2184 threadid:1, # always request threadid
2191 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
2194 pack_threadinfo_request (char *pkt, int mode, threadref *id)
2196 *pkt++ = 'q'; /* Info Query */
2197 *pkt++ = 'P'; /* process or thread info */
2198 pkt = pack_int (pkt, mode); /* mode */
2199 pkt = pack_threadid (pkt, id); /* threadid */
2200 *pkt = '\0'; /* terminate */
2204 /* These values tag the fields in a thread info response packet. */
2205 /* Tagging the fields allows us to request specific fields and to
2206 add more fields as time goes by. */
2208 #define TAG_THREADID 1 /* Echo the thread identifier. */
2209 #define TAG_EXISTS 2 /* Is this process defined enough to
2210 fetch registers and its stack? */
2211 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
2212 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
2213 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
2217 remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2218 struct gdb_ext_thread_info *info)
2220 struct remote_state *rs = get_remote_state ();
2224 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
2227 /* info->threadid = 0; FIXME: implement zero_threadref. */
2229 info->display[0] = '\0';
2230 info->shortname[0] = '\0';
2231 info->more_display[0] = '\0';
2233 /* Assume the characters indicating the packet type have been
2235 pkt = unpack_int (pkt, &mask); /* arg mask */
2236 pkt = unpack_threadid (pkt, &ref);
2239 warning (_("Incomplete response to threadinfo request."));
2240 if (!threadmatch (&ref, expectedref))
2241 { /* This is an answer to a different request. */
2242 warning (_("ERROR RMT Thread info mismatch."));
2245 copy_threadref (&info->threadid, &ref);
2247 /* Loop on tagged fields , try to bail if somthing goes wrong. */
2249 /* Packets are terminated with nulls. */
2250 while ((pkt < limit) && mask && *pkt)
2252 pkt = unpack_int (pkt, &tag); /* tag */
2253 pkt = unpack_byte (pkt, &length); /* length */
2254 if (!(tag & mask)) /* Tags out of synch with mask. */
2256 warning (_("ERROR RMT: threadinfo tag mismatch."));
2260 if (tag == TAG_THREADID)
2264 warning (_("ERROR RMT: length of threadid is not 16."));
2268 pkt = unpack_threadid (pkt, &ref);
2269 mask = mask & ~TAG_THREADID;
2272 if (tag == TAG_EXISTS)
2274 info->active = stub_unpack_int (pkt, length);
2276 mask = mask & ~(TAG_EXISTS);
2279 warning (_("ERROR RMT: 'exists' length too long."));
2285 if (tag == TAG_THREADNAME)
2287 pkt = unpack_string (pkt, &info->shortname[0], length);
2288 mask = mask & ~TAG_THREADNAME;
2291 if (tag == TAG_DISPLAY)
2293 pkt = unpack_string (pkt, &info->display[0], length);
2294 mask = mask & ~TAG_DISPLAY;
2297 if (tag == TAG_MOREDISPLAY)
2299 pkt = unpack_string (pkt, &info->more_display[0], length);
2300 mask = mask & ~TAG_MOREDISPLAY;
2303 warning (_("ERROR RMT: unknown thread info tag."));
2304 break; /* Not a tag we know about. */
2310 remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
2311 struct gdb_ext_thread_info *info)
2313 struct remote_state *rs = get_remote_state ();
2316 pack_threadinfo_request (rs->buf, fieldset, threadid);
2318 getpkt (&rs->buf, &rs->buf_size, 0);
2320 if (rs->buf[0] == '\0')
2323 result = remote_unpack_thread_info_response (rs->buf + 2,
2328 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
2331 pack_threadlist_request (char *pkt, int startflag, int threadcount,
2332 threadref *nextthread)
2334 *pkt++ = 'q'; /* info query packet */
2335 *pkt++ = 'L'; /* Process LIST or threadLIST request */
2336 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
2337 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
2338 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
2343 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2346 parse_threadlist_response (char *pkt, int result_limit,
2347 threadref *original_echo, threadref *resultlist,
2350 struct remote_state *rs = get_remote_state ();
2352 int count, resultcount, done;
2355 /* Assume the 'q' and 'M chars have been stripped. */
2356 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
2357 /* done parse past here */
2358 pkt = unpack_byte (pkt, &count); /* count field */
2359 pkt = unpack_nibble (pkt, &done);
2360 /* The first threadid is the argument threadid. */
2361 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
2362 while ((count-- > 0) && (pkt < limit))
2364 pkt = unpack_threadid (pkt, resultlist++);
2365 if (resultcount++ >= result_limit)
2374 remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2375 int *done, int *result_count, threadref *threadlist)
2377 struct remote_state *rs = get_remote_state ();
2378 static threadref echo_nextthread;
2381 /* Trancate result limit to be smaller than the packet size. */
2382 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2383 >= get_remote_packet_size ())
2384 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
2386 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2388 getpkt (&rs->buf, &rs->buf_size, 0);
2390 if (*rs->buf == '\0')
2394 parse_threadlist_response (rs->buf + 2, result_limit, &echo_nextthread,
2397 if (!threadmatch (&echo_nextthread, nextthread))
2399 /* FIXME: This is a good reason to drop the packet. */
2400 /* Possably, there is a duplicate response. */
2402 retransmit immediatly - race conditions
2403 retransmit after timeout - yes
2405 wait for packet, then exit
2407 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
2408 return 0; /* I choose simply exiting. */
2410 if (*result_count <= 0)
2414 warning (_("RMT ERROR : failed to get remote thread list."));
2417 return result; /* break; */
2419 if (*result_count > result_limit)
2422 warning (_("RMT ERROR: threadlist response longer than requested."));
2428 /* This is the interface between remote and threads, remotes upper
2431 /* remote_find_new_threads retrieves the thread list and for each
2432 thread in the list, looks up the thread in GDB's internal list,
2433 adding the thread if it does not already exist. This involves
2434 getting partial thread lists from the remote target so, polling the
2435 quit_flag is required. */
2438 /* About this many threadisds fit in a packet. */
2440 #define MAXTHREADLISTRESULTS 32
2443 remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2446 int done, i, result_count;
2450 static threadref nextthread;
2451 static threadref resultthreadlist[MAXTHREADLISTRESULTS];
2456 if (loopcount++ > looplimit)
2459 warning (_("Remote fetch threadlist -infinite loop-."));
2462 if (!remote_get_threadlist (startflag, &nextthread, MAXTHREADLISTRESULTS,
2463 &done, &result_count, resultthreadlist))
2468 /* Clear for later iterations. */
2470 /* Setup to resume next batch of thread references, set nextthread. */
2471 if (result_count >= 1)
2472 copy_threadref (&nextthread, &resultthreadlist[result_count - 1]);
2474 while (result_count--)
2475 if (!(result = (*stepfunction) (&resultthreadlist[i++], context)))
2482 remote_newthread_step (threadref *ref, void *context)
2484 int pid = ptid_get_pid (inferior_ptid);
2485 ptid_t ptid = ptid_build (pid, 0, threadref_to_int (ref));
2487 if (!in_thread_list (ptid))
2489 return 1; /* continue iterator */
2492 #define CRAZY_MAX_THREADS 1000
2495 remote_current_thread (ptid_t oldpid)
2497 struct remote_state *rs = get_remote_state ();
2500 getpkt (&rs->buf, &rs->buf_size, 0);
2501 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
2502 return read_ptid (&rs->buf[2], NULL);
2507 /* Find new threads for info threads command.
2508 * Original version, using John Metzler's thread protocol.
2512 remote_find_new_threads (void)
2514 remote_threadlist_iterator (remote_newthread_step, 0,
2518 #if defined(HAVE_LIBEXPAT)
2520 typedef struct thread_item
2526 DEF_VEC_O(thread_item_t);
2528 struct threads_parsing_context
2530 VEC (thread_item_t) *items;
2534 start_thread (struct gdb_xml_parser *parser,
2535 const struct gdb_xml_element *element,
2536 void *user_data, VEC(gdb_xml_value_s) *attributes)
2538 struct threads_parsing_context *data = user_data;
2540 struct thread_item item;
2542 struct gdb_xml_value *attr;
2544 id = xml_find_attribute (attributes, "id")->value;
2545 item.ptid = read_ptid (id, NULL);
2547 attr = xml_find_attribute (attributes, "core");
2549 item.core = *(ULONGEST *) attr->value;
2555 VEC_safe_push (thread_item_t, data->items, &item);
2559 end_thread (struct gdb_xml_parser *parser,
2560 const struct gdb_xml_element *element,
2561 void *user_data, const char *body_text)
2563 struct threads_parsing_context *data = user_data;
2565 if (body_text && *body_text)
2566 VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
2569 const struct gdb_xml_attribute thread_attributes[] = {
2570 { "id", GDB_XML_AF_NONE, NULL, NULL },
2571 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
2572 { NULL, GDB_XML_AF_NONE, NULL, NULL }
2575 const struct gdb_xml_element thread_children[] = {
2576 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2579 const struct gdb_xml_element threads_children[] = {
2580 { "thread", thread_attributes, thread_children,
2581 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
2582 start_thread, end_thread },
2583 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2586 const struct gdb_xml_element threads_elements[] = {
2587 { "threads", NULL, threads_children,
2588 GDB_XML_EF_NONE, NULL, NULL },
2589 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2592 /* Discard the contents of the constructed thread info context. */
2595 clear_threads_parsing_context (void *p)
2597 struct threads_parsing_context *context = p;
2599 struct thread_item *item;
2601 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2602 xfree (item->extra);
2604 VEC_free (thread_item_t, context->items);
2610 * Find all threads for info threads command.
2611 * Uses new thread protocol contributed by Cisco.
2612 * Falls back and attempts to use the older method (above)
2613 * if the target doesn't respond to the new method.
2617 remote_threads_info (struct target_ops *ops)
2619 struct remote_state *rs = get_remote_state ();
2623 if (remote_desc == 0) /* paranoia */
2624 error (_("Command can only be used when connected to the remote target."));
2626 #if defined(HAVE_LIBEXPAT)
2627 if (remote_protocol_packets[PACKET_qXfer_threads].support == PACKET_ENABLE)
2629 char *xml = target_read_stralloc (¤t_target,
2630 TARGET_OBJECT_THREADS, NULL);
2632 struct cleanup *back_to = make_cleanup (xfree, xml);
2636 struct threads_parsing_context context;
2638 context.items = NULL;
2639 make_cleanup (clear_threads_parsing_context, &context);
2641 if (gdb_xml_parse_quick (_("threads"), "threads.dtd",
2642 threads_elements, xml, &context) == 0)
2645 struct thread_item *item;
2648 VEC_iterate (thread_item_t, context.items, i, item);
2651 if (!ptid_equal (item->ptid, null_ptid))
2653 struct private_thread_info *info;
2654 /* In non-stop mode, we assume new found threads
2655 are running until proven otherwise with a
2656 stop reply. In all-stop, we can only get
2657 here if all threads are stopped. */
2658 int running = non_stop ? 1 : 0;
2660 remote_notice_new_inferior (item->ptid, running);
2662 info = demand_private_info (item->ptid);
2663 info->core = item->core;
2664 info->extra = item->extra;
2671 do_cleanups (back_to);
2676 if (use_threadinfo_query)
2678 putpkt ("qfThreadInfo");
2679 getpkt (&rs->buf, &rs->buf_size, 0);
2681 if (bufp[0] != '\0') /* q packet recognized */
2683 while (*bufp++ == 'm') /* reply contains one or more TID */
2687 new_thread = read_ptid (bufp, &bufp);
2688 if (!ptid_equal (new_thread, null_ptid))
2690 /* In non-stop mode, we assume new found threads
2691 are running until proven otherwise with a
2692 stop reply. In all-stop, we can only get
2693 here if all threads are stopped. */
2694 int running = non_stop ? 1 : 0;
2696 remote_notice_new_inferior (new_thread, running);
2699 while (*bufp++ == ','); /* comma-separated list */
2700 putpkt ("qsThreadInfo");
2701 getpkt (&rs->buf, &rs->buf_size, 0);
2708 /* Only qfThreadInfo is supported in non-stop mode. */
2712 /* Else fall back to old method based on jmetzler protocol. */
2713 use_threadinfo_query = 0;
2714 remote_find_new_threads ();
2719 * Collect a descriptive string about the given thread.
2720 * The target may say anything it wants to about the thread
2721 * (typically info about its blocked / runnable state, name, etc.).
2722 * This string will appear in the info threads display.
2724 * Optional: targets are not required to implement this function.
2728 remote_threads_extra_info (struct thread_info *tp)
2730 struct remote_state *rs = get_remote_state ();
2734 struct gdb_ext_thread_info threadinfo;
2735 static char display_buf[100]; /* arbitrary... */
2736 int n = 0; /* position in display_buf */
2738 if (remote_desc == 0) /* paranoia */
2739 internal_error (__FILE__, __LINE__,
2740 _("remote_threads_extra_info"));
2742 if (ptid_equal (tp->ptid, magic_null_ptid)
2743 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_tid (tp->ptid) == 0))
2744 /* This is the main thread which was added by GDB. The remote
2745 server doesn't know about it. */
2748 if (remote_protocol_packets[PACKET_qXfer_threads].support == PACKET_ENABLE)
2750 struct thread_info *info = find_thread_ptid (tp->ptid);
2752 if (info && info->private)
2753 return info->private->extra;
2758 if (use_threadextra_query)
2761 char *endb = rs->buf + get_remote_packet_size ();
2763 xsnprintf (b, endb - b, "qThreadExtraInfo,");
2765 write_ptid (b, endb, tp->ptid);
2768 getpkt (&rs->buf, &rs->buf_size, 0);
2769 if (rs->buf[0] != 0)
2771 n = min (strlen (rs->buf) / 2, sizeof (display_buf));
2772 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
2773 display_buf [result] = '\0';
2778 /* If the above query fails, fall back to the old method. */
2779 use_threadextra_query = 0;
2780 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
2781 | TAG_MOREDISPLAY | TAG_DISPLAY;
2782 int_to_threadref (&id, ptid_get_tid (tp->ptid));
2783 if (remote_get_threadinfo (&id, set, &threadinfo))
2784 if (threadinfo.active)
2786 if (*threadinfo.shortname)
2787 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
2788 " Name: %s,", threadinfo.shortname);
2789 if (*threadinfo.display)
2790 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
2791 " State: %s,", threadinfo.display);
2792 if (*threadinfo.more_display)
2793 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
2794 " Priority: %s", threadinfo.more_display);
2798 /* For purely cosmetic reasons, clear up trailing commas. */
2799 if (',' == display_buf[n-1])
2800 display_buf[n-1] = ' ';
2809 remote_static_tracepoint_marker_at (CORE_ADDR addr,
2810 struct static_tracepoint_marker *marker)
2812 struct remote_state *rs = get_remote_state ();
2815 sprintf (p, "qTSTMat:");
2817 p += hexnumstr (p, addr);
2819 getpkt (&rs->buf, &rs->buf_size, 0);
2823 error (_("Remote failure reply: %s"), p);
2827 parse_static_tracepoint_marker_definition (p, &p, marker);
2835 free_current_marker (void *arg)
2837 struct static_tracepoint_marker **marker_p = arg;
2839 if (*marker_p != NULL)
2841 release_static_tracepoint_marker (*marker_p);
2848 static VEC(static_tracepoint_marker_p) *
2849 remote_static_tracepoint_markers_by_strid (const char *strid)
2851 struct remote_state *rs = get_remote_state ();
2852 VEC(static_tracepoint_marker_p) *markers = NULL;
2853 struct static_tracepoint_marker *marker = NULL;
2854 struct cleanup *old_chain;
2857 /* Ask for a first packet of static tracepoint marker
2860 getpkt (&rs->buf, &rs->buf_size, 0);
2863 error (_("Remote failure reply: %s"), p);
2865 old_chain = make_cleanup (free_current_marker, &marker);
2870 marker = XCNEW (struct static_tracepoint_marker);
2874 parse_static_tracepoint_marker_definition (p, &p, marker);
2876 if (strid == NULL || strcmp (strid, marker->str_id) == 0)
2878 VEC_safe_push (static_tracepoint_marker_p,
2884 release_static_tracepoint_marker (marker);
2885 memset (marker, 0, sizeof (*marker));
2888 while (*p++ == ','); /* comma-separated list */
2889 /* Ask for another packet of static tracepoint definition. */
2891 getpkt (&rs->buf, &rs->buf_size, 0);
2895 do_cleanups (old_chain);
2900 /* Implement the to_get_ada_task_ptid function for the remote targets. */
2903 remote_get_ada_task_ptid (long lwp, long thread)
2905 return ptid_build (ptid_get_pid (inferior_ptid), 0, lwp);
2909 /* Restart the remote side; this is an extended protocol operation. */
2912 extended_remote_restart (void)
2914 struct remote_state *rs = get_remote_state ();
2916 /* Send the restart command; for reasons I don't understand the
2917 remote side really expects a number after the "R". */
2918 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
2921 remote_fileio_reset ();
2924 /* Clean up connection to a remote debugger. */
2927 remote_close (int quitting)
2929 if (remote_desc == NULL)
2930 return; /* already closed */
2932 /* Make sure we leave stdin registered in the event loop, and we
2933 don't leave the async SIGINT signal handler installed. */
2934 remote_terminal_ours ();
2936 serial_close (remote_desc);
2939 /* We don't have a connection to the remote stub anymore. Get rid
2940 of all the inferiors and their threads we were controlling.
2941 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
2942 will be unable to find the thread corresponding to (pid, 0, 0). */
2943 inferior_ptid = null_ptid;
2944 discard_all_inferiors ();
2946 /* We're no longer interested in any of these events. */
2947 discard_pending_stop_replies (-1);
2949 if (remote_async_inferior_event_token)
2950 delete_async_event_handler (&remote_async_inferior_event_token);
2951 if (remote_async_get_pending_events_token)
2952 delete_async_event_handler (&remote_async_get_pending_events_token);
2955 /* Query the remote side for the text, data and bss offsets. */
2960 struct remote_state *rs = get_remote_state ();
2963 int lose, num_segments = 0, do_sections, do_segments;
2964 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
2965 struct section_offsets *offs;
2966 struct symfile_segment_data *data;
2968 if (symfile_objfile == NULL)
2971 putpkt ("qOffsets");
2972 getpkt (&rs->buf, &rs->buf_size, 0);
2975 if (buf[0] == '\000')
2976 return; /* Return silently. Stub doesn't support
2980 warning (_("Remote failure reply: %s"), buf);
2984 /* Pick up each field in turn. This used to be done with scanf, but
2985 scanf will make trouble if CORE_ADDR size doesn't match
2986 conversion directives correctly. The following code will work
2987 with any size of CORE_ADDR. */
2988 text_addr = data_addr = bss_addr = 0;
2992 if (strncmp (ptr, "Text=", 5) == 0)
2995 /* Don't use strtol, could lose on big values. */
2996 while (*ptr && *ptr != ';')
2997 text_addr = (text_addr << 4) + fromhex (*ptr++);
2999 if (strncmp (ptr, ";Data=", 6) == 0)
3002 while (*ptr && *ptr != ';')
3003 data_addr = (data_addr << 4) + fromhex (*ptr++);
3008 if (!lose && strncmp (ptr, ";Bss=", 5) == 0)
3011 while (*ptr && *ptr != ';')
3012 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
3014 if (bss_addr != data_addr)
3015 warning (_("Target reported unsupported offsets: %s"), buf);
3020 else if (strncmp (ptr, "TextSeg=", 8) == 0)
3023 /* Don't use strtol, could lose on big values. */
3024 while (*ptr && *ptr != ';')
3025 text_addr = (text_addr << 4) + fromhex (*ptr++);
3028 if (strncmp (ptr, ";DataSeg=", 9) == 0)
3031 while (*ptr && *ptr != ';')
3032 data_addr = (data_addr << 4) + fromhex (*ptr++);
3040 error (_("Malformed response to offset query, %s"), buf);
3041 else if (*ptr != '\0')
3042 warning (_("Target reported unsupported offsets: %s"), buf);
3044 offs = ((struct section_offsets *)
3045 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
3046 memcpy (offs, symfile_objfile->section_offsets,
3047 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
3049 data = get_symfile_segment_data (symfile_objfile->obfd);
3050 do_segments = (data != NULL);
3051 do_sections = num_segments == 0;
3053 if (num_segments > 0)
3055 segments[0] = text_addr;
3056 segments[1] = data_addr;
3058 /* If we have two segments, we can still try to relocate everything
3059 by assuming that the .text and .data offsets apply to the whole
3060 text and data segments. Convert the offsets given in the packet
3061 to base addresses for symfile_map_offsets_to_segments. */
3062 else if (data && data->num_segments == 2)
3064 segments[0] = data->segment_bases[0] + text_addr;
3065 segments[1] = data->segment_bases[1] + data_addr;
3068 /* If the object file has only one segment, assume that it is text
3069 rather than data; main programs with no writable data are rare,
3070 but programs with no code are useless. Of course the code might
3071 have ended up in the data segment... to detect that we would need
3072 the permissions here. */
3073 else if (data && data->num_segments == 1)
3075 segments[0] = data->segment_bases[0] + text_addr;
3078 /* There's no way to relocate by segment. */
3084 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3085 offs, num_segments, segments);
3087 if (ret == 0 && !do_sections)
3088 error (_("Can not handle qOffsets TextSeg "
3089 "response with this symbol file"));
3096 free_symfile_segment_data (data);
3100 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3102 /* This is a temporary kludge to force data and bss to use the
3103 same offsets because that's what nlmconv does now. The real
3104 solution requires changes to the stub and remote.c that I
3105 don't have time to do right now. */
3107 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3108 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3111 objfile_relocate (symfile_objfile, offs);
3114 /* Callback for iterate_over_threads. Set the STOP_REQUESTED flags in
3115 threads we know are stopped already. This is used during the
3116 initial remote connection in non-stop mode --- threads that are
3117 reported as already being stopped are left stopped. */
3120 set_stop_requested_callback (struct thread_info *thread, void *data)
3122 /* If we have a stop reply for this thread, it must be stopped. */
3123 if (peek_stop_reply (thread->ptid))
3124 set_stop_requested (thread->ptid, 1);
3129 /* Send interrupt_sequence to remote target. */
3131 send_interrupt_sequence (void)
3133 if (interrupt_sequence_mode == interrupt_sequence_control_c)
3134 serial_write (remote_desc, "\x03", 1);
3135 else if (interrupt_sequence_mode == interrupt_sequence_break)
3136 serial_send_break (remote_desc);
3137 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3139 serial_send_break (remote_desc);
3140 serial_write (remote_desc, "g", 1);
3143 internal_error (__FILE__, __LINE__,
3144 _("Invalid value for interrupt_sequence_mode: %s."),
3145 interrupt_sequence_mode);
3149 remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
3151 struct remote_state *rs = get_remote_state ();
3152 struct packet_config *noack_config;
3153 char *wait_status = NULL;
3155 immediate_quit++; /* Allow user to interrupt it. */
3157 if (interrupt_on_connect)
3158 send_interrupt_sequence ();
3160 /* Ack any packet which the remote side has already sent. */
3161 serial_write (remote_desc, "+", 1);
3163 /* The first packet we send to the target is the optional "supported
3164 packets" request. If the target can answer this, it will tell us
3165 which later probes to skip. */
3166 remote_query_supported ();
3168 /* If the stub wants to get a QAllow, compose one and send it. */
3169 if (remote_protocol_packets[PACKET_QAllow].support != PACKET_DISABLE)
3170 remote_set_permissions ();
3172 /* Next, we possibly activate noack mode.
3174 If the QStartNoAckMode packet configuration is set to AUTO,
3175 enable noack mode if the stub reported a wish for it with
3178 If set to TRUE, then enable noack mode even if the stub didn't
3179 report it in qSupported. If the stub doesn't reply OK, the
3180 session ends with an error.
3182 If FALSE, then don't activate noack mode, regardless of what the
3183 stub claimed should be the default with qSupported. */
3185 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
3187 if (noack_config->detect == AUTO_BOOLEAN_TRUE
3188 || (noack_config->detect == AUTO_BOOLEAN_AUTO
3189 && noack_config->support == PACKET_ENABLE))
3191 putpkt ("QStartNoAckMode");
3192 getpkt (&rs->buf, &rs->buf_size, 0);
3193 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
3199 /* Tell the remote that we are using the extended protocol. */
3201 getpkt (&rs->buf, &rs->buf_size, 0);
3204 /* Next, if the target can specify a description, read it. We do
3205 this before anything involving memory or registers. */
3206 target_find_description ();
3208 /* Next, now that we know something about the target, update the
3209 address spaces in the program spaces. */
3210 update_address_spaces ();
3212 /* On OSs where the list of libraries is global to all
3213 processes, we fetch them early. */
3214 if (gdbarch_has_global_solist (target_gdbarch))
3215 solib_add (NULL, from_tty, target, auto_solib_add);
3219 if (!rs->non_stop_aware)
3220 error (_("Non-stop mode requested, but remote "
3221 "does not support non-stop"));
3223 putpkt ("QNonStop:1");
3224 getpkt (&rs->buf, &rs->buf_size, 0);
3226 if (strcmp (rs->buf, "OK") != 0)
3227 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
3229 /* Find about threads and processes the stub is already
3230 controlling. We default to adding them in the running state.
3231 The '?' query below will then tell us about which threads are
3233 remote_threads_info (target);
3235 else if (rs->non_stop_aware)
3237 /* Don't assume that the stub can operate in all-stop mode.
3238 Request it explicitely. */
3239 putpkt ("QNonStop:0");
3240 getpkt (&rs->buf, &rs->buf_size, 0);
3242 if (strcmp (rs->buf, "OK") != 0)
3243 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
3246 /* Check whether the target is running now. */
3248 getpkt (&rs->buf, &rs->buf_size, 0);
3252 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
3255 error (_("The target is not running (try extended-remote?)"));
3257 /* We're connected, but not running. Drop out before we
3258 call start_remote. */
3263 /* Save the reply for later. */
3264 wait_status = alloca (strlen (rs->buf) + 1);
3265 strcpy (wait_status, rs->buf);
3268 /* Let the stub know that we want it to return the thread. */
3269 set_continue_thread (minus_one_ptid);
3271 /* Without this, some commands which require an active target
3272 (such as kill) won't work. This variable serves (at least)
3273 double duty as both the pid of the target process (if it has
3274 such), and as a flag indicating that a target is active.
3275 These functions should be split out into seperate variables,
3276 especially since GDB will someday have a notion of debugging
3277 several processes. */
3278 inferior_ptid = magic_null_ptid;
3280 /* Now, if we have thread information, update inferior_ptid. */
3281 inferior_ptid = remote_current_thread (inferior_ptid);
3283 remote_add_inferior (ptid_get_pid (inferior_ptid), -1);
3285 /* Always add the main thread. */
3286 add_thread_silent (inferior_ptid);
3288 /* init_wait_for_inferior should be called before get_offsets in order
3289 to manage `inserted' flag in bp loc in a correct state.
3290 breakpoint_init_inferior, called from init_wait_for_inferior, set
3291 `inserted' flag to 0, while before breakpoint_re_set, called from
3292 start_remote, set `inserted' flag to 1. In the initialization of
3293 inferior, breakpoint_init_inferior should be called first, and then
3294 breakpoint_re_set can be called. If this order is broken, state of
3295 `inserted' flag is wrong, and cause some problems on breakpoint
3297 init_wait_for_inferior ();
3299 get_offsets (); /* Get text, data & bss offsets. */
3301 /* If we could not find a description using qXfer, and we know
3302 how to do it some other way, try again. This is not
3303 supported for non-stop; it could be, but it is tricky if
3304 there are no stopped threads when we connect. */
3305 if (remote_read_description_p (target)
3306 && gdbarch_target_desc (target_gdbarch) == NULL)
3308 target_clear_description ();
3309 target_find_description ();
3312 /* Use the previously fetched status. */
3313 gdb_assert (wait_status != NULL);
3314 strcpy (rs->buf, wait_status);
3315 rs->cached_wait_status = 1;
3318 start_remote (from_tty); /* Initialize gdb process mechanisms. */
3322 /* Clear WFI global state. Do this before finding about new
3323 threads and inferiors, and setting the current inferior.
3324 Otherwise we would clear the proceed status of the current
3325 inferior when we want its stop_soon state to be preserved
3326 (see notice_new_inferior). */
3327 init_wait_for_inferior ();
3329 /* In non-stop, we will either get an "OK", meaning that there
3330 are no stopped threads at this time; or, a regular stop
3331 reply. In the latter case, there may be more than one thread
3332 stopped --- we pull them all out using the vStopped
3334 if (strcmp (rs->buf, "OK") != 0)
3336 struct stop_reply *stop_reply;
3337 struct cleanup *old_chain;
3339 stop_reply = stop_reply_xmalloc ();
3340 old_chain = make_cleanup (do_stop_reply_xfree, stop_reply);
3342 remote_parse_stop_reply (rs->buf, stop_reply);
3343 discard_cleanups (old_chain);
3345 /* get_pending_stop_replies acks this one, and gets the rest
3347 pending_stop_reply = stop_reply;
3348 remote_get_pending_stop_replies ();
3350 /* Make sure that threads that were stopped remain
3352 iterate_over_threads (set_stop_requested_callback, NULL);
3355 if (target_can_async_p ())
3356 target_async (inferior_event_handler, 0);
3358 if (thread_count () == 0)
3361 error (_("The target is not running (try extended-remote?)"));
3363 /* We're connected, but not running. Drop out before we
3364 call start_remote. */
3368 /* Let the stub know that we want it to return the thread. */
3370 /* Force the stub to choose a thread. */
3371 set_general_thread (null_ptid);
3374 inferior_ptid = remote_current_thread (minus_one_ptid);
3375 if (ptid_equal (inferior_ptid, minus_one_ptid))
3376 error (_("remote didn't report the current thread in non-stop mode"));
3378 get_offsets (); /* Get text, data & bss offsets. */
3380 /* In non-stop mode, any cached wait status will be stored in
3381 the stop reply queue. */
3382 gdb_assert (wait_status == NULL);
3384 /* Report all signals during attach/startup. */
3385 remote_pass_signals (0, NULL);
3388 /* If we connected to a live target, do some additional setup. */
3389 if (target_has_execution)
3391 if (exec_bfd) /* No use without an exec file. */
3392 remote_check_symbols (symfile_objfile);
3395 /* Possibly the target has been engaged in a trace run started
3396 previously; find out where things are at. */
3397 if (remote_get_trace_status (current_trace_status ()) != -1)
3399 struct uploaded_tp *uploaded_tps = NULL;
3400 struct uploaded_tsv *uploaded_tsvs = NULL;
3402 if (current_trace_status ()->running)
3403 printf_filtered (_("Trace is already running on the target.\n"));
3405 /* Get trace state variables first, they may be checked when
3406 parsing uploaded commands. */
3408 remote_upload_trace_state_variables (&uploaded_tsvs);
3410 merge_uploaded_trace_state_variables (&uploaded_tsvs);
3412 remote_upload_tracepoints (&uploaded_tps);
3414 merge_uploaded_tracepoints (&uploaded_tps);
3417 /* If breakpoints are global, insert them now. */
3418 if (gdbarch_has_global_breakpoints (target_gdbarch)
3419 && breakpoints_always_inserted_mode ())
3420 insert_breakpoints ();
3423 /* Open a connection to a remote debugger.
3424 NAME is the filename used for communication. */
3427 remote_open (char *name, int from_tty)
3429 remote_open_1 (name, from_tty, &remote_ops, 0);
3432 /* Open a connection to a remote debugger using the extended
3433 remote gdb protocol. NAME is the filename used for communication. */
3436 extended_remote_open (char *name, int from_tty)
3438 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
3441 /* Generic code for opening a connection to a remote target. */
3444 init_all_packet_configs (void)
3448 for (i = 0; i < PACKET_MAX; i++)
3449 update_packet_config (&remote_protocol_packets[i]);
3452 /* Symbol look-up. */
3455 remote_check_symbols (struct objfile *objfile)
3457 struct remote_state *rs = get_remote_state ();
3458 char *msg, *reply, *tmp;
3459 struct minimal_symbol *sym;
3462 /* The remote side has no concept of inferiors that aren't running
3463 yet, it only knows about running processes. If we're connected
3464 but our current inferior is not running, we should not invite the
3465 remote target to request symbol lookups related to its
3466 (unrelated) current process. */
3467 if (!target_has_execution)
3470 if (remote_protocol_packets[PACKET_qSymbol].support == PACKET_DISABLE)
3473 /* Make sure the remote is pointing at the right process. Note
3474 there's no way to select "no process". */
3475 set_general_process ();
3477 /* Allocate a message buffer. We can't reuse the input buffer in RS,
3478 because we need both at the same time. */
3479 msg = alloca (get_remote_packet_size ());
3481 /* Invite target to request symbol lookups. */
3483 putpkt ("qSymbol::");
3484 getpkt (&rs->buf, &rs->buf_size, 0);
3485 packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSymbol]);
3488 while (strncmp (reply, "qSymbol:", 8) == 0)
3491 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
3493 sym = lookup_minimal_symbol (msg, NULL, NULL);
3495 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
3498 int addr_size = gdbarch_addr_bit (target_gdbarch) / 8;
3499 CORE_ADDR sym_addr = SYMBOL_VALUE_ADDRESS (sym);
3501 /* If this is a function address, return the start of code
3502 instead of any data function descriptor. */
3503 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch,
3507 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
3508 phex_nz (sym_addr, addr_size), &reply[8]);
3512 getpkt (&rs->buf, &rs->buf_size, 0);
3517 static struct serial *
3518 remote_serial_open (char *name)
3520 static int udp_warning = 0;
3522 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
3523 of in ser-tcp.c, because it is the remote protocol assuming that the
3524 serial connection is reliable and not the serial connection promising
3526 if (!udp_warning && strncmp (name, "udp:", 4) == 0)
3528 warning (_("The remote protocol may be unreliable over UDP.\n"
3529 "Some events may be lost, rendering further debugging "
3534 return serial_open (name);
3537 /* Inform the target of our permission settings. The permission flags
3538 work without this, but if the target knows the settings, it can do
3539 a couple things. First, it can add its own check, to catch cases
3540 that somehow manage to get by the permissions checks in target
3541 methods. Second, if the target is wired to disallow particular
3542 settings (for instance, a system in the field that is not set up to
3543 be able to stop at a breakpoint), it can object to any unavailable
3547 remote_set_permissions (void)
3549 struct remote_state *rs = get_remote_state ();
3551 sprintf (rs->buf, "QAllow:"
3552 "WriteReg:%x;WriteMem:%x;"
3553 "InsertBreak:%x;InsertTrace:%x;"
3554 "InsertFastTrace:%x;Stop:%x",
3555 may_write_registers, may_write_memory,
3556 may_insert_breakpoints, may_insert_tracepoints,
3557 may_insert_fast_tracepoints, may_stop);
3559 getpkt (&rs->buf, &rs->buf_size, 0);
3561 /* If the target didn't like the packet, warn the user. Do not try
3562 to undo the user's settings, that would just be maddening. */
3563 if (strcmp (rs->buf, "OK") != 0)
3564 warning (_("Remote refused setting permissions with: %s"), rs->buf);
3567 /* This type describes each known response to the qSupported
3569 struct protocol_feature
3571 /* The name of this protocol feature. */
3574 /* The default for this protocol feature. */
3575 enum packet_support default_support;
3577 /* The function to call when this feature is reported, or after
3578 qSupported processing if the feature is not supported.
3579 The first argument points to this structure. The second
3580 argument indicates whether the packet requested support be
3581 enabled, disabled, or probed (or the default, if this function
3582 is being called at the end of processing and this feature was
3583 not reported). The third argument may be NULL; if not NULL, it
3584 is a NUL-terminated string taken from the packet following
3585 this feature's name and an equals sign. */
3586 void (*func) (const struct protocol_feature *, enum packet_support,
3589 /* The corresponding packet for this feature. Only used if
3590 FUNC is remote_supported_packet. */
3595 remote_supported_packet (const struct protocol_feature *feature,
3596 enum packet_support support,
3597 const char *argument)
3601 warning (_("Remote qSupported response supplied an unexpected value for"
3602 " \"%s\"."), feature->name);
3606 if (remote_protocol_packets[feature->packet].support
3607 == PACKET_SUPPORT_UNKNOWN)
3608 remote_protocol_packets[feature->packet].support = support;
3612 remote_packet_size (const struct protocol_feature *feature,
3613 enum packet_support support, const char *value)
3615 struct remote_state *rs = get_remote_state ();
3620 if (support != PACKET_ENABLE)
3623 if (value == NULL || *value == '\0')
3625 warning (_("Remote target reported \"%s\" without a size."),
3631 packet_size = strtol (value, &value_end, 16);
3632 if (errno != 0 || *value_end != '\0' || packet_size < 0)
3634 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
3635 feature->name, value);
3639 if (packet_size > MAX_REMOTE_PACKET_SIZE)
3641 warning (_("limiting remote suggested packet size (%d bytes) to %d"),
3642 packet_size, MAX_REMOTE_PACKET_SIZE);
3643 packet_size = MAX_REMOTE_PACKET_SIZE;
3646 /* Record the new maximum packet size. */
3647 rs->explicit_packet_size = packet_size;
3651 remote_multi_process_feature (const struct protocol_feature *feature,
3652 enum packet_support support, const char *value)
3654 struct remote_state *rs = get_remote_state ();
3656 rs->multi_process_aware = (support == PACKET_ENABLE);
3660 remote_non_stop_feature (const struct protocol_feature *feature,
3661 enum packet_support support, const char *value)
3663 struct remote_state *rs = get_remote_state ();
3665 rs->non_stop_aware = (support == PACKET_ENABLE);
3669 remote_cond_tracepoint_feature (const struct protocol_feature *feature,
3670 enum packet_support support,
3673 struct remote_state *rs = get_remote_state ();
3675 rs->cond_tracepoints = (support == PACKET_ENABLE);
3679 remote_fast_tracepoint_feature (const struct protocol_feature *feature,
3680 enum packet_support support,
3683 struct remote_state *rs = get_remote_state ();
3685 rs->fast_tracepoints = (support == PACKET_ENABLE);
3689 remote_static_tracepoint_feature (const struct protocol_feature *feature,
3690 enum packet_support support,
3693 struct remote_state *rs = get_remote_state ();
3695 rs->static_tracepoints = (support == PACKET_ENABLE);
3699 remote_disconnected_tracing_feature (const struct protocol_feature *feature,
3700 enum packet_support support,
3703 struct remote_state *rs = get_remote_state ();
3705 rs->disconnected_tracing = (support == PACKET_ENABLE);
3709 remote_enable_disable_tracepoint_feature (const struct protocol_feature *feature,
3710 enum packet_support support,
3713 struct remote_state *rs = get_remote_state ();
3715 rs->enable_disable_tracepoints = (support == PACKET_ENABLE);
3719 remote_string_tracing_feature (const struct protocol_feature *feature,
3720 enum packet_support support,
3723 struct remote_state *rs = get_remote_state ();
3725 rs->string_tracing = (support == PACKET_ENABLE);
3728 static struct protocol_feature remote_protocol_features[] = {
3729 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
3730 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
3731 PACKET_qXfer_auxv },
3732 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
3733 PACKET_qXfer_features },
3734 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
3735 PACKET_qXfer_libraries },
3736 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
3737 PACKET_qXfer_memory_map },
3738 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
3739 PACKET_qXfer_spu_read },
3740 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
3741 PACKET_qXfer_spu_write },
3742 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
3743 PACKET_qXfer_osdata },
3744 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
3745 PACKET_qXfer_threads },
3746 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
3747 PACKET_qXfer_traceframe_info },
3748 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
3749 PACKET_QPassSignals },
3750 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
3751 PACKET_QStartNoAckMode },
3752 { "multiprocess", PACKET_DISABLE, remote_multi_process_feature, -1 },
3753 { "QNonStop", PACKET_DISABLE, remote_non_stop_feature, -1 },
3754 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
3755 PACKET_qXfer_siginfo_read },
3756 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
3757 PACKET_qXfer_siginfo_write },
3758 { "ConditionalTracepoints", PACKET_DISABLE, remote_cond_tracepoint_feature,
3759 PACKET_ConditionalTracepoints },
3760 { "FastTracepoints", PACKET_DISABLE, remote_fast_tracepoint_feature,
3761 PACKET_FastTracepoints },
3762 { "StaticTracepoints", PACKET_DISABLE, remote_static_tracepoint_feature,
3763 PACKET_StaticTracepoints },
3764 { "DisconnectedTracing", PACKET_DISABLE, remote_disconnected_tracing_feature,
3766 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
3768 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
3770 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
3771 PACKET_TracepointSource },
3772 { "QAllow", PACKET_DISABLE, remote_supported_packet,
3774 { "EnableDisableTracepoints", PACKET_DISABLE,
3775 remote_enable_disable_tracepoint_feature, -1 },
3776 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
3777 PACKET_qXfer_fdpic },
3778 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
3779 PACKET_QDisableRandomization },
3780 { "tracenz", PACKET_DISABLE,
3781 remote_string_tracing_feature, -1 },
3784 static char *remote_support_xml;
3786 /* Register string appended to "xmlRegisters=" in qSupported query. */
3789 register_remote_support_xml (const char *xml)
3791 #if defined(HAVE_LIBEXPAT)
3792 if (remote_support_xml == NULL)
3793 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
3796 char *copy = xstrdup (remote_support_xml + 13);
3797 char *p = strtok (copy, ",");
3801 if (strcmp (p, xml) == 0)
3808 while ((p = strtok (NULL, ",")) != NULL);
3811 remote_support_xml = reconcat (remote_support_xml,
3812 remote_support_xml, ",", xml,
3819 remote_query_supported_append (char *msg, const char *append)
3822 return reconcat (msg, msg, ";", append, (char *) NULL);
3824 return xstrdup (append);
3828 remote_query_supported (void)
3830 struct remote_state *rs = get_remote_state ();
3833 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
3835 /* The packet support flags are handled differently for this packet
3836 than for most others. We treat an error, a disabled packet, and
3837 an empty response identically: any features which must be reported
3838 to be used will be automatically disabled. An empty buffer
3839 accomplishes this, since that is also the representation for a list
3840 containing no features. */
3843 if (remote_protocol_packets[PACKET_qSupported].support != PACKET_DISABLE)
3846 struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
3849 q = remote_query_supported_append (q, "multiprocess+");
3851 if (remote_support_xml)
3852 q = remote_query_supported_append (q, remote_support_xml);
3854 q = remote_query_supported_append (q, "qRelocInsn+");
3856 q = reconcat (q, "qSupported:", q, (char *) NULL);
3859 do_cleanups (old_chain);
3861 getpkt (&rs->buf, &rs->buf_size, 0);
3863 /* If an error occured, warn, but do not return - just reset the
3864 buffer to empty and go on to disable features. */
3865 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
3868 warning (_("Remote failure reply: %s"), rs->buf);
3873 memset (seen, 0, sizeof (seen));
3878 enum packet_support is_supported;
3879 char *p, *end, *name_end, *value;
3881 /* First separate out this item from the rest of the packet. If
3882 there's another item after this, we overwrite the separator
3883 (terminated strings are much easier to work with). */
3885 end = strchr (p, ';');
3888 end = p + strlen (p);
3898 warning (_("empty item in \"qSupported\" response"));
3903 name_end = strchr (p, '=');
3906 /* This is a name=value entry. */
3907 is_supported = PACKET_ENABLE;
3908 value = name_end + 1;
3917 is_supported = PACKET_ENABLE;
3921 is_supported = PACKET_DISABLE;
3925 is_supported = PACKET_SUPPORT_UNKNOWN;
3929 warning (_("unrecognized item \"%s\" "
3930 "in \"qSupported\" response"), p);
3936 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
3937 if (strcmp (remote_protocol_features[i].name, p) == 0)
3939 const struct protocol_feature *feature;
3942 feature = &remote_protocol_features[i];
3943 feature->func (feature, is_supported, value);
3948 /* If we increased the packet size, make sure to increase the global
3949 buffer size also. We delay this until after parsing the entire
3950 qSupported packet, because this is the same buffer we were
3952 if (rs->buf_size < rs->explicit_packet_size)
3954 rs->buf_size = rs->explicit_packet_size;
3955 rs->buf = xrealloc (rs->buf, rs->buf_size);
3958 /* Handle the defaults for unmentioned features. */
3959 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
3962 const struct protocol_feature *feature;
3964 feature = &remote_protocol_features[i];
3965 feature->func (feature, feature->default_support, NULL);
3971 remote_open_1 (char *name, int from_tty,
3972 struct target_ops *target, int extended_p)
3974 struct remote_state *rs = get_remote_state ();
3977 error (_("To open a remote debug connection, you need to specify what\n"
3978 "serial device is attached to the remote system\n"
3979 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
3981 /* See FIXME above. */
3982 if (!target_async_permitted)
3983 wait_forever_enabled_p = 1;
3985 /* If we're connected to a running target, target_preopen will kill it.
3986 But if we're connected to a target system with no running process,
3987 then we will still be connected when it returns. Ask this question
3988 first, before target_preopen has a chance to kill anything. */
3989 if (remote_desc != NULL && !have_inferiors ())
3992 || query (_("Already connected to a remote target. Disconnect? ")))
3995 error (_("Still connected."));
3998 target_preopen (from_tty);
4000 unpush_target (target);
4002 /* This time without a query. If we were connected to an
4003 extended-remote target and target_preopen killed the running
4004 process, we may still be connected. If we are starting "target
4005 remote" now, the extended-remote target will not have been
4006 removed by unpush_target. */
4007 if (remote_desc != NULL && !have_inferiors ())
4010 /* Make sure we send the passed signals list the next time we resume. */
4011 xfree (last_pass_packet);
4012 last_pass_packet = NULL;
4014 remote_fileio_reset ();
4015 reopen_exec_file ();
4018 remote_desc = remote_serial_open (name);
4020 perror_with_name (name);
4022 if (baud_rate != -1)
4024 if (serial_setbaudrate (remote_desc, baud_rate))
4026 /* The requested speed could not be set. Error out to
4027 top level after closing remote_desc. Take care to
4028 set remote_desc to NULL to avoid closing remote_desc
4030 serial_close (remote_desc);
4032 perror_with_name (name);
4036 serial_raw (remote_desc);
4038 /* If there is something sitting in the buffer we might take it as a
4039 response to a command, which would be bad. */
4040 serial_flush_input (remote_desc);
4044 puts_filtered ("Remote debugging using ");
4045 puts_filtered (name);
4046 puts_filtered ("\n");
4048 push_target (target); /* Switch to using remote target now. */
4050 /* Register extra event sources in the event loop. */
4051 remote_async_inferior_event_token
4052 = create_async_event_handler (remote_async_inferior_event_handler,
4054 remote_async_get_pending_events_token
4055 = create_async_event_handler (remote_async_get_pending_events_handler,
4058 /* Reset the target state; these things will be queried either by
4059 remote_query_supported or as they are needed. */
4060 init_all_packet_configs ();
4061 rs->cached_wait_status = 0;
4062 rs->explicit_packet_size = 0;
4064 rs->multi_process_aware = 0;
4065 rs->extended = extended_p;
4066 rs->non_stop_aware = 0;
4067 rs->waiting_for_stop_reply = 0;
4068 rs->ctrlc_pending_p = 0;
4070 general_thread = not_sent_ptid;
4071 continue_thread = not_sent_ptid;
4072 remote_traceframe_number = -1;
4074 /* Probe for ability to use "ThreadInfo" query, as required. */
4075 use_threadinfo_query = 1;
4076 use_threadextra_query = 1;
4078 if (target_async_permitted)
4080 /* With this target we start out by owning the terminal. */
4081 remote_async_terminal_ours_p = 1;
4083 /* FIXME: cagney/1999-09-23: During the initial connection it is
4084 assumed that the target is already ready and able to respond to
4085 requests. Unfortunately remote_start_remote() eventually calls
4086 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
4087 around this. Eventually a mechanism that allows
4088 wait_for_inferior() to expect/get timeouts will be
4090 wait_forever_enabled_p = 0;
4093 /* First delete any symbols previously loaded from shared libraries. */
4094 no_shared_libraries (NULL, 0);
4097 init_thread_list ();
4099 /* Start the remote connection. If error() or QUIT, discard this
4100 target (we'd otherwise be in an inconsistent state) and then
4101 propogate the error on up the exception chain. This ensures that
4102 the caller doesn't stumble along blindly assuming that the
4103 function succeeded. The CLI doesn't have this problem but other
4104 UI's, such as MI do.
4106 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
4107 this function should return an error indication letting the
4108 caller restore the previous state. Unfortunately the command
4109 ``target remote'' is directly wired to this function making that
4110 impossible. On a positive note, the CLI side of this problem has
4111 been fixed - the function set_cmd_context() makes it possible for
4112 all the ``target ....'' commands to share a common callback
4113 function. See cli-dump.c. */
4115 volatile struct gdb_exception ex;
4117 TRY_CATCH (ex, RETURN_MASK_ALL)
4119 remote_start_remote (from_tty, target, extended_p);
4123 /* Pop the partially set up target - unless something else did
4124 already before throwing the exception. */
4125 if (remote_desc != NULL)
4127 if (target_async_permitted)
4128 wait_forever_enabled_p = 1;
4129 throw_exception (ex);
4133 if (target_async_permitted)
4134 wait_forever_enabled_p = 1;
4137 /* This takes a program previously attached to and detaches it. After
4138 this is done, GDB can be used to debug some other program. We
4139 better not have left any breakpoints in the target program or it'll
4140 die when it hits one. */
4143 remote_detach_1 (char *args, int from_tty, int extended)
4145 int pid = ptid_get_pid (inferior_ptid);
4146 struct remote_state *rs = get_remote_state ();
4149 error (_("Argument given to \"detach\" when remotely debugging."));
4151 if (!target_has_execution)
4152 error (_("No process to detach from."));
4154 /* Tell the remote target to detach. */
4155 if (remote_multi_process_p (rs))
4156 sprintf (rs->buf, "D;%x", pid);
4158 strcpy (rs->buf, "D");
4161 getpkt (&rs->buf, &rs->buf_size, 0);
4163 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
4165 else if (rs->buf[0] == '\0')
4166 error (_("Remote doesn't know how to detach"));
4168 error (_("Can't detach process."));
4172 if (remote_multi_process_p (rs))
4173 printf_filtered (_("Detached from remote %s.\n"),
4174 target_pid_to_str (pid_to_ptid (pid)));
4178 puts_filtered (_("Detached from remote process.\n"));
4180 puts_filtered (_("Ending remote debugging.\n"));
4184 discard_pending_stop_replies (pid);
4185 target_mourn_inferior ();
4189 remote_detach (struct target_ops *ops, char *args, int from_tty)
4191 remote_detach_1 (args, from_tty, 0);
4195 extended_remote_detach (struct target_ops *ops, char *args, int from_tty)
4197 remote_detach_1 (args, from_tty, 1);
4200 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
4203 remote_disconnect (struct target_ops *target, char *args, int from_tty)
4206 error (_("Argument given to \"disconnect\" when remotely debugging."));
4208 /* Make sure we unpush even the extended remote targets; mourn
4209 won't do it. So call remote_mourn_1 directly instead of
4210 target_mourn_inferior. */
4211 remote_mourn_1 (target);
4214 puts_filtered ("Ending remote debugging.\n");
4217 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
4218 be chatty about it. */
4221 extended_remote_attach_1 (struct target_ops *target, char *args, int from_tty)
4223 struct remote_state *rs = get_remote_state ();
4225 char *wait_status = NULL;
4227 pid = parse_pid_to_attach (args);
4229 /* Remote PID can be freely equal to getpid, do not check it here the same
4230 way as in other targets. */
4232 if (remote_protocol_packets[PACKET_vAttach].support == PACKET_DISABLE)
4233 error (_("This target does not support attaching to a process"));
4235 sprintf (rs->buf, "vAttach;%x", pid);
4237 getpkt (&rs->buf, &rs->buf_size, 0);
4239 if (packet_ok (rs->buf,
4240 &remote_protocol_packets[PACKET_vAttach]) == PACKET_OK)
4243 printf_unfiltered (_("Attached to %s\n"),
4244 target_pid_to_str (pid_to_ptid (pid)));
4248 /* Save the reply for later. */
4249 wait_status = alloca (strlen (rs->buf) + 1);
4250 strcpy (wait_status, rs->buf);
4252 else if (strcmp (rs->buf, "OK") != 0)
4253 error (_("Attaching to %s failed with: %s"),
4254 target_pid_to_str (pid_to_ptid (pid)),
4257 else if (remote_protocol_packets[PACKET_vAttach].support == PACKET_DISABLE)
4258 error (_("This target does not support attaching to a process"));
4260 error (_("Attaching to %s failed"),
4261 target_pid_to_str (pid_to_ptid (pid)));
4263 set_current_inferior (remote_add_inferior (pid, 1));
4265 inferior_ptid = pid_to_ptid (pid);
4269 struct thread_info *thread;
4271 /* Get list of threads. */
4272 remote_threads_info (target);
4274 thread = first_thread_of_process (pid);
4276 inferior_ptid = thread->ptid;
4278 inferior_ptid = pid_to_ptid (pid);
4280 /* Invalidate our notion of the remote current thread. */
4281 record_currthread (minus_one_ptid);
4285 /* Now, if we have thread information, update inferior_ptid. */
4286 inferior_ptid = remote_current_thread (inferior_ptid);
4288 /* Add the main thread to the thread list. */
4289 add_thread_silent (inferior_ptid);
4292 /* Next, if the target can specify a description, read it. We do
4293 this before anything involving memory or registers. */
4294 target_find_description ();
4298 /* Use the previously fetched status. */
4299 gdb_assert (wait_status != NULL);
4301 if (target_can_async_p ())
4303 struct stop_reply *stop_reply;
4304 struct cleanup *old_chain;
4306 stop_reply = stop_reply_xmalloc ();
4307 old_chain = make_cleanup (do_stop_reply_xfree, stop_reply);
4308 remote_parse_stop_reply (wait_status, stop_reply);
4309 discard_cleanups (old_chain);
4310 push_stop_reply (stop_reply);
4312 target_async (inferior_event_handler, 0);
4316 gdb_assert (wait_status != NULL);
4317 strcpy (rs->buf, wait_status);
4318 rs->cached_wait_status = 1;
4322 gdb_assert (wait_status == NULL);
4326 extended_remote_attach (struct target_ops *ops, char *args, int from_tty)
4328 extended_remote_attach_1 (ops, args, from_tty);
4331 /* Convert hex digit A to a number. */
4336 if (a >= '0' && a <= '9')
4338 else if (a >= 'a' && a <= 'f')
4339 return a - 'a' + 10;
4340 else if (a >= 'A' && a <= 'F')
4341 return a - 'A' + 10;
4343 error (_("Reply contains invalid hex digit %d"), a);
4347 hex2bin (const char *hex, gdb_byte *bin, int count)
4351 for (i = 0; i < count; i++)
4353 if (hex[0] == 0 || hex[1] == 0)
4355 /* Hex string is short, or of uneven length.
4356 Return the count that has been converted so far. */
4359 *bin++ = fromhex (hex[0]) * 16 + fromhex (hex[1]);
4365 /* Convert number NIB to a hex digit. */
4373 return 'a' + nib - 10;
4377 bin2hex (const gdb_byte *bin, char *hex, int count)
4381 /* May use a length, or a nul-terminated string as input. */
4383 count = strlen ((char *) bin);
4385 for (i = 0; i < count; i++)
4387 *hex++ = tohex ((*bin >> 4) & 0xf);
4388 *hex++ = tohex (*bin++ & 0xf);
4394 /* Check for the availability of vCont. This function should also check
4398 remote_vcont_probe (struct remote_state *rs)
4402 strcpy (rs->buf, "vCont?");
4404 getpkt (&rs->buf, &rs->buf_size, 0);
4407 /* Make sure that the features we assume are supported. */
4408 if (strncmp (buf, "vCont", 5) == 0)
4411 int support_s, support_S, support_c, support_C;
4417 rs->support_vCont_t = 0;
4418 while (p && *p == ';')
4421 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
4423 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
4425 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
4427 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
4429 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
4430 rs->support_vCont_t = 1;
4432 p = strchr (p, ';');
4435 /* If s, S, c, and C are not all supported, we can't use vCont. Clearing
4436 BUF will make packet_ok disable the packet. */
4437 if (!support_s || !support_S || !support_c || !support_C)
4441 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
4444 /* Helper function for building "vCont" resumptions. Write a
4445 resumption to P. ENDP points to one-passed-the-end of the buffer
4446 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
4447 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
4448 resumed thread should be single-stepped and/or signalled. If PTID
4449 equals minus_one_ptid, then all threads are resumed; if PTID
4450 represents a process, then all threads of the process are resumed;
4451 the thread to be stepped and/or signalled is given in the global
4455 append_resumption (char *p, char *endp,
4456 ptid_t ptid, int step, enum target_signal siggnal)
4458 struct remote_state *rs = get_remote_state ();
4460 if (step && siggnal != TARGET_SIGNAL_0)
4461 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
4463 p += xsnprintf (p, endp - p, ";s");
4464 else if (siggnal != TARGET_SIGNAL_0)
4465 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
4467 p += xsnprintf (p, endp - p, ";c");
4469 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
4473 /* All (-1) threads of process. */
4474 nptid = ptid_build (ptid_get_pid (ptid), 0, -1);
4476 p += xsnprintf (p, endp - p, ":");
4477 p = write_ptid (p, endp, nptid);
4479 else if (!ptid_equal (ptid, minus_one_ptid))
4481 p += xsnprintf (p, endp - p, ":");
4482 p = write_ptid (p, endp, ptid);
4488 /* Resume the remote inferior by using a "vCont" packet. The thread
4489 to be resumed is PTID; STEP and SIGGNAL indicate whether the
4490 resumed thread should be single-stepped and/or signalled. If PTID
4491 equals minus_one_ptid, then all threads are resumed; the thread to
4492 be stepped and/or signalled is given in the global INFERIOR_PTID.
4493 This function returns non-zero iff it resumes the inferior.
4495 This function issues a strict subset of all possible vCont commands at the
4499 remote_vcont_resume (ptid_t ptid, int step, enum target_signal siggnal)
4501 struct remote_state *rs = get_remote_state ();
4505 if (remote_protocol_packets[PACKET_vCont].support == PACKET_SUPPORT_UNKNOWN)
4506 remote_vcont_probe (rs);
4508 if (remote_protocol_packets[PACKET_vCont].support == PACKET_DISABLE)
4512 endp = rs->buf + get_remote_packet_size ();
4514 /* If we could generate a wider range of packets, we'd have to worry
4515 about overflowing BUF. Should there be a generic
4516 "multi-part-packet" packet? */
4518 p += xsnprintf (p, endp - p, "vCont");
4520 if (ptid_equal (ptid, magic_null_ptid))
4522 /* MAGIC_NULL_PTID means that we don't have any active threads,
4523 so we don't have any TID numbers the inferior will
4524 understand. Make sure to only send forms that do not specify
4526 append_resumption (p, endp, minus_one_ptid, step, siggnal);
4528 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
4530 /* Resume all threads (of all processes, or of a single
4531 process), with preference for INFERIOR_PTID. This assumes
4532 inferior_ptid belongs to the set of all threads we are about
4534 if (step || siggnal != TARGET_SIGNAL_0)
4536 /* Step inferior_ptid, with or without signal. */
4537 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
4540 /* And continue others without a signal. */
4541 append_resumption (p, endp, ptid, /*step=*/ 0, TARGET_SIGNAL_0);
4545 /* Scheduler locking; resume only PTID. */
4546 append_resumption (p, endp, ptid, step, siggnal);
4549 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
4554 /* In non-stop, the stub replies to vCont with "OK". The stop
4555 reply will be reported asynchronously by means of a `%Stop'
4557 getpkt (&rs->buf, &rs->buf_size, 0);
4558 if (strcmp (rs->buf, "OK") != 0)
4559 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
4565 /* Tell the remote machine to resume. */
4567 static enum target_signal last_sent_signal = TARGET_SIGNAL_0;
4569 static int last_sent_step;
4572 remote_resume (struct target_ops *ops,
4573 ptid_t ptid, int step, enum target_signal siggnal)
4575 struct remote_state *rs = get_remote_state ();
4578 last_sent_signal = siggnal;
4579 last_sent_step = step;
4581 /* The vCont packet doesn't need to specify threads via Hc. */
4582 /* No reverse support (yet) for vCont. */
4583 if (execution_direction != EXEC_REVERSE)
4584 if (remote_vcont_resume (ptid, step, siggnal))
4587 /* All other supported resume packets do use Hc, so set the continue
4589 if (ptid_equal (ptid, minus_one_ptid))
4590 set_continue_thread (any_thread_ptid);
4592 set_continue_thread (ptid);
4595 if (execution_direction == EXEC_REVERSE)
4597 /* We don't pass signals to the target in reverse exec mode. */
4598 if (info_verbose && siggnal != TARGET_SIGNAL_0)
4599 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
4603 && remote_protocol_packets[PACKET_bs].support == PACKET_DISABLE)
4604 error (_("Remote reverse-step not supported."));
4606 && remote_protocol_packets[PACKET_bc].support == PACKET_DISABLE)
4607 error (_("Remote reverse-continue not supported."));
4609 strcpy (buf, step ? "bs" : "bc");
4611 else if (siggnal != TARGET_SIGNAL_0)
4613 buf[0] = step ? 'S' : 'C';
4614 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
4615 buf[2] = tohex (((int) siggnal) & 0xf);
4619 strcpy (buf, step ? "s" : "c");
4624 /* We are about to start executing the inferior, let's register it
4625 with the event loop. NOTE: this is the one place where all the
4626 execution commands end up. We could alternatively do this in each
4627 of the execution commands in infcmd.c. */
4628 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
4629 into infcmd.c in order to allow inferior function calls to work
4630 NOT asynchronously. */
4631 if (target_can_async_p ())
4632 target_async (inferior_event_handler, 0);
4634 /* We've just told the target to resume. The remote server will
4635 wait for the inferior to stop, and then send a stop reply. In
4636 the mean time, we can't start another command/query ourselves
4637 because the stub wouldn't be ready to process it. This applies
4638 only to the base all-stop protocol, however. In non-stop (which
4639 only supports vCont), the stub replies with an "OK", and is
4640 immediate able to process further serial input. */
4642 rs->waiting_for_stop_reply = 1;
4646 /* Set up the signal handler for SIGINT, while the target is
4647 executing, ovewriting the 'regular' SIGINT signal handler. */
4649 initialize_sigint_signal_handler (void)
4651 signal (SIGINT, handle_remote_sigint);
4654 /* Signal handler for SIGINT, while the target is executing. */
4656 handle_remote_sigint (int sig)
4658 signal (sig, handle_remote_sigint_twice);
4659 mark_async_signal_handler_wrapper (sigint_remote_token);
4662 /* Signal handler for SIGINT, installed after SIGINT has already been
4663 sent once. It will take effect the second time that the user sends
4666 handle_remote_sigint_twice (int sig)
4668 signal (sig, handle_remote_sigint);
4669 mark_async_signal_handler_wrapper (sigint_remote_twice_token);
4672 /* Perform the real interruption of the target execution, in response
4675 async_remote_interrupt (gdb_client_data arg)
4678 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
4680 target_stop (inferior_ptid);
4683 /* Perform interrupt, if the first attempt did not succeed. Just give
4684 up on the target alltogether. */
4686 async_remote_interrupt_twice (gdb_client_data arg)
4689 fprintf_unfiltered (gdb_stdlog, "remote_interrupt_twice called\n");
4694 /* Reinstall the usual SIGINT handlers, after the target has
4697 cleanup_sigint_signal_handler (void *dummy)
4699 signal (SIGINT, handle_sigint);
4702 /* Send ^C to target to halt it. Target will respond, and send us a
4704 static void (*ofunc) (int);
4706 /* The command line interface's stop routine. This function is installed
4707 as a signal handler for SIGINT. The first time a user requests a
4708 stop, we call remote_stop to send a break or ^C. If there is no
4709 response from the target (it didn't stop when the user requested it),
4710 we ask the user if he'd like to detach from the target. */
4712 remote_interrupt (int signo)
4714 /* If this doesn't work, try more severe steps. */
4715 signal (signo, remote_interrupt_twice);
4717 gdb_call_async_signal_handler (sigint_remote_token, 1);
4720 /* The user typed ^C twice. */
4723 remote_interrupt_twice (int signo)
4725 signal (signo, ofunc);
4726 gdb_call_async_signal_handler (sigint_remote_twice_token, 1);
4727 signal (signo, remote_interrupt);
4730 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
4731 thread, all threads of a remote process, or all threads of all
4735 remote_stop_ns (ptid_t ptid)
4737 struct remote_state *rs = get_remote_state ();
4739 char *endp = rs->buf + get_remote_packet_size ();
4741 if (remote_protocol_packets[PACKET_vCont].support == PACKET_SUPPORT_UNKNOWN)
4742 remote_vcont_probe (rs);
4744 if (!rs->support_vCont_t)
4745 error (_("Remote server does not support stopping threads"));
4747 if (ptid_equal (ptid, minus_one_ptid)
4748 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
4749 p += xsnprintf (p, endp - p, "vCont;t");
4754 p += xsnprintf (p, endp - p, "vCont;t:");
4756 if (ptid_is_pid (ptid))
4757 /* All (-1) threads of process. */
4758 nptid = ptid_build (ptid_get_pid (ptid), 0, -1);
4761 /* Small optimization: if we already have a stop reply for
4762 this thread, no use in telling the stub we want this
4764 if (peek_stop_reply (ptid))
4770 write_ptid (p, endp, nptid);
4773 /* In non-stop, we get an immediate OK reply. The stop reply will
4774 come in asynchronously by notification. */
4776 getpkt (&rs->buf, &rs->buf_size, 0);
4777 if (strcmp (rs->buf, "OK") != 0)
4778 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
4781 /* All-stop version of target_stop. Sends a break or a ^C to stop the
4782 remote target. It is undefined which thread of which process
4783 reports the stop. */
4786 remote_stop_as (ptid_t ptid)
4788 struct remote_state *rs = get_remote_state ();
4790 rs->ctrlc_pending_p = 1;
4792 /* If the inferior is stopped already, but the core didn't know
4793 about it yet, just ignore the request. The cached wait status
4794 will be collected in remote_wait. */
4795 if (rs->cached_wait_status)
4798 /* Send interrupt_sequence to remote target. */
4799 send_interrupt_sequence ();
4802 /* This is the generic stop called via the target vector. When a target
4803 interrupt is requested, either by the command line or the GUI, we
4804 will eventually end up here. */
4807 remote_stop (ptid_t ptid)
4810 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
4813 remote_stop_ns (ptid);
4815 remote_stop_as (ptid);
4818 /* Ask the user what to do when an interrupt is received. */
4821 interrupt_query (void)
4823 target_terminal_ours ();
4825 if (target_can_async_p ())
4827 signal (SIGINT, handle_sigint);
4828 deprecated_throw_reason (RETURN_QUIT);
4832 if (query (_("Interrupted while waiting for the program.\n\
4833 Give up (and stop debugging it)? ")))
4836 deprecated_throw_reason (RETURN_QUIT);
4840 target_terminal_inferior ();
4843 /* Enable/disable target terminal ownership. Most targets can use
4844 terminal groups to control terminal ownership. Remote targets are
4845 different in that explicit transfer of ownership to/from GDB/target
4849 remote_terminal_inferior (void)
4851 if (!target_async_permitted)
4852 /* Nothing to do. */
4855 /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
4856 idempotent. The event-loop GDB talking to an asynchronous target
4857 with a synchronous command calls this function from both
4858 event-top.c and infrun.c/infcmd.c. Once GDB stops trying to
4859 transfer the terminal to the target when it shouldn't this guard
4861 if (!remote_async_terminal_ours_p)
4863 delete_file_handler (input_fd);
4864 remote_async_terminal_ours_p = 0;
4865 initialize_sigint_signal_handler ();
4866 /* NOTE: At this point we could also register our selves as the
4867 recipient of all input. Any characters typed could then be
4868 passed on down to the target. */
4872 remote_terminal_ours (void)
4874 if (!target_async_permitted)
4875 /* Nothing to do. */
4878 /* See FIXME in remote_terminal_inferior. */
4879 if (remote_async_terminal_ours_p)
4881 cleanup_sigint_signal_handler (NULL);
4882 add_file_handler (input_fd, stdin_event_handler, 0);
4883 remote_async_terminal_ours_p = 1;
4887 remote_console_output (char *msg)
4891 for (p = msg; p[0] && p[1]; p += 2)
4894 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
4898 fputs_unfiltered (tb, gdb_stdtarg);
4900 gdb_flush (gdb_stdtarg);
4903 typedef struct cached_reg
4906 gdb_byte data[MAX_REGISTER_SIZE];
4909 DEF_VEC_O(cached_reg_t);
4913 struct stop_reply *next;
4917 struct target_waitstatus ws;
4919 /* Expedited registers. This makes remote debugging a bit more
4920 efficient for those targets that provide critical registers as
4921 part of their normal status mechanism (as another roundtrip to
4922 fetch them is avoided). */
4923 VEC(cached_reg_t) *regcache;
4925 int stopped_by_watchpoint_p;
4926 CORE_ADDR watch_data_address;
4934 /* The list of already fetched and acknowledged stop events. */
4935 static struct stop_reply *stop_reply_queue;
4937 static struct stop_reply *
4938 stop_reply_xmalloc (void)
4940 struct stop_reply *r = XMALLOC (struct stop_reply);
4947 stop_reply_xfree (struct stop_reply *r)
4951 VEC_free (cached_reg_t, r->regcache);
4956 /* Discard all pending stop replies of inferior PID. If PID is -1,
4957 discard everything. */
4960 discard_pending_stop_replies (int pid)
4962 struct stop_reply *prev = NULL, *reply, *next;
4964 /* Discard the in-flight notification. */
4965 if (pending_stop_reply != NULL
4967 || ptid_get_pid (pending_stop_reply->ptid) == pid))
4969 stop_reply_xfree (pending_stop_reply);
4970 pending_stop_reply = NULL;
4973 /* Discard the stop replies we have already pulled with
4975 for (reply = stop_reply_queue; reply; reply = next)
4979 || ptid_get_pid (reply->ptid) == pid)
4981 if (reply == stop_reply_queue)
4982 stop_reply_queue = reply->next;
4984 prev->next = reply->next;
4986 stop_reply_xfree (reply);
4993 /* Cleanup wrapper. */
4996 do_stop_reply_xfree (void *arg)
4998 struct stop_reply *r = arg;
5000 stop_reply_xfree (r);
5003 /* Look for a queued stop reply belonging to PTID. If one is found,
5004 remove it from the queue, and return it. Returns NULL if none is
5005 found. If there are still queued events left to process, tell the
5006 event loop to get back to target_wait soon. */
5008 static struct stop_reply *
5009 queued_stop_reply (ptid_t ptid)
5011 struct stop_reply *it;
5012 struct stop_reply **it_link;
5014 it = stop_reply_queue;
5015 it_link = &stop_reply_queue;
5018 if (ptid_match (it->ptid, ptid))
5020 *it_link = it->next;
5025 it_link = &it->next;
5029 if (stop_reply_queue)
5030 /* There's still at least an event left. */
5031 mark_async_event_handler (remote_async_inferior_event_token);
5036 /* Push a fully parsed stop reply in the stop reply queue. Since we
5037 know that we now have at least one queued event left to pass to the
5038 core side, tell the event loop to get back to target_wait soon. */
5041 push_stop_reply (struct stop_reply *new_event)
5043 struct stop_reply *event;
5045 if (stop_reply_queue)
5047 for (event = stop_reply_queue;
5048 event && event->next;
5049 event = event->next)
5052 event->next = new_event;
5055 stop_reply_queue = new_event;
5057 mark_async_event_handler (remote_async_inferior_event_token);
5060 /* Returns true if we have a stop reply for PTID. */
5063 peek_stop_reply (ptid_t ptid)
5065 struct stop_reply *it;
5067 for (it = stop_reply_queue; it; it = it->next)
5068 if (ptid_equal (ptid, it->ptid))
5070 if (it->ws.kind == TARGET_WAITKIND_STOPPED)
5077 /* Parse the stop reply in BUF. Either the function succeeds, and the
5078 result is stored in EVENT, or throws an error. */
5081 remote_parse_stop_reply (char *buf, struct stop_reply *event)
5083 struct remote_arch_state *rsa = get_remote_arch_state ();
5087 event->ptid = null_ptid;
5088 event->ws.kind = TARGET_WAITKIND_IGNORE;
5089 event->ws.value.integer = 0;
5090 event->solibs_changed = 0;
5091 event->replay_event = 0;
5092 event->stopped_by_watchpoint_p = 0;
5093 event->regcache = NULL;
5098 case 'T': /* Status with PC, SP, FP, ... */
5099 /* Expedited reply, containing Signal, {regno, reg} repeat. */
5100 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
5102 n... = register number
5103 r... = register contents
5106 p = &buf[3]; /* after Txx */
5114 /* If the packet contains a register number, save it in
5115 pnum and set p1 to point to the character following it.
5116 Otherwise p1 points to p. */
5118 /* If this packet is an awatch packet, don't parse the 'a'
5119 as a register number. */
5121 if (strncmp (p, "awatch", strlen("awatch")) != 0
5122 && strncmp (p, "core", strlen ("core") != 0))
5124 /* Read the ``P'' register number. */
5125 pnum = strtol (p, &p_temp, 16);
5131 if (p1 == p) /* No register number present here. */
5133 p1 = strchr (p, ':');
5135 error (_("Malformed packet(a) (missing colon): %s\n\
5138 if (strncmp (p, "thread", p1 - p) == 0)
5139 event->ptid = read_ptid (++p1, &p);
5140 else if ((strncmp (p, "watch", p1 - p) == 0)
5141 || (strncmp (p, "rwatch", p1 - p) == 0)
5142 || (strncmp (p, "awatch", p1 - p) == 0))
5144 event->stopped_by_watchpoint_p = 1;
5145 p = unpack_varlen_hex (++p1, &addr);
5146 event->watch_data_address = (CORE_ADDR) addr;
5148 else if (strncmp (p, "library", p1 - p) == 0)
5152 while (*p_temp && *p_temp != ';')
5155 event->solibs_changed = 1;
5158 else if (strncmp (p, "replaylog", p1 - p) == 0)
5160 /* NO_HISTORY event.
5161 p1 will indicate "begin" or "end", but
5162 it makes no difference for now, so ignore it. */
5163 event->replay_event = 1;
5164 p_temp = strchr (p1 + 1, ';');
5168 else if (strncmp (p, "core", p1 - p) == 0)
5172 p = unpack_varlen_hex (++p1, &c);
5177 /* Silently skip unknown optional info. */
5178 p_temp = strchr (p1 + 1, ';');
5185 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
5186 cached_reg_t cached_reg;
5191 error (_("Malformed packet(b) (missing colon): %s\n\
5197 error (_("Remote sent bad register number %s: %s\n\
5199 hex_string (pnum), p, buf);
5201 cached_reg.num = reg->regnum;
5203 fieldsize = hex2bin (p, cached_reg.data,
5204 register_size (target_gdbarch,
5207 if (fieldsize < register_size (target_gdbarch,
5209 warning (_("Remote reply is too short: %s"), buf);
5211 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
5215 error (_("Remote register badly formatted: %s\nhere: %s"),
5220 case 'S': /* Old style status, just signal only. */
5221 if (event->solibs_changed)
5222 event->ws.kind = TARGET_WAITKIND_LOADED;
5223 else if (event->replay_event)
5224 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
5227 event->ws.kind = TARGET_WAITKIND_STOPPED;
5228 event->ws.value.sig = (enum target_signal)
5229 (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
5232 case 'W': /* Target exited. */
5239 /* GDB used to accept only 2 hex chars here. Stubs should
5240 only send more if they detect GDB supports multi-process
5242 p = unpack_varlen_hex (&buf[1], &value);
5246 /* The remote process exited. */
5247 event->ws.kind = TARGET_WAITKIND_EXITED;
5248 event->ws.value.integer = value;
5252 /* The remote process exited with a signal. */
5253 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
5254 event->ws.value.sig = (enum target_signal) value;
5257 /* If no process is specified, assume inferior_ptid. */
5258 pid = ptid_get_pid (inferior_ptid);
5267 else if (strncmp (p,
5268 "process:", sizeof ("process:") - 1) == 0)
5272 p += sizeof ("process:") - 1;
5273 unpack_varlen_hex (p, &upid);
5277 error (_("unknown stop reply packet: %s"), buf);
5280 error (_("unknown stop reply packet: %s"), buf);
5281 event->ptid = pid_to_ptid (pid);
5286 if (non_stop && ptid_equal (event->ptid, null_ptid))
5287 error (_("No process or thread specified in stop reply: %s"), buf);
5290 /* When the stub wants to tell GDB about a new stop reply, it sends a
5291 stop notification (%Stop). Those can come it at any time, hence,
5292 we have to make sure that any pending putpkt/getpkt sequence we're
5293 making is finished, before querying the stub for more events with
5294 vStopped. E.g., if we started a vStopped sequence immediatelly
5295 upon receiving the %Stop notification, something like this could
5303 1.6) <-- (registers reply to step #1.3)
5305 Obviously, the reply in step #1.6 would be unexpected to a vStopped
5308 To solve this, whenever we parse a %Stop notification sucessfully,
5309 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
5310 doing whatever we were doing:
5316 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
5317 2.5) <-- (registers reply to step #2.3)
5319 Eventualy after step #2.5, we return to the event loop, which
5320 notices there's an event on the
5321 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
5322 associated callback --- the function below. At this point, we're
5323 always safe to start a vStopped sequence. :
5326 2.7) <-- T05 thread:2
5332 remote_get_pending_stop_replies (void)
5334 struct remote_state *rs = get_remote_state ();
5336 if (pending_stop_reply)
5339 putpkt ("vStopped");
5341 /* Now we can rely on it. */
5342 push_stop_reply (pending_stop_reply);
5343 pending_stop_reply = NULL;
5347 getpkt (&rs->buf, &rs->buf_size, 0);
5348 if (strcmp (rs->buf, "OK") == 0)
5352 struct cleanup *old_chain;
5353 struct stop_reply *stop_reply = stop_reply_xmalloc ();
5355 old_chain = make_cleanup (do_stop_reply_xfree, stop_reply);
5356 remote_parse_stop_reply (rs->buf, stop_reply);
5359 putpkt ("vStopped");
5361 if (stop_reply->ws.kind != TARGET_WAITKIND_IGNORE)
5363 /* Now we can rely on it. */
5364 discard_cleanups (old_chain);
5365 push_stop_reply (stop_reply);
5368 /* We got an unknown stop reply. */
5369 do_cleanups (old_chain);
5376 /* Called when it is decided that STOP_REPLY holds the info of the
5377 event that is to be returned to the core. This function always
5378 destroys STOP_REPLY. */
5381 process_stop_reply (struct stop_reply *stop_reply,
5382 struct target_waitstatus *status)
5386 *status = stop_reply->ws;
5387 ptid = stop_reply->ptid;
5389 /* If no thread/process was reported by the stub, assume the current
5391 if (ptid_equal (ptid, null_ptid))
5392 ptid = inferior_ptid;
5394 if (status->kind != TARGET_WAITKIND_EXITED
5395 && status->kind != TARGET_WAITKIND_SIGNALLED)
5397 /* Expedited registers. */
5398 if (stop_reply->regcache)
5400 struct regcache *regcache
5401 = get_thread_arch_regcache (ptid, target_gdbarch);
5406 VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
5408 regcache_raw_supply (regcache, reg->num, reg->data);
5409 VEC_free (cached_reg_t, stop_reply->regcache);
5412 remote_stopped_by_watchpoint_p = stop_reply->stopped_by_watchpoint_p;
5413 remote_watch_data_address = stop_reply->watch_data_address;
5415 remote_notice_new_inferior (ptid, 0);
5416 demand_private_info (ptid)->core = stop_reply->core;
5419 stop_reply_xfree (stop_reply);
5423 /* The non-stop mode version of target_wait. */
5426 remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
5428 struct remote_state *rs = get_remote_state ();
5429 struct stop_reply *stop_reply;
5432 /* If in non-stop mode, get out of getpkt even if a
5433 notification is received. */
5435 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
5442 case 'E': /* Error of some sort. */
5443 /* We're out of sync with the target now. Did it continue
5444 or not? We can't tell which thread it was in non-stop,
5445 so just ignore this. */
5446 warning (_("Remote failure reply: %s"), rs->buf);
5448 case 'O': /* Console output. */
5449 remote_console_output (rs->buf + 1);
5452 warning (_("Invalid remote reply: %s"), rs->buf);
5456 /* Acknowledge a pending stop reply that may have arrived in the
5458 if (pending_stop_reply != NULL)
5459 remote_get_pending_stop_replies ();
5461 /* If indeed we noticed a stop reply, we're done. */
5462 stop_reply = queued_stop_reply (ptid);
5463 if (stop_reply != NULL)
5464 return process_stop_reply (stop_reply, status);
5466 /* Still no event. If we're just polling for an event, then
5467 return to the event loop. */
5468 if (options & TARGET_WNOHANG)
5470 status->kind = TARGET_WAITKIND_IGNORE;
5471 return minus_one_ptid;
5474 /* Otherwise do a blocking wait. */
5475 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
5480 /* Wait until the remote machine stops, then return, storing status in
5481 STATUS just as `wait' would. */
5484 remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
5486 struct remote_state *rs = get_remote_state ();
5487 ptid_t event_ptid = null_ptid;
5489 struct stop_reply *stop_reply;
5493 status->kind = TARGET_WAITKIND_IGNORE;
5494 status->value.integer = 0;
5496 stop_reply = queued_stop_reply (ptid);
5497 if (stop_reply != NULL)
5498 return process_stop_reply (stop_reply, status);
5500 if (rs->cached_wait_status)
5501 /* Use the cached wait status, but only once. */
5502 rs->cached_wait_status = 0;
5507 if (!target_is_async_p ())
5509 ofunc = signal (SIGINT, remote_interrupt);
5510 /* If the user hit C-c before this packet, or between packets,
5511 pretend that it was hit right here. */
5515 remote_interrupt (SIGINT);
5519 /* FIXME: cagney/1999-09-27: If we're in async mode we should
5520 _never_ wait for ever -> test on target_is_async_p().
5521 However, before we do that we need to ensure that the caller
5522 knows how to take the target into/out of async mode. */
5523 ret = getpkt_sane (&rs->buf, &rs->buf_size, wait_forever_enabled_p);
5524 if (!target_is_async_p ())
5525 signal (SIGINT, ofunc);
5530 remote_stopped_by_watchpoint_p = 0;
5532 /* We got something. */
5533 rs->waiting_for_stop_reply = 0;
5535 /* Assume that the target has acknowledged Ctrl-C unless we receive
5536 an 'F' or 'O' packet. */
5537 if (buf[0] != 'F' && buf[0] != 'O')
5538 rs->ctrlc_pending_p = 0;
5542 case 'E': /* Error of some sort. */
5543 /* We're out of sync with the target now. Did it continue or
5544 not? Not is more likely, so report a stop. */
5545 warning (_("Remote failure reply: %s"), buf);
5546 status->kind = TARGET_WAITKIND_STOPPED;
5547 status->value.sig = TARGET_SIGNAL_0;
5549 case 'F': /* File-I/O request. */
5550 remote_fileio_request (buf, rs->ctrlc_pending_p);
5551 rs->ctrlc_pending_p = 0;
5553 case 'T': case 'S': case 'X': case 'W':
5555 struct stop_reply *stop_reply;
5556 struct cleanup *old_chain;
5558 stop_reply = stop_reply_xmalloc ();
5559 old_chain = make_cleanup (do_stop_reply_xfree, stop_reply);
5560 remote_parse_stop_reply (buf, stop_reply);
5561 discard_cleanups (old_chain);
5562 event_ptid = process_stop_reply (stop_reply, status);
5565 case 'O': /* Console output. */
5566 remote_console_output (buf + 1);
5568 /* The target didn't really stop; keep waiting. */
5569 rs->waiting_for_stop_reply = 1;
5573 if (last_sent_signal != TARGET_SIGNAL_0)
5575 /* Zero length reply means that we tried 'S' or 'C' and the
5576 remote system doesn't support it. */
5577 target_terminal_ours_for_output ();
5579 ("Can't send signals to this remote system. %s not sent.\n",
5580 target_signal_to_name (last_sent_signal));
5581 last_sent_signal = TARGET_SIGNAL_0;
5582 target_terminal_inferior ();
5584 strcpy ((char *) buf, last_sent_step ? "s" : "c");
5585 putpkt ((char *) buf);
5587 /* We just told the target to resume, so a stop reply is in
5589 rs->waiting_for_stop_reply = 1;
5592 /* else fallthrough */
5594 warning (_("Invalid remote reply: %s"), buf);
5596 rs->waiting_for_stop_reply = 1;
5600 if (status->kind == TARGET_WAITKIND_IGNORE)
5602 /* Nothing interesting happened. If we're doing a non-blocking
5603 poll, we're done. Otherwise, go back to waiting. */
5604 if (options & TARGET_WNOHANG)
5605 return minus_one_ptid;
5609 else if (status->kind != TARGET_WAITKIND_EXITED
5610 && status->kind != TARGET_WAITKIND_SIGNALLED)
5612 if (!ptid_equal (event_ptid, null_ptid))
5613 record_currthread (event_ptid);
5615 event_ptid = inferior_ptid;
5618 /* A process exit. Invalidate our notion of current thread. */
5619 record_currthread (minus_one_ptid);
5624 /* Wait until the remote machine stops, then return, storing status in
5625 STATUS just as `wait' would. */
5628 remote_wait (struct target_ops *ops,
5629 ptid_t ptid, struct target_waitstatus *status, int options)
5634 event_ptid = remote_wait_ns (ptid, status, options);
5636 event_ptid = remote_wait_as (ptid, status, options);
5638 if (target_can_async_p ())
5640 /* If there are are events left in the queue tell the event loop
5642 if (stop_reply_queue)
5643 mark_async_event_handler (remote_async_inferior_event_token);
5649 /* Fetch a single register using a 'p' packet. */
5652 fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
5654 struct remote_state *rs = get_remote_state ();
5656 char regp[MAX_REGISTER_SIZE];
5659 if (remote_protocol_packets[PACKET_p].support == PACKET_DISABLE)
5662 if (reg->pnum == -1)
5667 p += hexnumstr (p, reg->pnum);
5670 getpkt (&rs->buf, &rs->buf_size, 0);
5674 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
5678 case PACKET_UNKNOWN:
5681 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
5682 gdbarch_register_name (get_regcache_arch (regcache),
5687 /* If this register is unfetchable, tell the regcache. */
5690 regcache_raw_supply (regcache, reg->regnum, NULL);
5694 /* Otherwise, parse and supply the value. */
5700 error (_("fetch_register_using_p: early buf termination"));
5702 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
5705 regcache_raw_supply (regcache, reg->regnum, regp);
5709 /* Fetch the registers included in the target's 'g' packet. */
5712 send_g_packet (void)
5714 struct remote_state *rs = get_remote_state ();
5717 sprintf (rs->buf, "g");
5718 remote_send (&rs->buf, &rs->buf_size);
5720 /* We can get out of synch in various cases. If the first character
5721 in the buffer is not a hex character, assume that has happened
5722 and try to fetch another packet to read. */
5723 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
5724 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
5725 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
5726 && rs->buf[0] != 'x') /* New: unavailable register value. */
5729 fprintf_unfiltered (gdb_stdlog,
5730 "Bad register packet; fetching a new packet\n");
5731 getpkt (&rs->buf, &rs->buf_size, 0);
5734 buf_len = strlen (rs->buf);
5736 /* Sanity check the received packet. */
5737 if (buf_len % 2 != 0)
5738 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
5744 process_g_packet (struct regcache *regcache)
5746 struct gdbarch *gdbarch = get_regcache_arch (regcache);
5747 struct remote_state *rs = get_remote_state ();
5748 struct remote_arch_state *rsa = get_remote_arch_state ();
5753 buf_len = strlen (rs->buf);
5755 /* Further sanity checks, with knowledge of the architecture. */
5756 if (buf_len > 2 * rsa->sizeof_g_packet)
5757 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
5759 /* Save the size of the packet sent to us by the target. It is used
5760 as a heuristic when determining the max size of packets that the
5761 target can safely receive. */
5762 if (rsa->actual_register_packet_size == 0)
5763 rsa->actual_register_packet_size = buf_len;
5765 /* If this is smaller than we guessed the 'g' packet would be,
5766 update our records. A 'g' reply that doesn't include a register's
5767 value implies either that the register is not available, or that
5768 the 'p' packet must be used. */
5769 if (buf_len < 2 * rsa->sizeof_g_packet)
5771 rsa->sizeof_g_packet = buf_len / 2;
5773 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
5775 if (rsa->regs[i].pnum == -1)
5778 if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
5779 rsa->regs[i].in_g_packet = 0;
5781 rsa->regs[i].in_g_packet = 1;
5785 regs = alloca (rsa->sizeof_g_packet);
5787 /* Unimplemented registers read as all bits zero. */
5788 memset (regs, 0, rsa->sizeof_g_packet);
5790 /* Reply describes registers byte by byte, each byte encoded as two
5791 hex characters. Suck them all up, then supply them to the
5792 register cacheing/storage mechanism. */
5795 for (i = 0; i < rsa->sizeof_g_packet; i++)
5797 if (p[0] == 0 || p[1] == 0)
5798 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
5799 internal_error (__FILE__, __LINE__,
5800 _("unexpected end of 'g' packet reply"));
5802 if (p[0] == 'x' && p[1] == 'x')
5803 regs[i] = 0; /* 'x' */
5805 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
5809 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
5811 struct packet_reg *r = &rsa->regs[i];
5815 if (r->offset * 2 >= strlen (rs->buf))
5816 /* This shouldn't happen - we adjusted in_g_packet above. */
5817 internal_error (__FILE__, __LINE__,
5818 _("unexpected end of 'g' packet reply"));
5819 else if (rs->buf[r->offset * 2] == 'x')
5821 gdb_assert (r->offset * 2 < strlen (rs->buf));
5822 /* The register isn't available, mark it as such (at
5823 the same time setting the value to zero). */
5824 regcache_raw_supply (regcache, r->regnum, NULL);
5827 regcache_raw_supply (regcache, r->regnum,
5834 fetch_registers_using_g (struct regcache *regcache)
5837 process_g_packet (regcache);
5840 /* Make the remote selected traceframe match GDB's selected
5844 set_remote_traceframe (void)
5848 if (remote_traceframe_number == get_traceframe_number ())
5851 /* Avoid recursion, remote_trace_find calls us again. */
5852 remote_traceframe_number = get_traceframe_number ();
5854 newnum = target_trace_find (tfind_number,
5855 get_traceframe_number (), 0, 0, NULL);
5857 /* Should not happen. If it does, all bets are off. */
5858 if (newnum != get_traceframe_number ())
5859 warning (_("could not set remote traceframe"));
5863 remote_fetch_registers (struct target_ops *ops,
5864 struct regcache *regcache, int regnum)
5866 struct remote_arch_state *rsa = get_remote_arch_state ();
5869 set_remote_traceframe ();
5870 set_general_thread (inferior_ptid);
5874 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
5876 gdb_assert (reg != NULL);
5878 /* If this register might be in the 'g' packet, try that first -
5879 we are likely to read more than one register. If this is the
5880 first 'g' packet, we might be overly optimistic about its
5881 contents, so fall back to 'p'. */
5882 if (reg->in_g_packet)
5884 fetch_registers_using_g (regcache);
5885 if (reg->in_g_packet)
5889 if (fetch_register_using_p (regcache, reg))
5892 /* This register is not available. */
5893 regcache_raw_supply (regcache, reg->regnum, NULL);
5898 fetch_registers_using_g (regcache);
5900 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
5901 if (!rsa->regs[i].in_g_packet)
5902 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
5904 /* This register is not available. */
5905 regcache_raw_supply (regcache, i, NULL);
5909 /* Prepare to store registers. Since we may send them all (using a
5910 'G' request), we have to read out the ones we don't want to change
5914 remote_prepare_to_store (struct regcache *regcache)
5916 struct remote_arch_state *rsa = get_remote_arch_state ();
5918 gdb_byte buf[MAX_REGISTER_SIZE];
5920 /* Make sure the entire registers array is valid. */
5921 switch (remote_protocol_packets[PACKET_P].support)
5923 case PACKET_DISABLE:
5924 case PACKET_SUPPORT_UNKNOWN:
5925 /* Make sure all the necessary registers are cached. */
5926 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
5927 if (rsa->regs[i].in_g_packet)
5928 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
5935 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
5936 packet was not recognized. */
5939 store_register_using_P (const struct regcache *regcache,
5940 struct packet_reg *reg)
5942 struct gdbarch *gdbarch = get_regcache_arch (regcache);
5943 struct remote_state *rs = get_remote_state ();
5944 /* Try storing a single register. */
5945 char *buf = rs->buf;
5946 gdb_byte regp[MAX_REGISTER_SIZE];
5949 if (remote_protocol_packets[PACKET_P].support == PACKET_DISABLE)
5952 if (reg->pnum == -1)
5955 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
5956 p = buf + strlen (buf);
5957 regcache_raw_collect (regcache, reg->regnum, regp);
5958 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
5960 getpkt (&rs->buf, &rs->buf_size, 0);
5962 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
5967 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
5968 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
5969 case PACKET_UNKNOWN:
5972 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
5976 /* Store register REGNUM, or all registers if REGNUM == -1, from the
5977 contents of the register cache buffer. FIXME: ignores errors. */
5980 store_registers_using_G (const struct regcache *regcache)
5982 struct remote_state *rs = get_remote_state ();
5983 struct remote_arch_state *rsa = get_remote_arch_state ();
5987 /* Extract all the registers in the regcache copying them into a
5992 regs = alloca (rsa->sizeof_g_packet);
5993 memset (regs, 0, rsa->sizeof_g_packet);
5994 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
5996 struct packet_reg *r = &rsa->regs[i];
5999 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
6003 /* Command describes registers byte by byte,
6004 each byte encoded as two hex characters. */
6007 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
6009 bin2hex (regs, p, rsa->sizeof_g_packet);
6011 getpkt (&rs->buf, &rs->buf_size, 0);
6012 if (packet_check_result (rs->buf) == PACKET_ERROR)
6013 error (_("Could not write registers; remote failure reply '%s'"),
6017 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
6018 of the register cache buffer. FIXME: ignores errors. */
6021 remote_store_registers (struct target_ops *ops,
6022 struct regcache *regcache, int regnum)
6024 struct remote_arch_state *rsa = get_remote_arch_state ();
6027 set_remote_traceframe ();
6028 set_general_thread (inferior_ptid);
6032 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
6034 gdb_assert (reg != NULL);
6036 /* Always prefer to store registers using the 'P' packet if
6037 possible; we often change only a small number of registers.
6038 Sometimes we change a larger number; we'd need help from a
6039 higher layer to know to use 'G'. */
6040 if (store_register_using_P (regcache, reg))
6043 /* For now, don't complain if we have no way to write the
6044 register. GDB loses track of unavailable registers too
6045 easily. Some day, this may be an error. We don't have
6046 any way to read the register, either... */
6047 if (!reg->in_g_packet)
6050 store_registers_using_G (regcache);
6054 store_registers_using_G (regcache);
6056 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6057 if (!rsa->regs[i].in_g_packet)
6058 if (!store_register_using_P (regcache, &rsa->regs[i]))
6059 /* See above for why we do not issue an error here. */
6064 /* Return the number of hex digits in num. */
6067 hexnumlen (ULONGEST num)
6071 for (i = 0; num != 0; i++)
6077 /* Set BUF to the minimum number of hex digits representing NUM. */
6080 hexnumstr (char *buf, ULONGEST num)
6082 int len = hexnumlen (num);
6084 return hexnumnstr (buf, num, len);
6088 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
6091 hexnumnstr (char *buf, ULONGEST num, int width)
6097 for (i = width - 1; i >= 0; i--)
6099 buf[i] = "0123456789abcdef"[(num & 0xf)];
6106 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
6109 remote_address_masked (CORE_ADDR addr)
6111 int address_size = remote_address_size;
6113 /* If "remoteaddresssize" was not set, default to target address size. */
6115 address_size = gdbarch_addr_bit (target_gdbarch);
6117 if (address_size > 0
6118 && address_size < (sizeof (ULONGEST) * 8))
6120 /* Only create a mask when that mask can safely be constructed
6121 in a ULONGEST variable. */
6124 mask = (mask << address_size) - 1;
6130 /* Convert BUFFER, binary data at least LEN bytes long, into escaped
6131 binary data in OUT_BUF. Set *OUT_LEN to the length of the data
6132 encoded in OUT_BUF, and return the number of bytes in OUT_BUF
6133 (which may be more than *OUT_LEN due to escape characters). The
6134 total number of bytes in the output buffer will be at most
6138 remote_escape_output (const gdb_byte *buffer, int len,
6139 gdb_byte *out_buf, int *out_len,
6142 int input_index, output_index;
6145 for (input_index = 0; input_index < len; input_index++)
6147 gdb_byte b = buffer[input_index];
6149 if (b == '$' || b == '#' || b == '}')
6151 /* These must be escaped. */
6152 if (output_index + 2 > out_maxlen)
6154 out_buf[output_index++] = '}';
6155 out_buf[output_index++] = b ^ 0x20;
6159 if (output_index + 1 > out_maxlen)
6161 out_buf[output_index++] = b;
6165 *out_len = input_index;
6166 return output_index;
6169 /* Convert BUFFER, escaped data LEN bytes long, into binary data
6170 in OUT_BUF. Return the number of bytes written to OUT_BUF.
6171 Raise an error if the total number of bytes exceeds OUT_MAXLEN.
6173 This function reverses remote_escape_output. It allows more
6174 escaped characters than that function does, in particular because
6175 '*' must be escaped to avoid the run-length encoding processing
6176 in reading packets. */
6179 remote_unescape_input (const gdb_byte *buffer, int len,
6180 gdb_byte *out_buf, int out_maxlen)
6182 int input_index, output_index;
6187 for (input_index = 0; input_index < len; input_index++)
6189 gdb_byte b = buffer[input_index];
6191 if (output_index + 1 > out_maxlen)
6193 warning (_("Received too much data from remote target;"
6194 " ignoring overflow."));
6195 return output_index;
6200 out_buf[output_index++] = b ^ 0x20;
6206 out_buf[output_index++] = b;
6210 error (_("Unmatched escape character in target response."));
6212 return output_index;
6215 /* Determine whether the remote target supports binary downloading.
6216 This is accomplished by sending a no-op memory write of zero length
6217 to the target at the specified address. It does not suffice to send
6218 the whole packet, since many stubs strip the eighth bit and
6219 subsequently compute a wrong checksum, which causes real havoc with
6222 NOTE: This can still lose if the serial line is not eight-bit
6223 clean. In cases like this, the user should clear "remote
6227 check_binary_download (CORE_ADDR addr)
6229 struct remote_state *rs = get_remote_state ();
6231 switch (remote_protocol_packets[PACKET_X].support)
6233 case PACKET_DISABLE:
6237 case PACKET_SUPPORT_UNKNOWN:
6243 p += hexnumstr (p, (ULONGEST) addr);
6245 p += hexnumstr (p, (ULONGEST) 0);
6249 putpkt_binary (rs->buf, (int) (p - rs->buf));
6250 getpkt (&rs->buf, &rs->buf_size, 0);
6252 if (rs->buf[0] == '\0')
6255 fprintf_unfiltered (gdb_stdlog,
6256 "binary downloading NOT "
6257 "supported by target\n");
6258 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
6263 fprintf_unfiltered (gdb_stdlog,
6264 "binary downloading supported by target\n");
6265 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
6272 /* Write memory data directly to the remote machine.
6273 This does not inform the data cache; the data cache uses this.
6274 HEADER is the starting part of the packet.
6275 MEMADDR is the address in the remote memory space.
6276 MYADDR is the address of the buffer in our space.
6277 LEN is the number of bytes.
6278 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
6279 should send data as binary ('X'), or hex-encoded ('M').
6281 The function creates packet of the form
6282 <HEADER><ADDRESS>,<LENGTH>:<DATA>
6284 where encoding of <DATA> is termined by PACKET_FORMAT.
6286 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
6289 Returns the number of bytes transferred, or 0 (setting errno) for
6290 error. Only transfer a single packet. */
6293 remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
6294 const gdb_byte *myaddr, int len,
6295 char packet_format, int use_length)
6297 struct remote_state *rs = get_remote_state ();
6307 if (packet_format != 'X' && packet_format != 'M')
6308 internal_error (__FILE__, __LINE__,
6309 _("remote_write_bytes_aux: bad packet format"));
6314 payload_size = get_memory_write_packet_size ();
6316 /* The packet buffer will be large enough for the payload;
6317 get_memory_packet_size ensures this. */
6320 /* Compute the size of the actual payload by subtracting out the
6321 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
6323 payload_size -= strlen ("$,:#NN");
6325 /* The comma won't be used. */
6327 header_length = strlen (header);
6328 payload_size -= header_length;
6329 payload_size -= hexnumlen (memaddr);
6331 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
6333 strcat (rs->buf, header);
6334 p = rs->buf + strlen (header);
6336 /* Compute a best guess of the number of bytes actually transfered. */
6337 if (packet_format == 'X')
6339 /* Best guess at number of bytes that will fit. */
6340 todo = min (len, payload_size);
6342 payload_size -= hexnumlen (todo);
6343 todo = min (todo, payload_size);
6347 /* Num bytes that will fit. */
6348 todo = min (len, payload_size / 2);
6350 payload_size -= hexnumlen (todo);
6351 todo = min (todo, payload_size / 2);
6355 internal_error (__FILE__, __LINE__,
6356 _("minumum packet size too small to write data"));
6358 /* If we already need another packet, then try to align the end
6359 of this packet to a useful boundary. */
6360 if (todo > 2 * REMOTE_ALIGN_WRITES && todo < len)
6361 todo = ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
6363 /* Append "<memaddr>". */
6364 memaddr = remote_address_masked (memaddr);
6365 p += hexnumstr (p, (ULONGEST) memaddr);
6372 /* Append <len>. Retain the location/size of <len>. It may need to
6373 be adjusted once the packet body has been created. */
6375 plenlen = hexnumstr (p, (ULONGEST) todo);
6383 /* Append the packet body. */
6384 if (packet_format == 'X')
6386 /* Binary mode. Send target system values byte by byte, in
6387 increasing byte addresses. Only escape certain critical
6389 payload_length = remote_escape_output (myaddr, todo, p, &nr_bytes,
6392 /* If not all TODO bytes fit, then we'll need another packet. Make
6393 a second try to keep the end of the packet aligned. Don't do
6394 this if the packet is tiny. */
6395 if (nr_bytes < todo && nr_bytes > 2 * REMOTE_ALIGN_WRITES)
6399 new_nr_bytes = (((memaddr + nr_bytes) & ~(REMOTE_ALIGN_WRITES - 1))
6401 if (new_nr_bytes != nr_bytes)
6402 payload_length = remote_escape_output (myaddr, new_nr_bytes,
6407 p += payload_length;
6408 if (use_length && nr_bytes < todo)
6410 /* Escape chars have filled up the buffer prematurely,
6411 and we have actually sent fewer bytes than planned.
6412 Fix-up the length field of the packet. Use the same
6413 number of characters as before. */
6414 plen += hexnumnstr (plen, (ULONGEST) nr_bytes, plenlen);
6415 *plen = ':'; /* overwrite \0 from hexnumnstr() */
6420 /* Normal mode: Send target system values byte by byte, in
6421 increasing byte addresses. Each byte is encoded as a two hex
6423 nr_bytes = bin2hex (myaddr, p, todo);
6427 putpkt_binary (rs->buf, (int) (p - rs->buf));
6428 getpkt (&rs->buf, &rs->buf_size, 0);
6430 if (rs->buf[0] == 'E')
6432 /* There is no correspondance between what the remote protocol
6433 uses for errors and errno codes. We would like a cleaner way
6434 of representing errors (big enough to include errno codes,
6435 bfd_error codes, and others). But for now just return EIO. */
6440 /* Return NR_BYTES, not TODO, in case escape chars caused us to send
6441 fewer bytes than we'd planned. */
6445 /* Write memory data directly to the remote machine.
6446 This does not inform the data cache; the data cache uses this.
6447 MEMADDR is the address in the remote memory space.
6448 MYADDR is the address of the buffer in our space.
6449 LEN is the number of bytes.
6451 Returns number of bytes transferred, or 0 (setting errno) for
6452 error. Only transfer a single packet. */
6455 remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, int len)
6457 char *packet_format = 0;
6459 /* Check whether the target supports binary download. */
6460 check_binary_download (memaddr);
6462 switch (remote_protocol_packets[PACKET_X].support)
6465 packet_format = "X";
6467 case PACKET_DISABLE:
6468 packet_format = "M";
6470 case PACKET_SUPPORT_UNKNOWN:
6471 internal_error (__FILE__, __LINE__,
6472 _("remote_write_bytes: bad internal state"));
6474 internal_error (__FILE__, __LINE__, _("bad switch"));
6477 return remote_write_bytes_aux (packet_format,
6478 memaddr, myaddr, len, packet_format[0], 1);
6481 /* Read memory data directly from the remote machine.
6482 This does not use the data cache; the data cache uses this.
6483 MEMADDR is the address in the remote memory space.
6484 MYADDR is the address of the buffer in our space.
6485 LEN is the number of bytes.
6487 Returns number of bytes transferred, or 0 for error. */
6490 remote_read_bytes (CORE_ADDR memaddr, gdb_byte *myaddr, int len)
6492 struct remote_state *rs = get_remote_state ();
6493 int max_buf_size; /* Max size of packet output buffer. */
6501 max_buf_size = get_memory_read_packet_size ();
6502 /* The packet buffer will be large enough for the payload;
6503 get_memory_packet_size ensures this. */
6505 /* Number if bytes that will fit. */
6506 todo = min (len, max_buf_size / 2);
6508 /* Construct "m"<memaddr>","<len>". */
6509 memaddr = remote_address_masked (memaddr);
6512 p += hexnumstr (p, (ULONGEST) memaddr);
6514 p += hexnumstr (p, (ULONGEST) todo);
6517 getpkt (&rs->buf, &rs->buf_size, 0);
6518 if (rs->buf[0] == 'E'
6519 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
6520 && rs->buf[3] == '\0')
6522 /* There is no correspondance between what the remote protocol
6523 uses for errors and errno codes. We would like a cleaner way
6524 of representing errors (big enough to include errno codes,
6525 bfd_error codes, and others). But for now just return
6530 /* Reply describes memory byte by byte, each byte encoded as two hex
6533 i = hex2bin (p, myaddr, todo);
6534 /* Return what we have. Let higher layers handle partial reads. */
6539 /* Remote notification handler. */
6542 handle_notification (char *buf, size_t length)
6544 if (strncmp (buf, "Stop:", 5) == 0)
6546 if (pending_stop_reply)
6548 /* We've already parsed the in-flight stop-reply, but the
6549 stub for some reason thought we didn't, possibly due to
6550 timeout on its side. Just ignore it. */
6552 fprintf_unfiltered (gdb_stdlog, "ignoring resent notification\n");
6556 struct cleanup *old_chain;
6557 struct stop_reply *reply = stop_reply_xmalloc ();
6559 old_chain = make_cleanup (do_stop_reply_xfree, reply);
6561 remote_parse_stop_reply (buf + 5, reply);
6563 discard_cleanups (old_chain);
6565 /* Be careful to only set it after parsing, since an error
6566 may be thrown then. */
6567 pending_stop_reply = reply;
6569 /* Notify the event loop there's a stop reply to acknowledge
6570 and that there may be more events to fetch. */
6571 mark_async_event_handler (remote_async_get_pending_events_token);
6574 fprintf_unfiltered (gdb_stdlog, "stop notification captured\n");
6578 /* We ignore notifications we don't recognize, for compatibility
6579 with newer stubs. */
6584 /* Read or write LEN bytes from inferior memory at MEMADDR,
6585 transferring to or from debugger address BUFFER. Write to inferior
6586 if SHOULD_WRITE is nonzero. Returns length of data written or
6587 read; 0 for error. TARGET is unused. */
6590 remote_xfer_memory (CORE_ADDR mem_addr, gdb_byte *buffer, int mem_len,
6591 int should_write, struct mem_attrib *attrib,
6592 struct target_ops *target)
6596 set_remote_traceframe ();
6597 set_general_thread (inferior_ptid);
6600 res = remote_write_bytes (mem_addr, buffer, mem_len);
6602 res = remote_read_bytes (mem_addr, buffer, mem_len);
6607 /* Sends a packet with content determined by the printf format string
6608 FORMAT and the remaining arguments, then gets the reply. Returns
6609 whether the packet was a success, a failure, or unknown. */
6611 static enum packet_result
6612 remote_send_printf (const char *format, ...)
6614 struct remote_state *rs = get_remote_state ();
6615 int max_size = get_remote_packet_size ();
6618 va_start (ap, format);
6621 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
6622 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
6624 if (putpkt (rs->buf) < 0)
6625 error (_("Communication problem with target."));
6628 getpkt (&rs->buf, &rs->buf_size, 0);
6630 return packet_check_result (rs->buf);
6634 restore_remote_timeout (void *p)
6636 int value = *(int *)p;
6638 remote_timeout = value;
6641 /* Flash writing can take quite some time. We'll set
6642 effectively infinite timeout for flash operations.
6643 In future, we'll need to decide on a better approach. */
6644 static const int remote_flash_timeout = 1000;
6647 remote_flash_erase (struct target_ops *ops,
6648 ULONGEST address, LONGEST length)
6650 int addr_size = gdbarch_addr_bit (target_gdbarch) / 8;
6651 int saved_remote_timeout = remote_timeout;
6652 enum packet_result ret;
6653 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
6654 &saved_remote_timeout);
6656 remote_timeout = remote_flash_timeout;
6658 ret = remote_send_printf ("vFlashErase:%s,%s",
6659 phex (address, addr_size),
6663 case PACKET_UNKNOWN:
6664 error (_("Remote target does not support flash erase"));
6666 error (_("Error erasing flash with vFlashErase packet"));
6671 do_cleanups (back_to);
6675 remote_flash_write (struct target_ops *ops,
6676 ULONGEST address, LONGEST length,
6677 const gdb_byte *data)
6679 int saved_remote_timeout = remote_timeout;
6681 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
6682 &saved_remote_timeout);
6684 remote_timeout = remote_flash_timeout;
6685 ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length, 'X', 0);
6686 do_cleanups (back_to);
6692 remote_flash_done (struct target_ops *ops)
6694 int saved_remote_timeout = remote_timeout;
6696 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
6697 &saved_remote_timeout);
6699 remote_timeout = remote_flash_timeout;
6700 ret = remote_send_printf ("vFlashDone");
6701 do_cleanups (back_to);
6705 case PACKET_UNKNOWN:
6706 error (_("Remote target does not support vFlashDone"));
6708 error (_("Error finishing flash operation"));
6715 remote_files_info (struct target_ops *ignore)
6717 puts_filtered ("Debugging a target over a serial line.\n");
6720 /* Stuff for dealing with the packets which are part of this protocol.
6721 See comment at top of file for details. */
6723 /* Read a single character from the remote end. */
6726 readchar (int timeout)
6730 ch = serial_readchar (remote_desc, timeout);
6735 switch ((enum serial_rc) ch)
6739 error (_("Remote connection closed"));
6743 perror_with_name (_("Remote communication error. "
6744 "Target disconnected."));
6746 case SERIAL_TIMEOUT:
6752 /* Send the command in *BUF to the remote machine, and read the reply
6753 into *BUF. Report an error if we get an error reply. Resize
6754 *BUF using xrealloc if necessary to hold the result, and update
6758 remote_send (char **buf,
6762 getpkt (buf, sizeof_buf, 0);
6764 if ((*buf)[0] == 'E')
6765 error (_("Remote failure reply: %s"), *buf);
6768 /* Return a pointer to an xmalloc'ed string representing an escaped
6769 version of BUF, of len N. E.g. \n is converted to \\n, \t to \\t,
6770 etc. The caller is responsible for releasing the returned
6774 escape_buffer (const char *buf, int n)
6776 struct cleanup *old_chain;
6777 struct ui_file *stb;
6780 stb = mem_fileopen ();
6781 old_chain = make_cleanup_ui_file_delete (stb);
6783 fputstrn_unfiltered (buf, n, 0, stb);
6784 str = ui_file_xstrdup (stb, NULL);
6785 do_cleanups (old_chain);
6789 /* Display a null-terminated packet on stdout, for debugging, using C
6793 print_packet (char *buf)
6795 puts_filtered ("\"");
6796 fputstr_filtered (buf, '"', gdb_stdout);
6797 puts_filtered ("\"");
6803 return putpkt_binary (buf, strlen (buf));
6806 /* Send a packet to the remote machine, with error checking. The data
6807 of the packet is in BUF. The string in BUF can be at most
6808 get_remote_packet_size () - 5 to account for the $, # and checksum,
6809 and for a possible /0 if we are debugging (remote_debug) and want
6810 to print the sent packet as a string. */
6813 putpkt_binary (char *buf, int cnt)
6815 struct remote_state *rs = get_remote_state ();
6817 unsigned char csum = 0;
6818 char *buf2 = alloca (cnt + 6);
6824 /* Catch cases like trying to read memory or listing threads while
6825 we're waiting for a stop reply. The remote server wouldn't be
6826 ready to handle this request, so we'd hang and timeout. We don't
6827 have to worry about this in synchronous mode, because in that
6828 case it's not possible to issue a command while the target is
6829 running. This is not a problem in non-stop mode, because in that
6830 case, the stub is always ready to process serial input. */
6831 if (!non_stop && target_can_async_p () && rs->waiting_for_stop_reply)
6832 error (_("Cannot execute this command while the target is running."));
6834 /* We're sending out a new packet. Make sure we don't look at a
6835 stale cached response. */
6836 rs->cached_wait_status = 0;
6838 /* Copy the packet into buffer BUF2, encapsulating it
6839 and giving it a checksum. */
6844 for (i = 0; i < cnt; i++)
6850 *p++ = tohex ((csum >> 4) & 0xf);
6851 *p++ = tohex (csum & 0xf);
6853 /* Send it over and over until we get a positive ack. */
6857 int started_error_output = 0;
6861 struct cleanup *old_chain;
6865 str = escape_buffer (buf2, p - buf2);
6866 old_chain = make_cleanup (xfree, str);
6867 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
6868 gdb_flush (gdb_stdlog);
6869 do_cleanups (old_chain);
6871 if (serial_write (remote_desc, buf2, p - buf2))
6872 perror_with_name (_("putpkt: write failed"));
6874 /* If this is a no acks version of the remote protocol, send the
6875 packet and move on. */
6879 /* Read until either a timeout occurs (-2) or '+' is read.
6880 Handle any notification that arrives in the mean time. */
6883 ch = readchar (remote_timeout);
6891 case SERIAL_TIMEOUT:
6894 if (started_error_output)
6896 putchar_unfiltered ('\n');
6897 started_error_output = 0;
6906 fprintf_unfiltered (gdb_stdlog, "Ack\n");
6910 fprintf_unfiltered (gdb_stdlog, "Nak\n");
6912 case SERIAL_TIMEOUT:
6916 break; /* Retransmit buffer. */
6920 fprintf_unfiltered (gdb_stdlog,
6921 "Packet instead of Ack, ignoring it\n");
6922 /* It's probably an old response sent because an ACK
6923 was lost. Gobble up the packet and ack it so it
6924 doesn't get retransmitted when we resend this
6927 serial_write (remote_desc, "+", 1);
6928 continue; /* Now, go look for +. */
6935 /* If we got a notification, handle it, and go back to looking
6937 /* We've found the start of a notification. Now
6938 collect the data. */
6939 val = read_frame (&rs->buf, &rs->buf_size);
6944 struct cleanup *old_chain;
6947 str = escape_buffer (rs->buf, val);
6948 old_chain = make_cleanup (xfree, str);
6949 fprintf_unfiltered (gdb_stdlog,
6950 " Notification received: %s\n",
6952 do_cleanups (old_chain);
6954 handle_notification (rs->buf, val);
6955 /* We're in sync now, rewait for the ack. */
6962 if (!started_error_output)
6964 started_error_output = 1;
6965 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
6967 fputc_unfiltered (ch & 0177, gdb_stdlog);
6968 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
6977 if (!started_error_output)
6979 started_error_output = 1;
6980 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
6982 fputc_unfiltered (ch & 0177, gdb_stdlog);
6986 break; /* Here to retransmit. */
6990 /* This is wrong. If doing a long backtrace, the user should be
6991 able to get out next time we call QUIT, without anything as
6992 violent as interrupt_query. If we want to provide a way out of
6993 here without getting to the next QUIT, it should be based on
6994 hitting ^C twice as in remote_wait. */
7005 /* Come here after finding the start of a frame when we expected an
7006 ack. Do our best to discard the rest of this packet. */
7015 c = readchar (remote_timeout);
7018 case SERIAL_TIMEOUT:
7019 /* Nothing we can do. */
7022 /* Discard the two bytes of checksum and stop. */
7023 c = readchar (remote_timeout);
7025 c = readchar (remote_timeout);
7028 case '*': /* Run length encoding. */
7029 /* Discard the repeat count. */
7030 c = readchar (remote_timeout);
7035 /* A regular character. */
7041 /* Come here after finding the start of the frame. Collect the rest
7042 into *BUF, verifying the checksum, length, and handling run-length
7043 compression. NUL terminate the buffer. If there is not enough room,
7044 expand *BUF using xrealloc.
7046 Returns -1 on error, number of characters in buffer (ignoring the
7047 trailing NULL) on success. (could be extended to return one of the
7048 SERIAL status indications). */
7051 read_frame (char **buf_p,
7058 struct remote_state *rs = get_remote_state ();
7065 c = readchar (remote_timeout);
7068 case SERIAL_TIMEOUT:
7070 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
7074 fputs_filtered ("Saw new packet start in middle of old one\n",
7076 return -1; /* Start a new packet, count retries. */
7079 unsigned char pktcsum;
7085 check_0 = readchar (remote_timeout);
7087 check_1 = readchar (remote_timeout);
7089 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
7092 fputs_filtered ("Timeout in checksum, retrying\n",
7096 else if (check_0 < 0 || check_1 < 0)
7099 fputs_filtered ("Communication error in checksum\n",
7104 /* Don't recompute the checksum; with no ack packets we
7105 don't have any way to indicate a packet retransmission
7110 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
7111 if (csum == pktcsum)
7116 struct cleanup *old_chain;
7119 str = escape_buffer (buf, bc);
7120 old_chain = make_cleanup (xfree, str);
7121 fprintf_unfiltered (gdb_stdlog,
7122 "Bad checksum, sentsum=0x%x, "
7123 "csum=0x%x, buf=%s\n",
7124 pktcsum, csum, str);
7125 do_cleanups (old_chain);
7127 /* Number of characters in buffer ignoring trailing
7131 case '*': /* Run length encoding. */
7136 c = readchar (remote_timeout);
7138 repeat = c - ' ' + 3; /* Compute repeat count. */
7140 /* The character before ``*'' is repeated. */
7142 if (repeat > 0 && repeat <= 255 && bc > 0)
7144 if (bc + repeat - 1 >= *sizeof_buf - 1)
7146 /* Make some more room in the buffer. */
7147 *sizeof_buf += repeat;
7148 *buf_p = xrealloc (*buf_p, *sizeof_buf);
7152 memset (&buf[bc], buf[bc - 1], repeat);
7158 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
7162 if (bc >= *sizeof_buf - 1)
7164 /* Make some more room in the buffer. */
7166 *buf_p = xrealloc (*buf_p, *sizeof_buf);
7177 /* Read a packet from the remote machine, with error checking, and
7178 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
7179 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
7180 rather than timing out; this is used (in synchronous mode) to wait
7181 for a target that is is executing user code to stop. */
7182 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
7183 don't have to change all the calls to getpkt to deal with the
7184 return value, because at the moment I don't know what the right
7185 thing to do it for those. */
7193 timed_out = getpkt_sane (buf, sizeof_buf, forever);
7197 /* Read a packet from the remote machine, with error checking, and
7198 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
7199 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
7200 rather than timing out; this is used (in synchronous mode) to wait
7201 for a target that is is executing user code to stop. If FOREVER ==
7202 0, this function is allowed to time out gracefully and return an
7203 indication of this to the caller. Otherwise return the number of
7204 bytes read. If EXPECTING_NOTIF, consider receiving a notification
7205 enough reason to return to the caller. */
7208 getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
7209 int expecting_notif)
7211 struct remote_state *rs = get_remote_state ();
7217 /* We're reading a new response. Make sure we don't look at a
7218 previously cached response. */
7219 rs->cached_wait_status = 0;
7221 strcpy (*buf, "timeout");
7224 timeout = watchdog > 0 ? watchdog : -1;
7225 else if (expecting_notif)
7226 timeout = 0; /* There should already be a char in the buffer. If
7229 timeout = remote_timeout;
7233 /* Process any number of notifications, and then return when
7237 /* If we get a timeout or bad checksm, retry up to MAX_TRIES
7239 for (tries = 1; tries <= MAX_TRIES; tries++)
7241 /* This can loop forever if the remote side sends us
7242 characters continuously, but if it pauses, we'll get
7243 SERIAL_TIMEOUT from readchar because of timeout. Then
7244 we'll count that as a retry.
7246 Note that even when forever is set, we will only wait
7247 forever prior to the start of a packet. After that, we
7248 expect characters to arrive at a brisk pace. They should
7249 show up within remote_timeout intervals. */
7251 c = readchar (timeout);
7252 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
7254 if (c == SERIAL_TIMEOUT)
7256 if (expecting_notif)
7257 return -1; /* Don't complain, it's normal to not get
7258 anything in this case. */
7260 if (forever) /* Watchdog went off? Kill the target. */
7264 error (_("Watchdog timeout has expired. Target detached."));
7267 fputs_filtered ("Timed out.\n", gdb_stdlog);
7271 /* We've found the start of a packet or notification.
7272 Now collect the data. */
7273 val = read_frame (buf, sizeof_buf);
7278 serial_write (remote_desc, "-", 1);
7281 if (tries > MAX_TRIES)
7283 /* We have tried hard enough, and just can't receive the
7284 packet/notification. Give up. */
7285 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
7287 /* Skip the ack char if we're in no-ack mode. */
7288 if (!rs->noack_mode)
7289 serial_write (remote_desc, "+", 1);
7293 /* If we got an ordinary packet, return that to our caller. */
7298 struct cleanup *old_chain;
7301 str = escape_buffer (*buf, val);
7302 old_chain = make_cleanup (xfree, str);
7303 fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
7304 do_cleanups (old_chain);
7307 /* Skip the ack char if we're in no-ack mode. */
7308 if (!rs->noack_mode)
7309 serial_write (remote_desc, "+", 1);
7313 /* If we got a notification, handle it, and go back to looking
7317 gdb_assert (c == '%');
7321 struct cleanup *old_chain;
7324 str = escape_buffer (*buf, val);
7325 old_chain = make_cleanup (xfree, str);
7326 fprintf_unfiltered (gdb_stdlog,
7327 " Notification received: %s\n",
7329 do_cleanups (old_chain);
7332 handle_notification (*buf, val);
7334 /* Notifications require no acknowledgement. */
7336 if (expecting_notif)
7343 getpkt_sane (char **buf, long *sizeof_buf, int forever)
7345 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0);
7349 getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever)
7351 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1);
7356 remote_kill (struct target_ops *ops)
7358 /* Use catch_errors so the user can quit from gdb even when we
7359 aren't on speaking terms with the remote system. */
7360 catch_errors ((catch_errors_ftype *) putpkt, "k", "", RETURN_MASK_ERROR);
7362 /* Don't wait for it to die. I'm not really sure it matters whether
7363 we do or not. For the existing stubs, kill is a noop. */
7364 target_mourn_inferior ();
7368 remote_vkill (int pid, struct remote_state *rs)
7370 if (remote_protocol_packets[PACKET_vKill].support == PACKET_DISABLE)
7373 /* Tell the remote target to detach. */
7374 sprintf (rs->buf, "vKill;%x", pid);
7376 getpkt (&rs->buf, &rs->buf_size, 0);
7378 if (packet_ok (rs->buf,
7379 &remote_protocol_packets[PACKET_vKill]) == PACKET_OK)
7381 else if (remote_protocol_packets[PACKET_vKill].support == PACKET_DISABLE)
7388 extended_remote_kill (struct target_ops *ops)
7391 int pid = ptid_get_pid (inferior_ptid);
7392 struct remote_state *rs = get_remote_state ();
7394 res = remote_vkill (pid, rs);
7395 if (res == -1 && !remote_multi_process_p (rs))
7397 /* Don't try 'k' on a multi-process aware stub -- it has no way
7398 to specify the pid. */
7402 getpkt (&rs->buf, &rs->buf_size, 0);
7403 if (rs->buf[0] != 'O' || rs->buf[0] != 'K')
7406 /* Don't wait for it to die. I'm not really sure it matters whether
7407 we do or not. For the existing stubs, kill is a noop. */
7413 error (_("Can't kill process"));
7415 target_mourn_inferior ();
7419 remote_mourn (struct target_ops *ops)
7421 remote_mourn_1 (ops);
7424 /* Worker function for remote_mourn. */
7426 remote_mourn_1 (struct target_ops *target)
7428 unpush_target (target);
7430 /* remote_close takes care of doing most of the clean up. */
7431 generic_mourn_inferior ();
7435 extended_remote_mourn_1 (struct target_ops *target)
7437 struct remote_state *rs = get_remote_state ();
7439 /* In case we got here due to an error, but we're going to stay
7441 rs->waiting_for_stop_reply = 0;
7443 /* We're no longer interested in these events. */
7444 discard_pending_stop_replies (ptid_get_pid (inferior_ptid));
7446 /* If the current general thread belonged to the process we just
7447 detached from or has exited, the remote side current general
7448 thread becomes undefined. Considering a case like this:
7450 - We just got here due to a detach.
7451 - The process that we're detaching from happens to immediately
7452 report a global breakpoint being hit in non-stop mode, in the
7453 same thread we had selected before.
7454 - GDB attaches to this process again.
7455 - This event happens to be the next event we handle.
7457 GDB would consider that the current general thread didn't need to
7458 be set on the stub side (with Hg), since for all it knew,
7459 GENERAL_THREAD hadn't changed.
7461 Notice that although in all-stop mode, the remote server always
7462 sets the current thread to the thread reporting the stop event,
7463 that doesn't happen in non-stop mode; in non-stop, the stub *must
7464 not* change the current thread when reporting a breakpoint hit,
7465 due to the decoupling of event reporting and event handling.
7467 To keep things simple, we always invalidate our notion of the
7469 record_currthread (minus_one_ptid);
7471 /* Unlike "target remote", we do not want to unpush the target; then
7472 the next time the user says "run", we won't be connected. */
7474 /* Call common code to mark the inferior as not running. */
7475 generic_mourn_inferior ();
7477 if (!have_inferiors ())
7479 if (!remote_multi_process_p (rs))
7481 /* Check whether the target is running now - some remote stubs
7482 automatically restart after kill. */
7484 getpkt (&rs->buf, &rs->buf_size, 0);
7486 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
7488 /* Assume that the target has been restarted. Set
7489 inferior_ptid so that bits of core GDB realizes
7490 there's something here, e.g., so that the user can
7491 say "kill" again. */
7492 inferior_ptid = magic_null_ptid;
7499 extended_remote_mourn (struct target_ops *ops)
7501 extended_remote_mourn_1 (ops);
7505 extended_remote_supports_disable_randomization (void)
7507 return (remote_protocol_packets[PACKET_QDisableRandomization].support
7512 extended_remote_disable_randomization (int val)
7514 struct remote_state *rs = get_remote_state ();
7517 sprintf (rs->buf, "QDisableRandomization:%x", val);
7519 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
7521 error (_("Target does not support QDisableRandomization."));
7522 if (strcmp (reply, "OK") != 0)
7523 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
7527 extended_remote_run (char *args)
7529 struct remote_state *rs = get_remote_state ();
7532 /* If the user has disabled vRun support, or we have detected that
7533 support is not available, do not try it. */
7534 if (remote_protocol_packets[PACKET_vRun].support == PACKET_DISABLE)
7537 strcpy (rs->buf, "vRun;");
7538 len = strlen (rs->buf);
7540 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
7541 error (_("Remote file name too long for run packet"));
7542 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len, 0);
7544 gdb_assert (args != NULL);
7547 struct cleanup *back_to;
7551 argv = gdb_buildargv (args);
7552 back_to = make_cleanup ((void (*) (void *)) freeargv, argv);
7553 for (i = 0; argv[i] != NULL; i++)
7555 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
7556 error (_("Argument list too long for run packet"));
7557 rs->buf[len++] = ';';
7558 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len, 0);
7560 do_cleanups (back_to);
7563 rs->buf[len++] = '\0';
7566 getpkt (&rs->buf, &rs->buf_size, 0);
7568 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]) == PACKET_OK)
7570 /* We have a wait response; we don't need it, though. All is well. */
7573 else if (remote_protocol_packets[PACKET_vRun].support == PACKET_DISABLE)
7574 /* It wasn't disabled before, but it is now. */
7578 if (remote_exec_file[0] == '\0')
7579 error (_("Running the default executable on the remote target failed; "
7580 "try \"set remote exec-file\"?"));
7582 error (_("Running \"%s\" on the remote target failed"),
7587 /* In the extended protocol we want to be able to do things like
7588 "run" and have them basically work as expected. So we need
7589 a special create_inferior function. We support changing the
7590 executable file and the command line arguments, but not the
7594 extended_remote_create_inferior_1 (char *exec_file, char *args,
7595 char **env, int from_tty)
7597 /* If running asynchronously, register the target file descriptor
7598 with the event loop. */
7599 if (target_can_async_p ())
7600 target_async (inferior_event_handler, 0);
7602 /* Disable address space randomization if requested (and supported). */
7603 if (extended_remote_supports_disable_randomization ())
7604 extended_remote_disable_randomization (disable_randomization);
7606 /* Now restart the remote server. */
7607 if (extended_remote_run (args) == -1)
7609 /* vRun was not supported. Fail if we need it to do what the
7611 if (remote_exec_file[0])
7612 error (_("Remote target does not support \"set remote exec-file\""));
7614 error (_("Remote target does not support \"set args\" or run <ARGS>"));
7616 /* Fall back to "R". */
7617 extended_remote_restart ();
7620 if (!have_inferiors ())
7622 /* Clean up from the last time we ran, before we mark the target
7623 running again. This will mark breakpoints uninserted, and
7624 get_offsets may insert breakpoints. */
7625 init_thread_list ();
7626 init_wait_for_inferior ();
7629 /* Now mark the inferior as running before we do anything else. */
7630 inferior_ptid = magic_null_ptid;
7632 /* Now, if we have thread information, update inferior_ptid. */
7633 inferior_ptid = remote_current_thread (inferior_ptid);
7635 remote_add_inferior (ptid_get_pid (inferior_ptid), 0);
7636 add_thread_silent (inferior_ptid);
7638 /* Get updated offsets, if the stub uses qOffsets. */
7643 extended_remote_create_inferior (struct target_ops *ops,
7644 char *exec_file, char *args,
7645 char **env, int from_tty)
7647 extended_remote_create_inferior_1 (exec_file, args, env, from_tty);
7651 /* Insert a breakpoint. On targets that have software breakpoint
7652 support, we ask the remote target to do the work; on targets
7653 which don't, we insert a traditional memory breakpoint. */
7656 remote_insert_breakpoint (struct gdbarch *gdbarch,
7657 struct bp_target_info *bp_tgt)
7659 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
7660 If it succeeds, then set the support to PACKET_ENABLE. If it
7661 fails, and the user has explicitly requested the Z support then
7662 report an error, otherwise, mark it disabled and go on. */
7664 if (remote_protocol_packets[PACKET_Z0].support != PACKET_DISABLE)
7666 CORE_ADDR addr = bp_tgt->placed_address;
7667 struct remote_state *rs;
7671 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
7673 rs = get_remote_state ();
7679 addr = (ULONGEST) remote_address_masked (addr);
7680 p += hexnumstr (p, addr);
7681 sprintf (p, ",%d", bpsize);
7684 getpkt (&rs->buf, &rs->buf_size, 0);
7686 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
7691 bp_tgt->placed_address = addr;
7692 bp_tgt->placed_size = bpsize;
7694 case PACKET_UNKNOWN:
7699 return memory_insert_breakpoint (gdbarch, bp_tgt);
7703 remote_remove_breakpoint (struct gdbarch *gdbarch,
7704 struct bp_target_info *bp_tgt)
7706 CORE_ADDR addr = bp_tgt->placed_address;
7707 struct remote_state *rs = get_remote_state ();
7709 if (remote_protocol_packets[PACKET_Z0].support != PACKET_DISABLE)
7717 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
7718 p += hexnumstr (p, addr);
7719 sprintf (p, ",%d", bp_tgt->placed_size);
7722 getpkt (&rs->buf, &rs->buf_size, 0);
7724 return (rs->buf[0] == 'E');
7727 return memory_remove_breakpoint (gdbarch, bp_tgt);
7731 watchpoint_to_Z_packet (int type)
7736 return Z_PACKET_WRITE_WP;
7739 return Z_PACKET_READ_WP;
7742 return Z_PACKET_ACCESS_WP;
7745 internal_error (__FILE__, __LINE__,
7746 _("hw_bp_to_z: bad watchpoint type %d"), type);
7751 remote_insert_watchpoint (CORE_ADDR addr, int len, int type,
7752 struct expression *cond)
7754 struct remote_state *rs = get_remote_state ();
7756 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
7758 if (remote_protocol_packets[PACKET_Z0 + packet].support == PACKET_DISABLE)
7761 sprintf (rs->buf, "Z%x,", packet);
7762 p = strchr (rs->buf, '\0');
7763 addr = remote_address_masked (addr);
7764 p += hexnumstr (p, (ULONGEST) addr);
7765 sprintf (p, ",%x", len);
7768 getpkt (&rs->buf, &rs->buf_size, 0);
7770 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
7774 case PACKET_UNKNOWN:
7779 internal_error (__FILE__, __LINE__,
7780 _("remote_insert_watchpoint: reached end of function"));
7785 remote_remove_watchpoint (CORE_ADDR addr, int len, int type,
7786 struct expression *cond)
7788 struct remote_state *rs = get_remote_state ();
7790 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
7792 if (remote_protocol_packets[PACKET_Z0 + packet].support == PACKET_DISABLE)
7795 sprintf (rs->buf, "z%x,", packet);
7796 p = strchr (rs->buf, '\0');
7797 addr = remote_address_masked (addr);
7798 p += hexnumstr (p, (ULONGEST) addr);
7799 sprintf (p, ",%x", len);
7801 getpkt (&rs->buf, &rs->buf_size, 0);
7803 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
7806 case PACKET_UNKNOWN:
7811 internal_error (__FILE__, __LINE__,
7812 _("remote_remove_watchpoint: reached end of function"));
7816 int remote_hw_watchpoint_limit = -1;
7817 int remote_hw_watchpoint_length_limit = -1;
7818 int remote_hw_breakpoint_limit = -1;
7821 remote_region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
7823 if (remote_hw_watchpoint_length_limit == 0)
7825 else if (remote_hw_watchpoint_length_limit < 0)
7827 else if (len <= remote_hw_watchpoint_length_limit)
7834 remote_check_watch_resources (int type, int cnt, int ot)
7836 if (type == bp_hardware_breakpoint)
7838 if (remote_hw_breakpoint_limit == 0)
7840 else if (remote_hw_breakpoint_limit < 0)
7842 else if (cnt <= remote_hw_breakpoint_limit)
7847 if (remote_hw_watchpoint_limit == 0)
7849 else if (remote_hw_watchpoint_limit < 0)
7853 else if (cnt <= remote_hw_watchpoint_limit)
7860 remote_stopped_by_watchpoint (void)
7862 return remote_stopped_by_watchpoint_p;
7866 remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
7870 if (remote_stopped_by_watchpoint ())
7872 *addr_p = remote_watch_data_address;
7881 remote_insert_hw_breakpoint (struct gdbarch *gdbarch,
7882 struct bp_target_info *bp_tgt)
7885 struct remote_state *rs;
7888 /* The length field should be set to the size of a breakpoint
7889 instruction, even though we aren't inserting one ourselves. */
7891 gdbarch_remote_breakpoint_from_pc
7892 (gdbarch, &bp_tgt->placed_address, &bp_tgt->placed_size);
7894 if (remote_protocol_packets[PACKET_Z1].support == PACKET_DISABLE)
7897 rs = get_remote_state ();
7904 addr = remote_address_masked (bp_tgt->placed_address);
7905 p += hexnumstr (p, (ULONGEST) addr);
7906 sprintf (p, ",%x", bp_tgt->placed_size);
7909 getpkt (&rs->buf, &rs->buf_size, 0);
7911 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
7914 case PACKET_UNKNOWN:
7919 internal_error (__FILE__, __LINE__,
7920 _("remote_insert_hw_breakpoint: reached end of function"));
7925 remote_remove_hw_breakpoint (struct gdbarch *gdbarch,
7926 struct bp_target_info *bp_tgt)
7929 struct remote_state *rs = get_remote_state ();
7932 if (remote_protocol_packets[PACKET_Z1].support == PACKET_DISABLE)
7939 addr = remote_address_masked (bp_tgt->placed_address);
7940 p += hexnumstr (p, (ULONGEST) addr);
7941 sprintf (p, ",%x", bp_tgt->placed_size);
7944 getpkt (&rs->buf, &rs->buf_size, 0);
7946 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
7949 case PACKET_UNKNOWN:
7954 internal_error (__FILE__, __LINE__,
7955 _("remote_remove_hw_breakpoint: reached end of function"));
7958 /* Table used by the crc32 function to calcuate the checksum. */
7960 static unsigned long crc32_table[256] =
7963 static unsigned long
7964 crc32 (const unsigned char *buf, int len, unsigned int crc)
7966 if (!crc32_table[1])
7968 /* Initialize the CRC table and the decoding table. */
7972 for (i = 0; i < 256; i++)
7974 for (c = i << 24, j = 8; j > 0; --j)
7975 c = c & 0x80000000 ? (c << 1) ^ 0x04c11db7 : (c << 1);
7982 crc = (crc << 8) ^ crc32_table[((crc >> 24) ^ *buf) & 255];
7988 /* Verify memory using the "qCRC:" request. */
7991 remote_verify_memory (struct target_ops *ops,
7992 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
7994 struct remote_state *rs = get_remote_state ();
7995 unsigned long host_crc, target_crc;
7998 /* FIXME: assumes lma can fit into long. */
7999 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
8000 (long) lma, (long) size);
8003 /* Be clever; compute the host_crc before waiting for target
8005 host_crc = crc32 (data, size, 0xffffffff);
8007 getpkt (&rs->buf, &rs->buf_size, 0);
8008 if (rs->buf[0] == 'E')
8011 if (rs->buf[0] != 'C')
8012 error (_("remote target does not support this operation"));
8014 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
8015 target_crc = target_crc * 16 + fromhex (*tmp);
8017 return (host_crc == target_crc);
8020 /* compare-sections command
8022 With no arguments, compares each loadable section in the exec bfd
8023 with the same memory range on the target, and reports mismatches.
8024 Useful for verifying the image on the target against the exec file. */
8027 compare_sections_command (char *args, int from_tty)
8030 struct cleanup *old_chain;
8032 const char *sectname;
8040 error (_("command cannot be used without an exec file"));
8042 for (s = exec_bfd->sections; s; s = s->next)
8044 if (!(s->flags & SEC_LOAD))
8045 continue; /* Skip non-loadable section. */
8047 size = bfd_get_section_size (s);
8049 continue; /* Skip zero-length section. */
8051 sectname = bfd_get_section_name (exec_bfd, s);
8052 if (args && strcmp (args, sectname) != 0)
8053 continue; /* Not the section selected by user. */
8055 matched = 1; /* Do this section. */
8058 sectdata = xmalloc (size);
8059 old_chain = make_cleanup (xfree, sectdata);
8060 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
8062 res = target_verify_memory (sectdata, lma, size);
8065 error (_("target memory fault, section %s, range %s -- %s"), sectname,
8066 paddress (target_gdbarch, lma),
8067 paddress (target_gdbarch, lma + size));
8069 printf_filtered ("Section %s, range %s -- %s: ", sectname,
8070 paddress (target_gdbarch, lma),
8071 paddress (target_gdbarch, lma + size));
8073 printf_filtered ("matched.\n");
8076 printf_filtered ("MIS-MATCHED!\n");
8080 do_cleanups (old_chain);
8083 warning (_("One or more sections of the remote executable does not match\n\
8084 the loaded file\n"));
8085 if (args && !matched)
8086 printf_filtered (_("No loaded section named '%s'.\n"), args);
8089 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
8090 into remote target. The number of bytes written to the remote
8091 target is returned, or -1 for error. */
8094 remote_write_qxfer (struct target_ops *ops, const char *object_name,
8095 const char *annex, const gdb_byte *writebuf,
8096 ULONGEST offset, LONGEST len,
8097 struct packet_config *packet)
8101 struct remote_state *rs = get_remote_state ();
8102 int max_size = get_memory_write_packet_size ();
8104 if (packet->support == PACKET_DISABLE)
8107 /* Insert header. */
8108 i = snprintf (rs->buf, max_size,
8109 "qXfer:%s:write:%s:%s:",
8110 object_name, annex ? annex : "",
8111 phex_nz (offset, sizeof offset));
8112 max_size -= (i + 1);
8114 /* Escape as much data as fits into rs->buf. */
8115 buf_len = remote_escape_output
8116 (writebuf, len, (rs->buf + i), &max_size, max_size);
8118 if (putpkt_binary (rs->buf, i + buf_len) < 0
8119 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
8120 || packet_ok (rs->buf, packet) != PACKET_OK)
8123 unpack_varlen_hex (rs->buf, &n);
8127 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
8128 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
8129 number of bytes read is returned, or 0 for EOF, or -1 for error.
8130 The number of bytes read may be less than LEN without indicating an
8131 EOF. PACKET is checked and updated to indicate whether the remote
8132 target supports this object. */
8135 remote_read_qxfer (struct target_ops *ops, const char *object_name,
8137 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
8138 struct packet_config *packet)
8140 static char *finished_object;
8141 static char *finished_annex;
8142 static ULONGEST finished_offset;
8144 struct remote_state *rs = get_remote_state ();
8145 LONGEST i, n, packet_len;
8147 if (packet->support == PACKET_DISABLE)
8150 /* Check whether we've cached an end-of-object packet that matches
8152 if (finished_object)
8154 if (strcmp (object_name, finished_object) == 0
8155 && strcmp (annex ? annex : "", finished_annex) == 0
8156 && offset == finished_offset)
8159 /* Otherwise, we're now reading something different. Discard
8161 xfree (finished_object);
8162 xfree (finished_annex);
8163 finished_object = NULL;
8164 finished_annex = NULL;
8167 /* Request only enough to fit in a single packet. The actual data
8168 may not, since we don't know how much of it will need to be escaped;
8169 the target is free to respond with slightly less data. We subtract
8170 five to account for the response type and the protocol frame. */
8171 n = min (get_remote_packet_size () - 5, len);
8172 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
8173 object_name, annex ? annex : "",
8174 phex_nz (offset, sizeof offset),
8175 phex_nz (n, sizeof n));
8176 i = putpkt (rs->buf);
8181 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
8182 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
8185 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
8186 error (_("Unknown remote qXfer reply: %s"), rs->buf);
8188 /* 'm' means there is (or at least might be) more data after this
8189 batch. That does not make sense unless there's at least one byte
8190 of data in this reply. */
8191 if (rs->buf[0] == 'm' && packet_len == 1)
8192 error (_("Remote qXfer reply contained no data."));
8194 /* Got some data. */
8195 i = remote_unescape_input (rs->buf + 1, packet_len - 1, readbuf, n);
8197 /* 'l' is an EOF marker, possibly including a final block of data,
8198 or possibly empty. If we have the final block of a non-empty
8199 object, record this fact to bypass a subsequent partial read. */
8200 if (rs->buf[0] == 'l' && offset + i > 0)
8202 finished_object = xstrdup (object_name);
8203 finished_annex = xstrdup (annex ? annex : "");
8204 finished_offset = offset + i;
8211 remote_xfer_partial (struct target_ops *ops, enum target_object object,
8212 const char *annex, gdb_byte *readbuf,
8213 const gdb_byte *writebuf, ULONGEST offset, LONGEST len)
8215 struct remote_state *rs;
8220 set_remote_traceframe ();
8221 set_general_thread (inferior_ptid);
8223 rs = get_remote_state ();
8225 /* Handle memory using the standard memory routines. */
8226 if (object == TARGET_OBJECT_MEMORY)
8232 /* If the remote target is connected but not running, we should
8233 pass this request down to a lower stratum (e.g. the executable
8235 if (!target_has_execution)
8238 if (writebuf != NULL)
8239 xfered = remote_write_bytes (offset, writebuf, len);
8241 xfered = remote_read_bytes (offset, readbuf, len);
8245 else if (xfered == 0 && errno == 0)
8251 /* Handle SPU memory using qxfer packets. */
8252 if (object == TARGET_OBJECT_SPU)
8255 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
8256 &remote_protocol_packets
8257 [PACKET_qXfer_spu_read]);
8259 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
8260 &remote_protocol_packets
8261 [PACKET_qXfer_spu_write]);
8264 /* Handle extra signal info using qxfer packets. */
8265 if (object == TARGET_OBJECT_SIGNAL_INFO)
8268 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
8269 &remote_protocol_packets
8270 [PACKET_qXfer_siginfo_read]);
8272 return remote_write_qxfer (ops, "siginfo", annex,
8273 writebuf, offset, len,
8274 &remote_protocol_packets
8275 [PACKET_qXfer_siginfo_write]);
8278 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
8281 return remote_read_qxfer (ops, "statictrace", annex,
8282 readbuf, offset, len,
8283 &remote_protocol_packets
8284 [PACKET_qXfer_statictrace_read]);
8289 /* Only handle flash writes. */
8290 if (writebuf != NULL)
8296 case TARGET_OBJECT_FLASH:
8297 xfered = remote_flash_write (ops, offset, len, writebuf);
8301 else if (xfered == 0 && errno == 0)
8311 /* Map pre-existing objects onto letters. DO NOT do this for new
8312 objects!!! Instead specify new query packets. */
8315 case TARGET_OBJECT_AVR:
8319 case TARGET_OBJECT_AUXV:
8320 gdb_assert (annex == NULL);
8321 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
8322 &remote_protocol_packets[PACKET_qXfer_auxv]);
8324 case TARGET_OBJECT_AVAILABLE_FEATURES:
8325 return remote_read_qxfer
8326 (ops, "features", annex, readbuf, offset, len,
8327 &remote_protocol_packets[PACKET_qXfer_features]);
8329 case TARGET_OBJECT_LIBRARIES:
8330 return remote_read_qxfer
8331 (ops, "libraries", annex, readbuf, offset, len,
8332 &remote_protocol_packets[PACKET_qXfer_libraries]);
8334 case TARGET_OBJECT_MEMORY_MAP:
8335 gdb_assert (annex == NULL);
8336 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
8337 &remote_protocol_packets[PACKET_qXfer_memory_map]);
8339 case TARGET_OBJECT_OSDATA:
8340 /* Should only get here if we're connected. */
8341 gdb_assert (remote_desc);
8342 return remote_read_qxfer
8343 (ops, "osdata", annex, readbuf, offset, len,
8344 &remote_protocol_packets[PACKET_qXfer_osdata]);
8346 case TARGET_OBJECT_THREADS:
8347 gdb_assert (annex == NULL);
8348 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
8349 &remote_protocol_packets[PACKET_qXfer_threads]);
8351 case TARGET_OBJECT_TRACEFRAME_INFO:
8352 gdb_assert (annex == NULL);
8353 return remote_read_qxfer
8354 (ops, "traceframe-info", annex, readbuf, offset, len,
8355 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
8357 case TARGET_OBJECT_FDPIC:
8358 return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
8359 &remote_protocol_packets[PACKET_qXfer_fdpic]);
8364 /* Note: a zero OFFSET and LEN can be used to query the minimum
8366 if (offset == 0 && len == 0)
8367 return (get_remote_packet_size ());
8368 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
8369 large enough let the caller deal with it. */
8370 if (len < get_remote_packet_size ())
8372 len = get_remote_packet_size ();
8374 /* Except for querying the minimum buffer size, target must be open. */
8376 error (_("remote query is only available after target open"));
8378 gdb_assert (annex != NULL);
8379 gdb_assert (readbuf != NULL);
8385 /* We used one buffer char for the remote protocol q command and
8386 another for the query type. As the remote protocol encapsulation
8387 uses 4 chars plus one extra in case we are debugging
8388 (remote_debug), we have PBUFZIZ - 7 left to pack the query
8391 while (annex[i] && (i < (get_remote_packet_size () - 8)))
8393 /* Bad caller may have sent forbidden characters. */
8394 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
8399 gdb_assert (annex[i] == '\0');
8401 i = putpkt (rs->buf);
8405 getpkt (&rs->buf, &rs->buf_size, 0);
8406 strcpy ((char *) readbuf, rs->buf);
8408 return strlen ((char *) readbuf);
8412 remote_search_memory (struct target_ops* ops,
8413 CORE_ADDR start_addr, ULONGEST search_space_len,
8414 const gdb_byte *pattern, ULONGEST pattern_len,
8415 CORE_ADDR *found_addrp)
8417 int addr_size = gdbarch_addr_bit (target_gdbarch) / 8;
8418 struct remote_state *rs = get_remote_state ();
8419 int max_size = get_memory_write_packet_size ();
8420 struct packet_config *packet =
8421 &remote_protocol_packets[PACKET_qSearch_memory];
8422 /* Number of packet bytes used to encode the pattern;
8423 this could be more than PATTERN_LEN due to escape characters. */
8424 int escaped_pattern_len;
8425 /* Amount of pattern that was encodable in the packet. */
8426 int used_pattern_len;
8429 ULONGEST found_addr;
8431 /* Don't go to the target if we don't have to.
8432 This is done before checking packet->support to avoid the possibility that
8433 a success for this edge case means the facility works in general. */
8434 if (pattern_len > search_space_len)
8436 if (pattern_len == 0)
8438 *found_addrp = start_addr;
8442 /* If we already know the packet isn't supported, fall back to the simple
8443 way of searching memory. */
8445 if (packet->support == PACKET_DISABLE)
8447 /* Target doesn't provided special support, fall back and use the
8448 standard support (copy memory and do the search here). */
8449 return simple_search_memory (ops, start_addr, search_space_len,
8450 pattern, pattern_len, found_addrp);
8453 /* Insert header. */
8454 i = snprintf (rs->buf, max_size,
8455 "qSearch:memory:%s;%s;",
8456 phex_nz (start_addr, addr_size),
8457 phex_nz (search_space_len, sizeof (search_space_len)));
8458 max_size -= (i + 1);
8460 /* Escape as much data as fits into rs->buf. */
8461 escaped_pattern_len =
8462 remote_escape_output (pattern, pattern_len, (rs->buf + i),
8463 &used_pattern_len, max_size);
8465 /* Bail if the pattern is too large. */
8466 if (used_pattern_len != pattern_len)
8467 error (_("Pattern is too large to transmit to remote target."));
8469 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
8470 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
8471 || packet_ok (rs->buf, packet) != PACKET_OK)
8473 /* The request may not have worked because the command is not
8474 supported. If so, fall back to the simple way. */
8475 if (packet->support == PACKET_DISABLE)
8477 return simple_search_memory (ops, start_addr, search_space_len,
8478 pattern, pattern_len, found_addrp);
8483 if (rs->buf[0] == '0')
8485 else if (rs->buf[0] == '1')
8488 if (rs->buf[1] != ',')
8489 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
8490 unpack_varlen_hex (rs->buf + 2, &found_addr);
8491 *found_addrp = found_addr;
8494 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
8500 remote_rcmd (char *command,
8501 struct ui_file *outbuf)
8503 struct remote_state *rs = get_remote_state ();
8507 error (_("remote rcmd is only available after target open"));
8509 /* Send a NULL command across as an empty command. */
8510 if (command == NULL)
8513 /* The query prefix. */
8514 strcpy (rs->buf, "qRcmd,");
8515 p = strchr (rs->buf, '\0');
8517 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
8518 > get_remote_packet_size ())
8519 error (_("\"monitor\" command ``%s'' is too long."), command);
8521 /* Encode the actual command. */
8522 bin2hex ((gdb_byte *) command, p, 0);
8524 if (putpkt (rs->buf) < 0)
8525 error (_("Communication problem with target."));
8527 /* get/display the response */
8532 /* XXX - see also remote_get_noisy_reply(). */
8534 getpkt (&rs->buf, &rs->buf_size, 0);
8537 error (_("Target does not support this command."));
8538 if (buf[0] == 'O' && buf[1] != 'K')
8540 remote_console_output (buf + 1); /* 'O' message from stub. */
8543 if (strcmp (buf, "OK") == 0)
8545 if (strlen (buf) == 3 && buf[0] == 'E'
8546 && isdigit (buf[1]) && isdigit (buf[2]))
8548 error (_("Protocol error with Rcmd"));
8550 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
8552 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
8554 fputc_unfiltered (c, outbuf);
8560 static VEC(mem_region_s) *
8561 remote_memory_map (struct target_ops *ops)
8563 VEC(mem_region_s) *result = NULL;
8564 char *text = target_read_stralloc (¤t_target,
8565 TARGET_OBJECT_MEMORY_MAP, NULL);
8569 struct cleanup *back_to = make_cleanup (xfree, text);
8571 result = parse_memory_map (text);
8572 do_cleanups (back_to);
8579 packet_command (char *args, int from_tty)
8581 struct remote_state *rs = get_remote_state ();
8584 error (_("command can only be used with remote target"));
8587 error (_("remote-packet command requires packet text as argument"));
8589 puts_filtered ("sending: ");
8590 print_packet (args);
8591 puts_filtered ("\n");
8594 getpkt (&rs->buf, &rs->buf_size, 0);
8595 puts_filtered ("received: ");
8596 print_packet (rs->buf);
8597 puts_filtered ("\n");
8601 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
8603 static void display_thread_info (struct gdb_ext_thread_info *info);
8605 static void threadset_test_cmd (char *cmd, int tty);
8607 static void threadalive_test (char *cmd, int tty);
8609 static void threadlist_test_cmd (char *cmd, int tty);
8611 int get_and_display_threadinfo (threadref *ref);
8613 static void threadinfo_test_cmd (char *cmd, int tty);
8615 static int thread_display_step (threadref *ref, void *context);
8617 static void threadlist_update_test_cmd (char *cmd, int tty);
8619 static void init_remote_threadtests (void);
8621 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
8624 threadset_test_cmd (char *cmd, int tty)
8626 int sample_thread = SAMPLE_THREAD;
8628 printf_filtered (_("Remote threadset test\n"));
8629 set_general_thread (sample_thread);
8634 threadalive_test (char *cmd, int tty)
8636 int sample_thread = SAMPLE_THREAD;
8637 int pid = ptid_get_pid (inferior_ptid);
8638 ptid_t ptid = ptid_build (pid, 0, sample_thread);
8640 if (remote_thread_alive (ptid))
8641 printf_filtered ("PASS: Thread alive test\n");
8643 printf_filtered ("FAIL: Thread alive test\n");
8646 void output_threadid (char *title, threadref *ref);
8649 output_threadid (char *title, threadref *ref)
8653 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
8655 printf_filtered ("%s %s\n", title, (&hexid[0]));
8659 threadlist_test_cmd (char *cmd, int tty)
8662 threadref nextthread;
8663 int done, result_count;
8664 threadref threadlist[3];
8666 printf_filtered ("Remote Threadlist test\n");
8667 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
8668 &result_count, &threadlist[0]))
8669 printf_filtered ("FAIL: threadlist test\n");
8672 threadref *scan = threadlist;
8673 threadref *limit = scan + result_count;
8675 while (scan < limit)
8676 output_threadid (" thread ", scan++);
8681 display_thread_info (struct gdb_ext_thread_info *info)
8683 output_threadid ("Threadid: ", &info->threadid);
8684 printf_filtered ("Name: %s\n ", info->shortname);
8685 printf_filtered ("State: %s\n", info->display);
8686 printf_filtered ("other: %s\n\n", info->more_display);
8690 get_and_display_threadinfo (threadref *ref)
8694 struct gdb_ext_thread_info threadinfo;
8696 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
8697 | TAG_MOREDISPLAY | TAG_DISPLAY;
8698 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
8699 display_thread_info (&threadinfo);
8704 threadinfo_test_cmd (char *cmd, int tty)
8706 int athread = SAMPLE_THREAD;
8710 int_to_threadref (&thread, athread);
8711 printf_filtered ("Remote Threadinfo test\n");
8712 if (!get_and_display_threadinfo (&thread))
8713 printf_filtered ("FAIL cannot get thread info\n");
8717 thread_display_step (threadref *ref, void *context)
8719 /* output_threadid(" threadstep ",ref); *//* simple test */
8720 return get_and_display_threadinfo (ref);
8724 threadlist_update_test_cmd (char *cmd, int tty)
8726 printf_filtered ("Remote Threadlist update test\n");
8727 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
8731 init_remote_threadtests (void)
8733 add_com ("tlist", class_obscure, threadlist_test_cmd,
8734 _("Fetch and print the remote list of "
8735 "thread identifiers, one pkt only"));
8736 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
8737 _("Fetch and display info about one thread"));
8738 add_com ("tset", class_obscure, threadset_test_cmd,
8739 _("Test setting to a different thread"));
8740 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
8741 _("Iterate through updating all remote thread info"));
8742 add_com ("talive", class_obscure, threadalive_test,
8743 _(" Remote thread alive test "));
8748 /* Convert a thread ID to a string. Returns the string in a static
8752 remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
8754 static char buf[64];
8755 struct remote_state *rs = get_remote_state ();
8757 if (ptid_is_pid (ptid))
8759 /* Printing an inferior target id. */
8761 /* When multi-process extensions are off, there's no way in the
8762 remote protocol to know the remote process id, if there's any
8763 at all. There's one exception --- when we're connected with
8764 target extended-remote, and we manually attached to a process
8765 with "attach PID". We don't record anywhere a flag that
8766 allows us to distinguish that case from the case of
8767 connecting with extended-remote and the stub already being
8768 attached to a process, and reporting yes to qAttached, hence
8769 no smart special casing here. */
8770 if (!remote_multi_process_p (rs))
8772 xsnprintf (buf, sizeof buf, "Remote target");
8776 return normal_pid_to_str (ptid);
8780 if (ptid_equal (magic_null_ptid, ptid))
8781 xsnprintf (buf, sizeof buf, "Thread <main>");
8782 else if (remote_multi_process_p (rs))
8783 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
8784 ptid_get_pid (ptid), ptid_get_tid (ptid));
8786 xsnprintf (buf, sizeof buf, "Thread %ld",
8787 ptid_get_tid (ptid));
8792 /* Get the address of the thread local variable in OBJFILE which is
8793 stored at OFFSET within the thread local storage for thread PTID. */
8796 remote_get_thread_local_address (struct target_ops *ops,
8797 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
8799 if (remote_protocol_packets[PACKET_qGetTLSAddr].support != PACKET_DISABLE)
8801 struct remote_state *rs = get_remote_state ();
8803 char *endp = rs->buf + get_remote_packet_size ();
8804 enum packet_result result;
8806 strcpy (p, "qGetTLSAddr:");
8808 p = write_ptid (p, endp, ptid);
8810 p += hexnumstr (p, offset);
8812 p += hexnumstr (p, lm);
8816 getpkt (&rs->buf, &rs->buf_size, 0);
8817 result = packet_ok (rs->buf,
8818 &remote_protocol_packets[PACKET_qGetTLSAddr]);
8819 if (result == PACKET_OK)
8823 unpack_varlen_hex (rs->buf, &result);
8826 else if (result == PACKET_UNKNOWN)
8827 throw_error (TLS_GENERIC_ERROR,
8828 _("Remote target doesn't support qGetTLSAddr packet"));
8830 throw_error (TLS_GENERIC_ERROR,
8831 _("Remote target failed to process qGetTLSAddr request"));
8834 throw_error (TLS_GENERIC_ERROR,
8835 _("TLS not supported or disabled on this target"));
8840 /* Provide thread local base, i.e. Thread Information Block address.
8841 Returns 1 if ptid is found and thread_local_base is non zero. */
8844 remote_get_tib_address (ptid_t ptid, CORE_ADDR *addr)
8846 if (remote_protocol_packets[PACKET_qGetTIBAddr].support != PACKET_DISABLE)
8848 struct remote_state *rs = get_remote_state ();
8850 char *endp = rs->buf + get_remote_packet_size ();
8851 enum packet_result result;
8853 strcpy (p, "qGetTIBAddr:");
8855 p = write_ptid (p, endp, ptid);
8859 getpkt (&rs->buf, &rs->buf_size, 0);
8860 result = packet_ok (rs->buf,
8861 &remote_protocol_packets[PACKET_qGetTIBAddr]);
8862 if (result == PACKET_OK)
8866 unpack_varlen_hex (rs->buf, &result);
8868 *addr = (CORE_ADDR) result;
8871 else if (result == PACKET_UNKNOWN)
8872 error (_("Remote target doesn't support qGetTIBAddr packet"));
8874 error (_("Remote target failed to process qGetTIBAddr request"));
8877 error (_("qGetTIBAddr not supported or disabled on this target"));
8882 /* Support for inferring a target description based on the current
8883 architecture and the size of a 'g' packet. While the 'g' packet
8884 can have any size (since optional registers can be left off the
8885 end), some sizes are easily recognizable given knowledge of the
8886 approximate architecture. */
8888 struct remote_g_packet_guess
8891 const struct target_desc *tdesc;
8893 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
8894 DEF_VEC_O(remote_g_packet_guess_s);
8896 struct remote_g_packet_data
8898 VEC(remote_g_packet_guess_s) *guesses;
8901 static struct gdbarch_data *remote_g_packet_data_handle;
8904 remote_g_packet_data_init (struct obstack *obstack)
8906 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
8910 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
8911 const struct target_desc *tdesc)
8913 struct remote_g_packet_data *data
8914 = gdbarch_data (gdbarch, remote_g_packet_data_handle);
8915 struct remote_g_packet_guess new_guess, *guess;
8918 gdb_assert (tdesc != NULL);
8921 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
8923 if (guess->bytes == bytes)
8924 internal_error (__FILE__, __LINE__,
8925 _("Duplicate g packet description added for size %d"),
8928 new_guess.bytes = bytes;
8929 new_guess.tdesc = tdesc;
8930 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
8933 /* Return 1 if remote_read_description would do anything on this target
8934 and architecture, 0 otherwise. */
8937 remote_read_description_p (struct target_ops *target)
8939 struct remote_g_packet_data *data
8940 = gdbarch_data (target_gdbarch, remote_g_packet_data_handle);
8942 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
8948 static const struct target_desc *
8949 remote_read_description (struct target_ops *target)
8951 struct remote_g_packet_data *data
8952 = gdbarch_data (target_gdbarch, remote_g_packet_data_handle);
8954 /* Do not try this during initial connection, when we do not know
8955 whether there is a running but stopped thread. */
8956 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
8959 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
8961 struct remote_g_packet_guess *guess;
8963 int bytes = send_g_packet ();
8966 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
8968 if (guess->bytes == bytes)
8969 return guess->tdesc;
8971 /* We discard the g packet. A minor optimization would be to
8972 hold on to it, and fill the register cache once we have selected
8973 an architecture, but it's too tricky to do safely. */
8979 /* Remote file transfer support. This is host-initiated I/O, not
8980 target-initiated; for target-initiated, see remote-fileio.c. */
8982 /* If *LEFT is at least the length of STRING, copy STRING to
8983 *BUFFER, update *BUFFER to point to the new end of the buffer, and
8984 decrease *LEFT. Otherwise raise an error. */
8987 remote_buffer_add_string (char **buffer, int *left, char *string)
8989 int len = strlen (string);
8992 error (_("Packet too long for target."));
8994 memcpy (*buffer, string, len);
8998 /* NUL-terminate the buffer as a convenience, if there is
9004 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
9005 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9006 decrease *LEFT. Otherwise raise an error. */
9009 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
9012 if (2 * len > *left)
9013 error (_("Packet too long for target."));
9015 bin2hex (bytes, *buffer, len);
9019 /* NUL-terminate the buffer as a convenience, if there is
9025 /* If *LEFT is large enough, convert VALUE to hex and add it to
9026 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9027 decrease *LEFT. Otherwise raise an error. */
9030 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
9032 int len = hexnumlen (value);
9035 error (_("Packet too long for target."));
9037 hexnumstr (*buffer, value);
9041 /* NUL-terminate the buffer as a convenience, if there is
9047 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
9048 value, *REMOTE_ERRNO to the remote error number or zero if none
9049 was included, and *ATTACHMENT to point to the start of the annex
9050 if any. The length of the packet isn't needed here; there may
9051 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
9053 Return 0 if the packet could be parsed, -1 if it could not. If
9054 -1 is returned, the other variables may not be initialized. */
9057 remote_hostio_parse_result (char *buffer, int *retcode,
9058 int *remote_errno, char **attachment)
9065 if (buffer[0] != 'F')
9069 *retcode = strtol (&buffer[1], &p, 16);
9070 if (errno != 0 || p == &buffer[1])
9073 /* Check for ",errno". */
9077 *remote_errno = strtol (p + 1, &p2, 16);
9078 if (errno != 0 || p + 1 == p2)
9083 /* Check for ";attachment". If there is no attachment, the
9084 packet should end here. */
9087 *attachment = p + 1;
9090 else if (*p == '\0')
9096 /* Send a prepared I/O packet to the target and read its response.
9097 The prepared packet is in the global RS->BUF before this function
9098 is called, and the answer is there when we return.
9100 COMMAND_BYTES is the length of the request to send, which may include
9101 binary data. WHICH_PACKET is the packet configuration to check
9102 before attempting a packet. If an error occurs, *REMOTE_ERRNO
9103 is set to the error number and -1 is returned. Otherwise the value
9104 returned by the function is returned.
9106 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
9107 attachment is expected; an error will be reported if there's a
9108 mismatch. If one is found, *ATTACHMENT will be set to point into
9109 the packet buffer and *ATTACHMENT_LEN will be set to the
9110 attachment's length. */
9113 remote_hostio_send_command (int command_bytes, int which_packet,
9114 int *remote_errno, char **attachment,
9115 int *attachment_len)
9117 struct remote_state *rs = get_remote_state ();
9118 int ret, bytes_read;
9119 char *attachment_tmp;
9122 || remote_protocol_packets[which_packet].support == PACKET_DISABLE)
9124 *remote_errno = FILEIO_ENOSYS;
9128 putpkt_binary (rs->buf, command_bytes);
9129 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
9131 /* If it timed out, something is wrong. Don't try to parse the
9135 *remote_errno = FILEIO_EINVAL;
9139 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
9142 *remote_errno = FILEIO_EINVAL;
9144 case PACKET_UNKNOWN:
9145 *remote_errno = FILEIO_ENOSYS;
9151 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
9154 *remote_errno = FILEIO_EINVAL;
9158 /* Make sure we saw an attachment if and only if we expected one. */
9159 if ((attachment_tmp == NULL && attachment != NULL)
9160 || (attachment_tmp != NULL && attachment == NULL))
9162 *remote_errno = FILEIO_EINVAL;
9166 /* If an attachment was found, it must point into the packet buffer;
9167 work out how many bytes there were. */
9168 if (attachment_tmp != NULL)
9170 *attachment = attachment_tmp;
9171 *attachment_len = bytes_read - (*attachment - rs->buf);
9177 /* Open FILENAME on the remote target, using FLAGS and MODE. Return a
9178 remote file descriptor, or -1 if an error occurs (and set
9182 remote_hostio_open (const char *filename, int flags, int mode,
9185 struct remote_state *rs = get_remote_state ();
9187 int left = get_remote_packet_size () - 1;
9189 remote_buffer_add_string (&p, &left, "vFile:open:");
9191 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
9193 remote_buffer_add_string (&p, &left, ",");
9195 remote_buffer_add_int (&p, &left, flags);
9196 remote_buffer_add_string (&p, &left, ",");
9198 remote_buffer_add_int (&p, &left, mode);
9200 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
9201 remote_errno, NULL, NULL);
9204 /* Write up to LEN bytes from WRITE_BUF to FD on the remote target.
9205 Return the number of bytes written, or -1 if an error occurs (and
9206 set *REMOTE_ERRNO). */
9209 remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
9210 ULONGEST offset, int *remote_errno)
9212 struct remote_state *rs = get_remote_state ();
9214 int left = get_remote_packet_size ();
9217 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
9219 remote_buffer_add_int (&p, &left, fd);
9220 remote_buffer_add_string (&p, &left, ",");
9222 remote_buffer_add_int (&p, &left, offset);
9223 remote_buffer_add_string (&p, &left, ",");
9225 p += remote_escape_output (write_buf, len, p, &out_len,
9226 get_remote_packet_size () - (p - rs->buf));
9228 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
9229 remote_errno, NULL, NULL);
9232 /* Read up to LEN bytes FD on the remote target into READ_BUF
9233 Return the number of bytes read, or -1 if an error occurs (and
9234 set *REMOTE_ERRNO). */
9237 remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
9238 ULONGEST offset, int *remote_errno)
9240 struct remote_state *rs = get_remote_state ();
9243 int left = get_remote_packet_size ();
9244 int ret, attachment_len;
9247 remote_buffer_add_string (&p, &left, "vFile:pread:");
9249 remote_buffer_add_int (&p, &left, fd);
9250 remote_buffer_add_string (&p, &left, ",");
9252 remote_buffer_add_int (&p, &left, len);
9253 remote_buffer_add_string (&p, &left, ",");
9255 remote_buffer_add_int (&p, &left, offset);
9257 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
9258 remote_errno, &attachment,
9264 read_len = remote_unescape_input (attachment, attachment_len,
9266 if (read_len != ret)
9267 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
9272 /* Close FD on the remote target. Return 0, or -1 if an error occurs
9273 (and set *REMOTE_ERRNO). */
9276 remote_hostio_close (int fd, int *remote_errno)
9278 struct remote_state *rs = get_remote_state ();
9280 int left = get_remote_packet_size () - 1;
9282 remote_buffer_add_string (&p, &left, "vFile:close:");
9284 remote_buffer_add_int (&p, &left, fd);
9286 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
9287 remote_errno, NULL, NULL);
9290 /* Unlink FILENAME on the remote target. Return 0, or -1 if an error
9291 occurs (and set *REMOTE_ERRNO). */
9294 remote_hostio_unlink (const char *filename, int *remote_errno)
9296 struct remote_state *rs = get_remote_state ();
9298 int left = get_remote_packet_size () - 1;
9300 remote_buffer_add_string (&p, &left, "vFile:unlink:");
9302 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
9305 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
9306 remote_errno, NULL, NULL);
9310 remote_fileio_errno_to_host (int errnum)
9334 case FILEIO_ENOTDIR:
9354 case FILEIO_ENAMETOOLONG:
9355 return ENAMETOOLONG;
9361 remote_hostio_error (int errnum)
9363 int host_error = remote_fileio_errno_to_host (errnum);
9365 if (host_error == -1)
9366 error (_("Unknown remote I/O error %d"), errnum);
9368 error (_("Remote I/O error: %s"), safe_strerror (host_error));
9372 remote_hostio_close_cleanup (void *opaque)
9374 int fd = *(int *) opaque;
9377 remote_hostio_close (fd, &remote_errno);
9382 remote_bfd_iovec_open (struct bfd *abfd, void *open_closure)
9384 const char *filename = bfd_get_filename (abfd);
9385 int fd, remote_errno;
9388 gdb_assert (remote_filename_p (filename));
9390 fd = remote_hostio_open (filename + 7, FILEIO_O_RDONLY, 0, &remote_errno);
9393 errno = remote_fileio_errno_to_host (remote_errno);
9394 bfd_set_error (bfd_error_system_call);
9398 stream = xmalloc (sizeof (int));
9404 remote_bfd_iovec_close (struct bfd *abfd, void *stream)
9406 int fd = *(int *)stream;
9411 /* Ignore errors on close; these may happen if the remote
9412 connection was already torn down. */
9413 remote_hostio_close (fd, &remote_errno);
9419 remote_bfd_iovec_pread (struct bfd *abfd, void *stream, void *buf,
9420 file_ptr nbytes, file_ptr offset)
9422 int fd = *(int *)stream;
9424 file_ptr pos, bytes;
9427 while (nbytes > pos)
9429 bytes = remote_hostio_pread (fd, (char *)buf + pos, nbytes - pos,
9430 offset + pos, &remote_errno);
9432 /* Success, but no bytes, means end-of-file. */
9436 errno = remote_fileio_errno_to_host (remote_errno);
9437 bfd_set_error (bfd_error_system_call);
9448 remote_bfd_iovec_stat (struct bfd *abfd, void *stream, struct stat *sb)
9450 /* FIXME: We should probably implement remote_hostio_stat. */
9451 sb->st_size = INT_MAX;
9456 remote_filename_p (const char *filename)
9458 return strncmp (filename, "remote:", 7) == 0;
9462 remote_bfd_open (const char *remote_file, const char *target)
9464 return bfd_openr_iovec (remote_file, target,
9465 remote_bfd_iovec_open, NULL,
9466 remote_bfd_iovec_pread,
9467 remote_bfd_iovec_close,
9468 remote_bfd_iovec_stat);
9472 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
9474 struct cleanup *back_to, *close_cleanup;
9475 int retcode, fd, remote_errno, bytes, io_size;
9478 int bytes_in_buffer;
9483 error (_("command can only be used with remote target"));
9485 file = fopen (local_file, "rb");
9487 perror_with_name (local_file);
9488 back_to = make_cleanup_fclose (file);
9490 fd = remote_hostio_open (remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
9492 0700, &remote_errno);
9494 remote_hostio_error (remote_errno);
9496 /* Send up to this many bytes at once. They won't all fit in the
9497 remote packet limit, so we'll transfer slightly fewer. */
9498 io_size = get_remote_packet_size ();
9499 buffer = xmalloc (io_size);
9500 make_cleanup (xfree, buffer);
9502 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
9504 bytes_in_buffer = 0;
9507 while (bytes_in_buffer || !saw_eof)
9511 bytes = fread (buffer + bytes_in_buffer, 1,
9512 io_size - bytes_in_buffer,
9517 error (_("Error reading %s."), local_file);
9520 /* EOF. Unless there is something still in the
9521 buffer from the last iteration, we are done. */
9523 if (bytes_in_buffer == 0)
9531 bytes += bytes_in_buffer;
9532 bytes_in_buffer = 0;
9534 retcode = remote_hostio_pwrite (fd, buffer, bytes,
9535 offset, &remote_errno);
9538 remote_hostio_error (remote_errno);
9539 else if (retcode == 0)
9540 error (_("Remote write of %d bytes returned 0!"), bytes);
9541 else if (retcode < bytes)
9543 /* Short write. Save the rest of the read data for the next
9545 bytes_in_buffer = bytes - retcode;
9546 memmove (buffer, buffer + retcode, bytes_in_buffer);
9552 discard_cleanups (close_cleanup);
9553 if (remote_hostio_close (fd, &remote_errno))
9554 remote_hostio_error (remote_errno);
9557 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
9558 do_cleanups (back_to);
9562 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
9564 struct cleanup *back_to, *close_cleanup;
9565 int fd, remote_errno, bytes, io_size;
9571 error (_("command can only be used with remote target"));
9573 fd = remote_hostio_open (remote_file, FILEIO_O_RDONLY, 0, &remote_errno);
9575 remote_hostio_error (remote_errno);
9577 file = fopen (local_file, "wb");
9579 perror_with_name (local_file);
9580 back_to = make_cleanup_fclose (file);
9582 /* Send up to this many bytes at once. They won't all fit in the
9583 remote packet limit, so we'll transfer slightly fewer. */
9584 io_size = get_remote_packet_size ();
9585 buffer = xmalloc (io_size);
9586 make_cleanup (xfree, buffer);
9588 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
9593 bytes = remote_hostio_pread (fd, buffer, io_size, offset, &remote_errno);
9595 /* Success, but no bytes, means end-of-file. */
9598 remote_hostio_error (remote_errno);
9602 bytes = fwrite (buffer, 1, bytes, file);
9604 perror_with_name (local_file);
9607 discard_cleanups (close_cleanup);
9608 if (remote_hostio_close (fd, &remote_errno))
9609 remote_hostio_error (remote_errno);
9612 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
9613 do_cleanups (back_to);
9617 remote_file_delete (const char *remote_file, int from_tty)
9619 int retcode, remote_errno;
9622 error (_("command can only be used with remote target"));
9624 retcode = remote_hostio_unlink (remote_file, &remote_errno);
9626 remote_hostio_error (remote_errno);
9629 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
9633 remote_put_command (char *args, int from_tty)
9635 struct cleanup *back_to;
9639 error_no_arg (_("file to put"));
9641 argv = gdb_buildargv (args);
9642 back_to = make_cleanup_freeargv (argv);
9643 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
9644 error (_("Invalid parameters to remote put"));
9646 remote_file_put (argv[0], argv[1], from_tty);
9648 do_cleanups (back_to);
9652 remote_get_command (char *args, int from_tty)
9654 struct cleanup *back_to;
9658 error_no_arg (_("file to get"));
9660 argv = gdb_buildargv (args);
9661 back_to = make_cleanup_freeargv (argv);
9662 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
9663 error (_("Invalid parameters to remote get"));
9665 remote_file_get (argv[0], argv[1], from_tty);
9667 do_cleanups (back_to);
9671 remote_delete_command (char *args, int from_tty)
9673 struct cleanup *back_to;
9677 error_no_arg (_("file to delete"));
9679 argv = gdb_buildargv (args);
9680 back_to = make_cleanup_freeargv (argv);
9681 if (argv[0] == NULL || argv[1] != NULL)
9682 error (_("Invalid parameters to remote delete"));
9684 remote_file_delete (argv[0], from_tty);
9686 do_cleanups (back_to);
9690 remote_command (char *args, int from_tty)
9692 help_list (remote_cmdlist, "remote ", -1, gdb_stdout);
9696 remote_can_execute_reverse (void)
9698 if (remote_protocol_packets[PACKET_bs].support == PACKET_ENABLE
9699 || remote_protocol_packets[PACKET_bc].support == PACKET_ENABLE)
9706 remote_supports_non_stop (void)
9712 remote_supports_disable_randomization (void)
9714 /* Only supported in extended mode. */
9719 remote_supports_multi_process (void)
9721 struct remote_state *rs = get_remote_state ();
9723 return remote_multi_process_p (rs);
9727 remote_supports_cond_tracepoints (void)
9729 struct remote_state *rs = get_remote_state ();
9731 return rs->cond_tracepoints;
9735 remote_supports_fast_tracepoints (void)
9737 struct remote_state *rs = get_remote_state ();
9739 return rs->fast_tracepoints;
9743 remote_supports_static_tracepoints (void)
9745 struct remote_state *rs = get_remote_state ();
9747 return rs->static_tracepoints;
9751 remote_supports_enable_disable_tracepoint (void)
9753 struct remote_state *rs = get_remote_state ();
9755 return rs->enable_disable_tracepoints;
9759 remote_supports_string_tracing (void)
9761 struct remote_state *rs = get_remote_state ();
9763 return rs->string_tracing;
9767 remote_trace_init (void)
9770 remote_get_noisy_reply (&target_buf, &target_buf_size);
9771 if (strcmp (target_buf, "OK") != 0)
9772 error (_("Target does not support this command."));
9775 static void free_actions_list (char **actions_list);
9776 static void free_actions_list_cleanup_wrapper (void *);
9778 free_actions_list_cleanup_wrapper (void *al)
9780 free_actions_list (al);
9784 free_actions_list (char **actions_list)
9788 if (actions_list == 0)
9791 for (ndx = 0; actions_list[ndx]; ndx++)
9792 xfree (actions_list[ndx]);
9794 xfree (actions_list);
9797 /* Recursive routine to walk through command list including loops, and
9798 download packets for each command. */
9801 remote_download_command_source (int num, ULONGEST addr,
9802 struct command_line *cmds)
9804 struct remote_state *rs = get_remote_state ();
9805 struct command_line *cmd;
9807 for (cmd = cmds; cmd; cmd = cmd->next)
9809 QUIT; /* Allow user to bail out with ^C. */
9810 strcpy (rs->buf, "QTDPsrc:");
9811 encode_source_string (num, addr, "cmd", cmd->line,
9812 rs->buf + strlen (rs->buf),
9813 rs->buf_size - strlen (rs->buf));
9815 remote_get_noisy_reply (&target_buf, &target_buf_size);
9816 if (strcmp (target_buf, "OK"))
9817 warning (_("Target does not support source download."));
9819 if (cmd->control_type == while_control
9820 || cmd->control_type == while_stepping_control)
9822 remote_download_command_source (num, addr, *cmd->body_list);
9824 QUIT; /* Allow user to bail out with ^C. */
9825 strcpy (rs->buf, "QTDPsrc:");
9826 encode_source_string (num, addr, "cmd", "end",
9827 rs->buf + strlen (rs->buf),
9828 rs->buf_size - strlen (rs->buf));
9830 remote_get_noisy_reply (&target_buf, &target_buf_size);
9831 if (strcmp (target_buf, "OK"))
9832 warning (_("Target does not support source download."));
9838 remote_download_tracepoint (struct breakpoint *b)
9840 struct bp_location *loc;
9845 char **stepping_actions;
9847 struct cleanup *old_chain = NULL;
9848 struct agent_expr *aexpr;
9849 struct cleanup *aexpr_chain = NULL;
9851 struct tracepoint *t = (struct tracepoint *) b;
9853 /* Iterate over all the tracepoint locations. It's up to the target to
9854 notice multiple tracepoint packets with the same number but different
9855 addresses, and treat them as multiple locations. */
9856 for (loc = b->loc; loc; loc = loc->next)
9858 encode_actions (b, loc, &tdp_actions, &stepping_actions);
9859 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
9861 (void) make_cleanup (free_actions_list_cleanup_wrapper,
9864 tpaddr = loc->address;
9865 sprintf_vma (addrbuf, tpaddr);
9866 sprintf (buf, "QTDP:%x:%s:%c:%lx:%x", b->number,
9867 addrbuf, /* address */
9868 (b->enable_state == bp_enabled ? 'E' : 'D'),
9869 t->step_count, t->pass_count);
9870 /* Fast tracepoints are mostly handled by the target, but we can
9871 tell the target how big of an instruction block should be moved
9873 if (b->type == bp_fast_tracepoint)
9875 /* Only test for support at download time; we may not know
9876 target capabilities at definition time. */
9877 if (remote_supports_fast_tracepoints ())
9881 if (gdbarch_fast_tracepoint_valid_at (target_gdbarch,
9882 tpaddr, &isize, NULL))
9883 sprintf (buf + strlen (buf), ":F%x", isize);
9885 /* If it passed validation at definition but fails now,
9886 something is very wrong. */
9887 internal_error (__FILE__, __LINE__,
9888 _("Fast tracepoint not "
9889 "valid during download"));
9892 /* Fast tracepoints are functionally identical to regular
9893 tracepoints, so don't take lack of support as a reason to
9894 give up on the trace run. */
9895 warning (_("Target does not support fast tracepoints, "
9896 "downloading %d as regular tracepoint"), b->number);
9898 else if (b->type == bp_static_tracepoint)
9900 /* Only test for support at download time; we may not know
9901 target capabilities at definition time. */
9902 if (remote_supports_static_tracepoints ())
9904 struct static_tracepoint_marker marker;
9906 if (target_static_tracepoint_marker_at (tpaddr, &marker))
9909 error (_("Static tracepoint not valid during download"));
9912 /* Fast tracepoints are functionally identical to regular
9913 tracepoints, so don't take lack of support as a reason
9914 to give up on the trace run. */
9915 error (_("Target does not support static tracepoints"));
9917 /* If the tracepoint has a conditional, make it into an agent
9918 expression and append to the definition. */
9921 /* Only test support at download time, we may not know target
9922 capabilities at definition time. */
9923 if (remote_supports_cond_tracepoints ())
9925 aexpr = gen_eval_for_expr (tpaddr, loc->cond);
9926 aexpr_chain = make_cleanup_free_agent_expr (aexpr);
9927 sprintf (buf + strlen (buf), ":X%x,", aexpr->len);
9928 pkt = buf + strlen (buf);
9929 for (ndx = 0; ndx < aexpr->len; ++ndx)
9930 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
9932 do_cleanups (aexpr_chain);
9935 warning (_("Target does not support conditional tracepoints, "
9936 "ignoring tp %d cond"), b->number);
9939 if (b->commands || *default_collect)
9942 remote_get_noisy_reply (&target_buf, &target_buf_size);
9943 if (strcmp (target_buf, "OK"))
9944 error (_("Target does not support tracepoints."));
9946 /* do_single_steps (t); */
9949 for (ndx = 0; tdp_actions[ndx]; ndx++)
9951 QUIT; /* Allow user to bail out with ^C. */
9952 sprintf (buf, "QTDP:-%x:%s:%s%c",
9953 b->number, addrbuf, /* address */
9955 ((tdp_actions[ndx + 1] || stepping_actions)
9958 remote_get_noisy_reply (&target_buf,
9960 if (strcmp (target_buf, "OK"))
9961 error (_("Error on target while setting tracepoints."));
9964 if (stepping_actions)
9966 for (ndx = 0; stepping_actions[ndx]; ndx++)
9968 QUIT; /* Allow user to bail out with ^C. */
9969 sprintf (buf, "QTDP:-%x:%s:%s%s%s",
9970 b->number, addrbuf, /* address */
9971 ((ndx == 0) ? "S" : ""),
9972 stepping_actions[ndx],
9973 (stepping_actions[ndx + 1] ? "-" : ""));
9975 remote_get_noisy_reply (&target_buf,
9977 if (strcmp (target_buf, "OK"))
9978 error (_("Error on target while setting tracepoints."));
9982 if (remote_protocol_packets[PACKET_TracepointSource].support
9987 strcpy (buf, "QTDPsrc:");
9988 encode_source_string (b->number, loc->address,
9989 "at", b->addr_string, buf + strlen (buf),
9990 2048 - strlen (buf));
9993 remote_get_noisy_reply (&target_buf, &target_buf_size);
9994 if (strcmp (target_buf, "OK"))
9995 warning (_("Target does not support source download."));
9999 strcpy (buf, "QTDPsrc:");
10000 encode_source_string (b->number, loc->address,
10001 "cond", b->cond_string, buf + strlen (buf),
10002 2048 - strlen (buf));
10004 remote_get_noisy_reply (&target_buf, &target_buf_size);
10005 if (strcmp (target_buf, "OK"))
10006 warning (_("Target does not support source download."));
10008 remote_download_command_source (b->number, loc->address,
10009 breakpoint_commands (b));
10012 do_cleanups (old_chain);
10017 remote_download_trace_state_variable (struct trace_state_variable *tsv)
10019 struct remote_state *rs = get_remote_state ();
10022 sprintf (rs->buf, "QTDV:%x:%s:%x:",
10023 tsv->number, phex ((ULONGEST) tsv->initial_value, 8), tsv->builtin);
10024 p = rs->buf + strlen (rs->buf);
10025 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
10026 error (_("Trace state variable name too long for tsv definition packet"));
10027 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, 0);
10030 remote_get_noisy_reply (&target_buf, &target_buf_size);
10031 if (*target_buf == '\0')
10032 error (_("Target does not support this command."));
10033 if (strcmp (target_buf, "OK") != 0)
10034 error (_("Error on target while downloading trace state variable."));
10038 remote_enable_tracepoint (struct bp_location *location)
10040 struct remote_state *rs = get_remote_state ();
10043 sprintf_vma (addr_buf, location->address);
10044 sprintf (rs->buf, "QTEnable:%x:%s", location->owner->number, addr_buf);
10046 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
10047 if (*rs->buf == '\0')
10048 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
10049 if (strcmp (rs->buf, "OK") != 0)
10050 error (_("Error on target while enabling tracepoint."));
10054 remote_disable_tracepoint (struct bp_location *location)
10056 struct remote_state *rs = get_remote_state ();
10059 sprintf_vma (addr_buf, location->address);
10060 sprintf (rs->buf, "QTDisable:%x:%s", location->owner->number, addr_buf);
10062 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
10063 if (*rs->buf == '\0')
10064 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
10065 if (strcmp (rs->buf, "OK") != 0)
10066 error (_("Error on target while disabling tracepoint."));
10070 remote_trace_set_readonly_regions (void)
10073 bfd_size_type size;
10079 return; /* No information to give. */
10081 strcpy (target_buf, "QTro");
10082 for (s = exec_bfd->sections; s; s = s->next)
10084 char tmp1[40], tmp2[40];
10087 if ((s->flags & SEC_LOAD) == 0 ||
10088 /* (s->flags & SEC_CODE) == 0 || */
10089 (s->flags & SEC_READONLY) == 0)
10093 vma = bfd_get_section_vma (,s);
10094 size = bfd_get_section_size (s);
10095 sprintf_vma (tmp1, vma);
10096 sprintf_vma (tmp2, vma + size);
10097 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
10098 if (offset + sec_length + 1 > target_buf_size)
10100 if (remote_protocol_packets[PACKET_qXfer_traceframe_info].support
10103 Too many sections for read-only sections definition packet."));
10106 sprintf (target_buf + offset, ":%s,%s", tmp1, tmp2);
10107 offset += sec_length;
10111 putpkt (target_buf);
10112 getpkt (&target_buf, &target_buf_size, 0);
10117 remote_trace_start (void)
10119 putpkt ("QTStart");
10120 remote_get_noisy_reply (&target_buf, &target_buf_size);
10121 if (*target_buf == '\0')
10122 error (_("Target does not support this command."));
10123 if (strcmp (target_buf, "OK") != 0)
10124 error (_("Bogus reply from target: %s"), target_buf);
10128 remote_get_trace_status (struct trace_status *ts)
10130 /* Initialize it just to avoid a GCC false warning. */
10132 /* FIXME we need to get register block size some other way. */
10133 extern int trace_regblock_size;
10134 volatile struct gdb_exception ex;
10136 trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
10138 putpkt ("qTStatus");
10140 TRY_CATCH (ex, RETURN_MASK_ERROR)
10142 p = remote_get_noisy_reply (&target_buf, &target_buf_size);
10146 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
10150 /* If the remote target doesn't do tracing, flag it. */
10154 /* We're working with a live target. */
10157 /* Set some defaults. */
10158 ts->running_known = 0;
10159 ts->stop_reason = trace_stop_reason_unknown;
10160 ts->traceframe_count = -1;
10161 ts->buffer_free = 0;
10164 error (_("Bogus trace status reply from target: %s"), target_buf);
10166 parse_trace_status (p, ts);
10168 return ts->running;
10172 remote_trace_stop (void)
10175 remote_get_noisy_reply (&target_buf, &target_buf_size);
10176 if (*target_buf == '\0')
10177 error (_("Target does not support this command."));
10178 if (strcmp (target_buf, "OK") != 0)
10179 error (_("Bogus reply from target: %s"), target_buf);
10183 remote_trace_find (enum trace_find_type type, int num,
10184 ULONGEST addr1, ULONGEST addr2,
10187 struct remote_state *rs = get_remote_state ();
10189 int target_frameno = -1, target_tracept = -1;
10191 /* Lookups other than by absolute frame number depend on the current
10192 trace selected, so make sure it is correct on the remote end
10194 if (type != tfind_number)
10195 set_remote_traceframe ();
10198 strcpy (p, "QTFrame:");
10199 p = strchr (p, '\0');
10203 sprintf (p, "%x", num);
10206 sprintf (p, "pc:%s", phex_nz (addr1, 0));
10209 sprintf (p, "tdp:%x", num);
10212 sprintf (p, "range:%s:%s", phex_nz (addr1, 0), phex_nz (addr2, 0));
10214 case tfind_outside:
10215 sprintf (p, "outside:%s:%s", phex_nz (addr1, 0), phex_nz (addr2, 0));
10218 error (_("Unknown trace find type %d"), type);
10222 reply = remote_get_noisy_reply (&(rs->buf), &sizeof_pkt);
10223 if (*reply == '\0')
10224 error (_("Target does not support this command."));
10226 while (reply && *reply)
10231 target_frameno = (int) strtol (p, &reply, 16);
10233 error (_("Unable to parse trace frame number"));
10234 /* Don't update our remote traceframe number cache on failure
10235 to select a remote traceframe. */
10236 if (target_frameno == -1)
10241 target_tracept = (int) strtol (p, &reply, 16);
10243 error (_("Unable to parse tracepoint number"));
10245 case 'O': /* "OK"? */
10246 if (reply[1] == 'K' && reply[2] == '\0')
10249 error (_("Bogus reply from target: %s"), reply);
10252 error (_("Bogus reply from target: %s"), reply);
10255 *tpp = target_tracept;
10257 remote_traceframe_number = target_frameno;
10258 return target_frameno;
10262 remote_get_trace_state_variable_value (int tsvnum, LONGEST *val)
10264 struct remote_state *rs = get_remote_state ();
10268 set_remote_traceframe ();
10270 sprintf (rs->buf, "qTV:%x", tsvnum);
10272 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10273 if (reply && *reply)
10277 unpack_varlen_hex (reply + 1, &uval);
10278 *val = (LONGEST) uval;
10286 remote_save_trace_data (const char *filename)
10288 struct remote_state *rs = get_remote_state ();
10292 strcpy (p, "QTSave:");
10294 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
10295 error (_("Remote file name too long for trace save packet"));
10296 p += 2 * bin2hex ((gdb_byte *) filename, p, 0);
10299 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10300 if (*reply == '\0')
10301 error (_("Target does not support this command."));
10302 if (strcmp (reply, "OK") != 0)
10303 error (_("Bogus reply from target: %s"), reply);
10307 /* This is basically a memory transfer, but needs to be its own packet
10308 because we don't know how the target actually organizes its trace
10309 memory, plus we want to be able to ask for as much as possible, but
10310 not be unhappy if we don't get as much as we ask for. */
10313 remote_get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
10315 struct remote_state *rs = get_remote_state ();
10321 strcpy (p, "qTBuffer:");
10323 p += hexnumstr (p, offset);
10325 p += hexnumstr (p, len);
10329 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10330 if (reply && *reply)
10332 /* 'l' by itself means we're at the end of the buffer and
10333 there is nothing more to get. */
10337 /* Convert the reply into binary. Limit the number of bytes to
10338 convert according to our passed-in buffer size, rather than
10339 what was returned in the packet; if the target is
10340 unexpectedly generous and gives us a bigger reply than we
10341 asked for, we don't want to crash. */
10342 rslt = hex2bin (target_buf, buf, len);
10346 /* Something went wrong, flag as an error. */
10351 remote_set_disconnected_tracing (int val)
10353 struct remote_state *rs = get_remote_state ();
10355 if (rs->disconnected_tracing)
10359 sprintf (rs->buf, "QTDisconnected:%x", val);
10361 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10362 if (*reply == '\0')
10363 error (_("Target does not support this command."));
10364 if (strcmp (reply, "OK") != 0)
10365 error (_("Bogus reply from target: %s"), reply);
10368 warning (_("Target does not support disconnected tracing."));
10372 remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
10374 struct thread_info *info = find_thread_ptid (ptid);
10376 if (info && info->private)
10377 return info->private->core;
10382 remote_set_circular_trace_buffer (int val)
10384 struct remote_state *rs = get_remote_state ();
10387 sprintf (rs->buf, "QTBuffer:circular:%x", val);
10389 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10390 if (*reply == '\0')
10391 error (_("Target does not support this command."));
10392 if (strcmp (reply, "OK") != 0)
10393 error (_("Bogus reply from target: %s"), reply);
10396 static struct traceframe_info *
10397 remote_traceframe_info (void)
10401 text = target_read_stralloc (¤t_target,
10402 TARGET_OBJECT_TRACEFRAME_INFO, NULL);
10405 struct traceframe_info *info;
10406 struct cleanup *back_to = make_cleanup (xfree, text);
10408 info = parse_traceframe_info (text);
10409 do_cleanups (back_to);
10417 init_remote_ops (void)
10419 remote_ops.to_shortname = "remote";
10420 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
10421 remote_ops.to_doc =
10422 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
10423 Specify the serial device it is connected to\n\
10424 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
10425 remote_ops.to_open = remote_open;
10426 remote_ops.to_close = remote_close;
10427 remote_ops.to_detach = remote_detach;
10428 remote_ops.to_disconnect = remote_disconnect;
10429 remote_ops.to_resume = remote_resume;
10430 remote_ops.to_wait = remote_wait;
10431 remote_ops.to_fetch_registers = remote_fetch_registers;
10432 remote_ops.to_store_registers = remote_store_registers;
10433 remote_ops.to_prepare_to_store = remote_prepare_to_store;
10434 remote_ops.deprecated_xfer_memory = remote_xfer_memory;
10435 remote_ops.to_files_info = remote_files_info;
10436 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
10437 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
10438 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
10439 remote_ops.to_stopped_data_address = remote_stopped_data_address;
10440 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
10441 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
10442 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
10443 remote_ops.to_region_ok_for_hw_watchpoint
10444 = remote_region_ok_for_hw_watchpoint;
10445 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
10446 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
10447 remote_ops.to_kill = remote_kill;
10448 remote_ops.to_load = generic_load;
10449 remote_ops.to_mourn_inferior = remote_mourn;
10450 remote_ops.to_pass_signals = remote_pass_signals;
10451 remote_ops.to_thread_alive = remote_thread_alive;
10452 remote_ops.to_find_new_threads = remote_threads_info;
10453 remote_ops.to_pid_to_str = remote_pid_to_str;
10454 remote_ops.to_extra_thread_info = remote_threads_extra_info;
10455 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
10456 remote_ops.to_stop = remote_stop;
10457 remote_ops.to_xfer_partial = remote_xfer_partial;
10458 remote_ops.to_rcmd = remote_rcmd;
10459 remote_ops.to_log_command = serial_log_command;
10460 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
10461 remote_ops.to_stratum = process_stratum;
10462 remote_ops.to_has_all_memory = default_child_has_all_memory;
10463 remote_ops.to_has_memory = default_child_has_memory;
10464 remote_ops.to_has_stack = default_child_has_stack;
10465 remote_ops.to_has_registers = default_child_has_registers;
10466 remote_ops.to_has_execution = default_child_has_execution;
10467 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
10468 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
10469 remote_ops.to_magic = OPS_MAGIC;
10470 remote_ops.to_memory_map = remote_memory_map;
10471 remote_ops.to_flash_erase = remote_flash_erase;
10472 remote_ops.to_flash_done = remote_flash_done;
10473 remote_ops.to_read_description = remote_read_description;
10474 remote_ops.to_search_memory = remote_search_memory;
10475 remote_ops.to_can_async_p = remote_can_async_p;
10476 remote_ops.to_is_async_p = remote_is_async_p;
10477 remote_ops.to_async = remote_async;
10478 remote_ops.to_terminal_inferior = remote_terminal_inferior;
10479 remote_ops.to_terminal_ours = remote_terminal_ours;
10480 remote_ops.to_supports_non_stop = remote_supports_non_stop;
10481 remote_ops.to_supports_multi_process = remote_supports_multi_process;
10482 remote_ops.to_supports_disable_randomization
10483 = remote_supports_disable_randomization;
10484 remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
10485 remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
10486 remote_ops.to_trace_init = remote_trace_init;
10487 remote_ops.to_download_tracepoint = remote_download_tracepoint;
10488 remote_ops.to_download_trace_state_variable
10489 = remote_download_trace_state_variable;
10490 remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
10491 remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
10492 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
10493 remote_ops.to_trace_start = remote_trace_start;
10494 remote_ops.to_get_trace_status = remote_get_trace_status;
10495 remote_ops.to_trace_stop = remote_trace_stop;
10496 remote_ops.to_trace_find = remote_trace_find;
10497 remote_ops.to_get_trace_state_variable_value
10498 = remote_get_trace_state_variable_value;
10499 remote_ops.to_save_trace_data = remote_save_trace_data;
10500 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
10501 remote_ops.to_upload_trace_state_variables
10502 = remote_upload_trace_state_variables;
10503 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
10504 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
10505 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
10506 remote_ops.to_core_of_thread = remote_core_of_thread;
10507 remote_ops.to_verify_memory = remote_verify_memory;
10508 remote_ops.to_get_tib_address = remote_get_tib_address;
10509 remote_ops.to_set_permissions = remote_set_permissions;
10510 remote_ops.to_static_tracepoint_marker_at
10511 = remote_static_tracepoint_marker_at;
10512 remote_ops.to_static_tracepoint_markers_by_strid
10513 = remote_static_tracepoint_markers_by_strid;
10514 remote_ops.to_traceframe_info = remote_traceframe_info;
10517 /* Set up the extended remote vector by making a copy of the standard
10518 remote vector and adding to it. */
10521 init_extended_remote_ops (void)
10523 extended_remote_ops = remote_ops;
10525 extended_remote_ops.to_shortname = "extended-remote";
10526 extended_remote_ops.to_longname =
10527 "Extended remote serial target in gdb-specific protocol";
10528 extended_remote_ops.to_doc =
10529 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
10530 Specify the serial device it is connected to (e.g. /dev/ttya).";
10531 extended_remote_ops.to_open = extended_remote_open;
10532 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
10533 extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
10534 extended_remote_ops.to_detach = extended_remote_detach;
10535 extended_remote_ops.to_attach = extended_remote_attach;
10536 extended_remote_ops.to_kill = extended_remote_kill;
10537 extended_remote_ops.to_supports_disable_randomization
10538 = extended_remote_supports_disable_randomization;
10542 remote_can_async_p (void)
10544 if (!target_async_permitted)
10545 /* We only enable async when the user specifically asks for it. */
10548 /* We're async whenever the serial device is. */
10549 return serial_can_async_p (remote_desc);
10553 remote_is_async_p (void)
10555 if (!target_async_permitted)
10556 /* We only enable async when the user specifically asks for it. */
10559 /* We're async whenever the serial device is. */
10560 return serial_is_async_p (remote_desc);
10563 /* Pass the SERIAL event on and up to the client. One day this code
10564 will be able to delay notifying the client of an event until the
10565 point where an entire packet has been received. */
10567 static void (*async_client_callback) (enum inferior_event_type event_type,
10569 static void *async_client_context;
10570 static serial_event_ftype remote_async_serial_handler;
10573 remote_async_serial_handler (struct serial *scb, void *context)
10575 /* Don't propogate error information up to the client. Instead let
10576 the client find out about the error by querying the target. */
10577 async_client_callback (INF_REG_EVENT, async_client_context);
10581 remote_async_inferior_event_handler (gdb_client_data data)
10583 inferior_event_handler (INF_REG_EVENT, NULL);
10587 remote_async_get_pending_events_handler (gdb_client_data data)
10589 remote_get_pending_stop_replies ();
10593 remote_async (void (*callback) (enum inferior_event_type event_type,
10594 void *context), void *context)
10596 if (callback != NULL)
10598 serial_async (remote_desc, remote_async_serial_handler, NULL);
10599 async_client_callback = callback;
10600 async_client_context = context;
10603 serial_async (remote_desc, NULL, NULL);
10607 set_remote_cmd (char *args, int from_tty)
10609 help_list (remote_set_cmdlist, "set remote ", -1, gdb_stdout);
10613 show_remote_cmd (char *args, int from_tty)
10615 /* We can't just use cmd_show_list here, because we want to skip
10616 the redundant "show remote Z-packet" and the legacy aliases. */
10617 struct cleanup *showlist_chain;
10618 struct cmd_list_element *list = remote_show_cmdlist;
10619 struct ui_out *uiout = current_uiout;
10621 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
10622 for (; list != NULL; list = list->next)
10623 if (strcmp (list->name, "Z-packet") == 0)
10625 else if (list->type == not_set_cmd)
10626 /* Alias commands are exactly like the original, except they
10627 don't have the normal type. */
10631 struct cleanup *option_chain
10632 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
10634 ui_out_field_string (uiout, "name", list->name);
10635 ui_out_text (uiout, ": ");
10636 if (list->type == show_cmd)
10637 do_setshow_command ((char *) NULL, from_tty, list);
10639 cmd_func (list, NULL, from_tty);
10640 /* Close the tuple. */
10641 do_cleanups (option_chain);
10644 /* Close the tuple. */
10645 do_cleanups (showlist_chain);
10649 /* Function to be called whenever a new objfile (shlib) is detected. */
10651 remote_new_objfile (struct objfile *objfile)
10653 if (remote_desc != 0) /* Have a remote connection. */
10654 remote_check_symbols (objfile);
10657 /* Pull all the tracepoints defined on the target and create local
10658 data structures representing them. We don't want to create real
10659 tracepoints yet, we don't want to mess up the user's existing
10663 remote_upload_tracepoints (struct uploaded_tp **utpp)
10665 struct remote_state *rs = get_remote_state ();
10668 /* Ask for a first packet of tracepoint definition. */
10670 getpkt (&rs->buf, &rs->buf_size, 0);
10672 while (*p && *p != 'l')
10674 parse_tracepoint_definition (p, utpp);
10675 /* Ask for another packet of tracepoint definition. */
10677 getpkt (&rs->buf, &rs->buf_size, 0);
10684 remote_upload_trace_state_variables (struct uploaded_tsv **utsvp)
10686 struct remote_state *rs = get_remote_state ();
10689 /* Ask for a first packet of variable definition. */
10691 getpkt (&rs->buf, &rs->buf_size, 0);
10693 while (*p && *p != 'l')
10695 parse_tsv_definition (p, utsvp);
10696 /* Ask for another packet of variable definition. */
10698 getpkt (&rs->buf, &rs->buf_size, 0);
10705 _initialize_remote (void)
10707 struct remote_state *rs;
10708 struct cmd_list_element *cmd;
10711 /* architecture specific data */
10712 remote_gdbarch_data_handle =
10713 gdbarch_data_register_post_init (init_remote_state);
10714 remote_g_packet_data_handle =
10715 gdbarch_data_register_pre_init (remote_g_packet_data_init);
10717 /* Initialize the per-target state. At the moment there is only one
10718 of these, not one per target. Only one target is active at a
10719 time. The default buffer size is unimportant; it will be expanded
10720 whenever a larger buffer is needed. */
10721 rs = get_remote_state_raw ();
10722 rs->buf_size = 400;
10723 rs->buf = xmalloc (rs->buf_size);
10725 init_remote_ops ();
10726 add_target (&remote_ops);
10728 init_extended_remote_ops ();
10729 add_target (&extended_remote_ops);
10731 /* Hook into new objfile notification. */
10732 observer_attach_new_objfile (remote_new_objfile);
10734 /* Set up signal handlers. */
10735 sigint_remote_token =
10736 create_async_signal_handler (async_remote_interrupt, NULL);
10737 sigint_remote_twice_token =
10738 create_async_signal_handler (async_remote_interrupt_twice, NULL);
10741 init_remote_threadtests ();
10744 /* set/show remote ... */
10746 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
10747 Remote protocol specific variables\n\
10748 Configure various remote-protocol specific variables such as\n\
10749 the packets being used"),
10750 &remote_set_cmdlist, "set remote ",
10751 0 /* allow-unknown */, &setlist);
10752 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
10753 Remote protocol specific variables\n\
10754 Configure various remote-protocol specific variables such as\n\
10755 the packets being used"),
10756 &remote_show_cmdlist, "show remote ",
10757 0 /* allow-unknown */, &showlist);
10759 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
10760 Compare section data on target to the exec file.\n\
10761 Argument is a single section name (default: all loaded sections)."),
10764 add_cmd ("packet", class_maintenance, packet_command, _("\
10765 Send an arbitrary packet to a remote target.\n\
10766 maintenance packet TEXT\n\
10767 If GDB is talking to an inferior via the GDB serial protocol, then\n\
10768 this command sends the string TEXT to the inferior, and displays the\n\
10769 response packet. GDB supplies the initial `$' character, and the\n\
10770 terminating `#' character and checksum."),
10773 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
10774 Set whether to send break if interrupted."), _("\
10775 Show whether to send break if interrupted."), _("\
10776 If set, a break, instead of a cntrl-c, is sent to the remote target."),
10777 set_remotebreak, show_remotebreak,
10778 &setlist, &showlist);
10779 cmd_name = "remotebreak";
10780 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
10781 deprecate_cmd (cmd, "set remote interrupt-sequence");
10782 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
10783 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
10784 deprecate_cmd (cmd, "show remote interrupt-sequence");
10786 add_setshow_enum_cmd ("interrupt-sequence", class_support,
10787 interrupt_sequence_modes, &interrupt_sequence_mode,
10789 Set interrupt sequence to remote target."), _("\
10790 Show interrupt sequence to remote target."), _("\
10791 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
10792 NULL, show_interrupt_sequence,
10793 &remote_set_cmdlist,
10794 &remote_show_cmdlist);
10796 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
10797 &interrupt_on_connect, _("\
10798 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
10799 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
10800 If set, interrupt sequence is sent to remote target."),
10802 &remote_set_cmdlist, &remote_show_cmdlist);
10804 /* Install commands for configuring memory read/write packets. */
10806 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
10807 Set the maximum number of bytes per memory write packet (deprecated)."),
10809 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
10810 Show the maximum number of bytes per memory write packet (deprecated)."),
10812 add_cmd ("memory-write-packet-size", no_class,
10813 set_memory_write_packet_size, _("\
10814 Set the maximum number of bytes per memory-write packet.\n\
10815 Specify the number of bytes in a packet or 0 (zero) for the\n\
10816 default packet size. The actual limit is further reduced\n\
10817 dependent on the target. Specify ``fixed'' to disable the\n\
10818 further restriction and ``limit'' to enable that restriction."),
10819 &remote_set_cmdlist);
10820 add_cmd ("memory-read-packet-size", no_class,
10821 set_memory_read_packet_size, _("\
10822 Set the maximum number of bytes per memory-read packet.\n\
10823 Specify the number of bytes in a packet or 0 (zero) for the\n\
10824 default packet size. The actual limit is further reduced\n\
10825 dependent on the target. Specify ``fixed'' to disable the\n\
10826 further restriction and ``limit'' to enable that restriction."),
10827 &remote_set_cmdlist);
10828 add_cmd ("memory-write-packet-size", no_class,
10829 show_memory_write_packet_size,
10830 _("Show the maximum number of bytes per memory-write packet."),
10831 &remote_show_cmdlist);
10832 add_cmd ("memory-read-packet-size", no_class,
10833 show_memory_read_packet_size,
10834 _("Show the maximum number of bytes per memory-read packet."),
10835 &remote_show_cmdlist);
10837 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
10838 &remote_hw_watchpoint_limit, _("\
10839 Set the maximum number of target hardware watchpoints."), _("\
10840 Show the maximum number of target hardware watchpoints."), _("\
10841 Specify a negative limit for unlimited."),
10842 NULL, NULL, /* FIXME: i18n: The maximum
10843 number of target hardware
10844 watchpoints is %s. */
10845 &remote_set_cmdlist, &remote_show_cmdlist);
10846 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
10847 &remote_hw_watchpoint_length_limit, _("\
10848 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
10849 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
10850 Specify a negative limit for unlimited."),
10851 NULL, NULL, /* FIXME: i18n: The maximum
10852 length (in bytes) of a target
10853 hardware watchpoint is %s. */
10854 &remote_set_cmdlist, &remote_show_cmdlist);
10855 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
10856 &remote_hw_breakpoint_limit, _("\
10857 Set the maximum number of target hardware breakpoints."), _("\
10858 Show the maximum number of target hardware breakpoints."), _("\
10859 Specify a negative limit for unlimited."),
10860 NULL, NULL, /* FIXME: i18n: The maximum
10861 number of target hardware
10862 breakpoints is %s. */
10863 &remote_set_cmdlist, &remote_show_cmdlist);
10865 add_setshow_integer_cmd ("remoteaddresssize", class_obscure,
10866 &remote_address_size, _("\
10867 Set the maximum size of the address (in bits) in a memory packet."), _("\
10868 Show the maximum size of the address (in bits) in a memory packet."), NULL,
10870 NULL, /* FIXME: i18n: */
10871 &setlist, &showlist);
10873 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
10874 "X", "binary-download", 1);
10876 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
10877 "vCont", "verbose-resume", 0);
10879 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
10880 "QPassSignals", "pass-signals", 0);
10882 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
10883 "qSymbol", "symbol-lookup", 0);
10885 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
10886 "P", "set-register", 1);
10888 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
10889 "p", "fetch-register", 1);
10891 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
10892 "Z0", "software-breakpoint", 0);
10894 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
10895 "Z1", "hardware-breakpoint", 0);
10897 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
10898 "Z2", "write-watchpoint", 0);
10900 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
10901 "Z3", "read-watchpoint", 0);
10903 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
10904 "Z4", "access-watchpoint", 0);
10906 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
10907 "qXfer:auxv:read", "read-aux-vector", 0);
10909 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
10910 "qXfer:features:read", "target-features", 0);
10912 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
10913 "qXfer:libraries:read", "library-info", 0);
10915 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
10916 "qXfer:memory-map:read", "memory-map", 0);
10918 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
10919 "qXfer:spu:read", "read-spu-object", 0);
10921 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
10922 "qXfer:spu:write", "write-spu-object", 0);
10924 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
10925 "qXfer:osdata:read", "osdata", 0);
10927 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
10928 "qXfer:threads:read", "threads", 0);
10930 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
10931 "qXfer:siginfo:read", "read-siginfo-object", 0);
10933 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
10934 "qXfer:siginfo:write", "write-siginfo-object", 0);
10936 add_packet_config_cmd
10937 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
10938 "qXfer:trace-frame-info:read", "traceframe-info", 0);
10940 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
10941 "qGetTLSAddr", "get-thread-local-storage-address",
10944 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
10945 "qGetTIBAddr", "get-thread-information-block-address",
10948 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
10949 "bc", "reverse-continue", 0);
10951 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
10952 "bs", "reverse-step", 0);
10954 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
10955 "qSupported", "supported-packets", 0);
10957 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
10958 "qSearch:memory", "search-memory", 0);
10960 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
10961 "vFile:open", "hostio-open", 0);
10963 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
10964 "vFile:pread", "hostio-pread", 0);
10966 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
10967 "vFile:pwrite", "hostio-pwrite", 0);
10969 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
10970 "vFile:close", "hostio-close", 0);
10972 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
10973 "vFile:unlink", "hostio-unlink", 0);
10975 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
10976 "vAttach", "attach", 0);
10978 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
10981 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
10982 "QStartNoAckMode", "noack", 0);
10984 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
10985 "vKill", "kill", 0);
10987 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
10988 "qAttached", "query-attached", 0);
10990 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
10991 "ConditionalTracepoints",
10992 "conditional-tracepoints", 0);
10993 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
10994 "FastTracepoints", "fast-tracepoints", 0);
10996 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
10997 "TracepointSource", "TracepointSource", 0);
10999 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
11000 "QAllow", "allow", 0);
11002 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
11003 "StaticTracepoints", "static-tracepoints", 0);
11005 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
11006 "qXfer:statictrace:read", "read-sdata-object", 0);
11008 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
11009 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
11011 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
11012 "QDisableRandomization", "disable-randomization", 0);
11014 /* Keep the old ``set remote Z-packet ...'' working. Each individual
11015 Z sub-packet has its own set and show commands, but users may
11016 have sets to this variable in their .gdbinit files (or in their
11018 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
11019 &remote_Z_packet_detect, _("\
11020 Set use of remote protocol `Z' packets"), _("\
11021 Show use of remote protocol `Z' packets "), _("\
11022 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
11024 set_remote_protocol_Z_packet_cmd,
11025 show_remote_protocol_Z_packet_cmd,
11026 /* FIXME: i18n: Use of remote protocol
11027 `Z' packets is %s. */
11028 &remote_set_cmdlist, &remote_show_cmdlist);
11030 add_prefix_cmd ("remote", class_files, remote_command, _("\
11031 Manipulate files on the remote system\n\
11032 Transfer files to and from the remote target system."),
11033 &remote_cmdlist, "remote ",
11034 0 /* allow-unknown */, &cmdlist);
11036 add_cmd ("put", class_files, remote_put_command,
11037 _("Copy a local file to the remote system."),
11040 add_cmd ("get", class_files, remote_get_command,
11041 _("Copy a remote file to the local system."),
11044 add_cmd ("delete", class_files, remote_delete_command,
11045 _("Delete a remote file."),
11048 remote_exec_file = xstrdup ("");
11049 add_setshow_string_noescape_cmd ("exec-file", class_files,
11050 &remote_exec_file, _("\
11051 Set the remote pathname for \"run\""), _("\
11052 Show the remote pathname for \"run\""), NULL, NULL, NULL,
11053 &remote_set_cmdlist, &remote_show_cmdlist);
11055 /* Eventually initialize fileio. See fileio.c */
11056 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
11058 /* Take advantage of the fact that the LWP field is not used, to tag
11059 special ptids with it set to != 0. */
11060 magic_null_ptid = ptid_build (42000, 1, -1);
11061 not_sent_ptid = ptid_build (42000, 1, -2);
11062 any_thread_ptid = ptid_build (42000, 1, 0);
11064 target_buf_size = 2048;
11065 target_buf = xmalloc (target_buf_size);