1 /* Remote target communications for serial-line targets in custom GDB protocol
3 Copyright (C) 1988-2012 Free Software Foundation, Inc.
5 This file is part of GDB.
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
20 /* See the GDB User Guide for details of the GDB remote protocol. */
23 #include "gdb_string.h"
29 #include "exceptions.h"
31 /*#include "terminal.h" */
34 #include "gdb-stabs.h"
35 #include "gdbthread.h"
39 #include "gdb_assert.h"
42 #include "cli/cli-decode.h"
43 #include "cli/cli-setshow.h"
44 #include "target-descriptions.h"
49 #include "event-loop.h"
50 #include "event-top.h"
56 #include "gdbcore.h" /* for exec_bfd */
58 #include "remote-fileio.h"
59 #include "gdb/fileio.h"
61 #include "xml-support.h"
63 #include "memory-map.h"
65 #include "tracepoint.h"
69 /* Temp hacks for tracepoint encoding migration. */
70 static char *target_buf;
71 static long target_buf_size;
73 encode_actions (struct breakpoint *t, struct bp_location *tloc,
74 char ***tdp_actions, char ***stepping_actions);
76 /* The size to align memory write packets, when practical. The protocol
77 does not guarantee any alignment, and gdb will generate short
78 writes and unaligned writes, but even as a best-effort attempt this
79 can improve bulk transfers. For instance, if a write is misaligned
80 relative to the target's data bus, the stub may need to make an extra
81 round trip fetching data from the target. This doesn't make a
82 huge difference, but it's easy to do, so we try to be helpful.
84 The alignment chosen is arbitrary; usually data bus width is
85 important here, not the possibly larger cache line size. */
86 enum { REMOTE_ALIGN_WRITES = 16 };
88 /* Prototypes for local functions. */
89 static void cleanup_sigint_signal_handler (void *dummy);
90 static void initialize_sigint_signal_handler (void);
91 static int getpkt_sane (char **buf, long *sizeof_buf, int forever);
92 static int getpkt_or_notif_sane (char **buf, long *sizeof_buf,
95 static void handle_remote_sigint (int);
96 static void handle_remote_sigint_twice (int);
97 static void async_remote_interrupt (gdb_client_data);
98 void async_remote_interrupt_twice (gdb_client_data);
100 static void remote_files_info (struct target_ops *ignore);
102 static void remote_prepare_to_store (struct regcache *regcache);
104 static void remote_open (char *name, int from_tty);
106 static void extended_remote_open (char *name, int from_tty);
108 static void remote_open_1 (char *, int, struct target_ops *, int extended_p);
110 static void remote_close (int quitting);
112 static void remote_mourn (struct target_ops *ops);
114 static void extended_remote_restart (void);
116 static void extended_remote_mourn (struct target_ops *);
118 static void remote_mourn_1 (struct target_ops *);
120 static void remote_send (char **buf, long *sizeof_buf_p);
122 static int readchar (int timeout);
124 static void remote_kill (struct target_ops *ops);
126 static int tohex (int nib);
128 static int remote_can_async_p (void);
130 static int remote_is_async_p (void);
132 static void remote_async (void (*callback) (enum inferior_event_type event_type,
133 void *context), void *context);
135 static void remote_detach (struct target_ops *ops, char *args, int from_tty);
137 static void remote_interrupt (int signo);
139 static void remote_interrupt_twice (int signo);
141 static void interrupt_query (void);
143 static void set_general_thread (struct ptid ptid);
144 static void set_continue_thread (struct ptid ptid);
146 static void get_offsets (void);
148 static void skip_frame (void);
150 static long read_frame (char **buf_p, long *sizeof_buf);
152 static int hexnumlen (ULONGEST num);
154 static void init_remote_ops (void);
156 static void init_extended_remote_ops (void);
158 static void remote_stop (ptid_t);
160 static int ishex (int ch, int *val);
162 static int stubhex (int ch);
164 static int hexnumstr (char *, ULONGEST);
166 static int hexnumnstr (char *, ULONGEST, int);
168 static CORE_ADDR remote_address_masked (CORE_ADDR);
170 static void print_packet (char *);
172 static void compare_sections_command (char *, int);
174 static void packet_command (char *, int);
176 static int stub_unpack_int (char *buff, int fieldlength);
178 static ptid_t remote_current_thread (ptid_t oldptid);
180 static void remote_find_new_threads (void);
182 static void record_currthread (ptid_t currthread);
184 static int fromhex (int a);
186 extern int hex2bin (const char *hex, gdb_byte *bin, int count);
188 extern int bin2hex (const gdb_byte *bin, char *hex, int count);
190 static int putpkt_binary (char *buf, int cnt);
192 static void check_binary_download (CORE_ADDR addr);
194 struct packet_config;
196 static void show_packet_config_cmd (struct packet_config *config);
198 static void update_packet_config (struct packet_config *config);
200 static void set_remote_protocol_packet_cmd (char *args, int from_tty,
201 struct cmd_list_element *c);
203 static void show_remote_protocol_packet_cmd (struct ui_file *file,
205 struct cmd_list_element *c,
208 static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
209 static ptid_t read_ptid (char *buf, char **obuf);
211 static void remote_set_permissions (void);
214 static int remote_get_trace_status (struct trace_status *ts);
216 static int remote_upload_tracepoints (struct uploaded_tp **utpp);
218 static int remote_upload_trace_state_variables (struct uploaded_tsv **utsvp);
220 static void remote_query_supported (void);
222 static void remote_check_symbols (struct objfile *objfile);
224 void _initialize_remote (void);
227 static struct stop_reply *stop_reply_xmalloc (void);
228 static void stop_reply_xfree (struct stop_reply *);
229 static void do_stop_reply_xfree (void *arg);
230 static void remote_parse_stop_reply (char *buf, struct stop_reply *);
231 static void push_stop_reply (struct stop_reply *);
232 static void remote_get_pending_stop_replies (void);
233 static void discard_pending_stop_replies (int pid);
234 static int peek_stop_reply (ptid_t ptid);
236 static void remote_async_inferior_event_handler (gdb_client_data);
237 static void remote_async_get_pending_events_handler (gdb_client_data);
239 static void remote_terminal_ours (void);
241 static int remote_read_description_p (struct target_ops *target);
243 static void remote_console_output (char *msg);
245 /* The non-stop remote protocol provisions for one pending stop reply.
246 This is where we keep it until it is acknowledged. */
248 static struct stop_reply *pending_stop_reply = NULL;
252 static struct cmd_list_element *remote_cmdlist;
254 /* For "set remote" and "show remote". */
256 static struct cmd_list_element *remote_set_cmdlist;
257 static struct cmd_list_element *remote_show_cmdlist;
259 /* Description of the remote protocol state for the currently
260 connected target. This is per-target state, and independent of the
261 selected architecture. */
265 /* A buffer to use for incoming packets, and its current size. The
266 buffer is grown dynamically for larger incoming packets.
267 Outgoing packets may also be constructed in this buffer.
268 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
269 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
274 /* True if we're going through initial connection setup (finding out
275 about the remote side's threads, relocating symbols, etc.). */
278 /* If we negotiated packet size explicitly (and thus can bypass
279 heuristics for the largest packet size that will not overflow
280 a buffer in the stub), this will be set to that packet size.
281 Otherwise zero, meaning to use the guessed size. */
282 long explicit_packet_size;
284 /* remote_wait is normally called when the target is running and
285 waits for a stop reply packet. But sometimes we need to call it
286 when the target is already stopped. We can send a "?" packet
287 and have remote_wait read the response. Or, if we already have
288 the response, we can stash it in BUF and tell remote_wait to
289 skip calling getpkt. This flag is set when BUF contains a
290 stop reply packet and the target is not waiting. */
291 int cached_wait_status;
293 /* True, if in no ack mode. That is, neither GDB nor the stub will
294 expect acks from each other. The connection is assumed to be
298 /* True if we're connected in extended remote mode. */
301 /* True if the stub reported support for multi-process
303 int multi_process_aware;
305 /* True if we resumed the target and we're waiting for the target to
306 stop. In the mean time, we can't start another command/query.
307 The remote server wouldn't be ready to process it, so we'd
308 timeout waiting for a reply that would never come and eventually
309 we'd close the connection. This can happen in asynchronous mode
310 because we allow GDB commands while the target is running. */
311 int waiting_for_stop_reply;
313 /* True if the stub reports support for non-stop mode. */
316 /* True if the stub reports support for vCont;t. */
319 /* True if the stub reports support for conditional tracepoints. */
320 int cond_tracepoints;
322 /* True if the stub reports support for fast tracepoints. */
323 int fast_tracepoints;
325 /* True if the stub reports support for static tracepoints. */
326 int static_tracepoints;
328 /* True if the stub reports support for installing tracepoint while
330 int install_in_trace;
332 /* True if the stub can continue running a trace while GDB is
334 int disconnected_tracing;
336 /* True if the stub reports support for enabling and disabling
337 tracepoints while a trace experiment is running. */
338 int enable_disable_tracepoints;
340 /* True if the stub can collect strings using tracenz bytecode. */
343 /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
344 responded to that. */
348 /* Private data that we'll store in (struct thread_info)->private. */
349 struct private_thread_info
356 free_private_thread_info (struct private_thread_info *info)
362 /* Returns true if the multi-process extensions are in effect. */
364 remote_multi_process_p (struct remote_state *rs)
366 return rs->extended && rs->multi_process_aware;
369 /* This data could be associated with a target, but we do not always
370 have access to the current target when we need it, so for now it is
371 static. This will be fine for as long as only one target is in use
373 static struct remote_state remote_state;
375 static struct remote_state *
376 get_remote_state_raw (void)
378 return &remote_state;
381 /* Description of the remote protocol for a given architecture. */
385 long offset; /* Offset into G packet. */
386 long regnum; /* GDB's internal register number. */
387 LONGEST pnum; /* Remote protocol register number. */
388 int in_g_packet; /* Always part of G packet. */
389 /* long size in bytes; == register_size (target_gdbarch, regnum);
391 /* char *name; == gdbarch_register_name (target_gdbarch, regnum);
395 struct remote_arch_state
397 /* Description of the remote protocol registers. */
398 long sizeof_g_packet;
400 /* Description of the remote protocol registers indexed by REGNUM
401 (making an array gdbarch_num_regs in size). */
402 struct packet_reg *regs;
404 /* This is the size (in chars) of the first response to the ``g''
405 packet. It is used as a heuristic when determining the maximum
406 size of memory-read and memory-write packets. A target will
407 typically only reserve a buffer large enough to hold the ``g''
408 packet. The size does not include packet overhead (headers and
410 long actual_register_packet_size;
412 /* This is the maximum size (in chars) of a non read/write packet.
413 It is also used as a cap on the size of read/write packets. */
414 long remote_packet_size;
417 long sizeof_pkt = 2000;
419 /* Utility: generate error from an incoming stub packet. */
421 trace_error (char *buf)
424 return; /* not an error msg */
427 case '1': /* malformed packet error */
428 if (*++buf == '0') /* general case: */
429 error (_("remote.c: error in outgoing packet."));
431 error (_("remote.c: error in outgoing packet at field #%ld."),
432 strtol (buf, NULL, 16));
434 error (_("trace API error 0x%s."), ++buf);
436 error (_("Target returns error code '%s'."), buf);
440 /* Utility: wait for reply from stub, while accepting "O" packets. */
442 remote_get_noisy_reply (char **buf_p,
445 do /* Loop on reply from remote stub. */
449 QUIT; /* Allow user to bail out with ^C. */
450 getpkt (buf_p, sizeof_buf, 0);
454 else if (strncmp (buf, "qRelocInsn:", strlen ("qRelocInsn:")) == 0)
457 CORE_ADDR from, to, org_to;
459 int adjusted_size = 0;
460 volatile struct gdb_exception ex;
462 p = buf + strlen ("qRelocInsn:");
463 pp = unpack_varlen_hex (p, &ul);
465 error (_("invalid qRelocInsn packet: %s"), buf);
469 unpack_varlen_hex (p, &ul);
474 TRY_CATCH (ex, RETURN_MASK_ALL)
476 gdbarch_relocate_instruction (target_gdbarch, &to, from);
480 adjusted_size = to - org_to;
482 sprintf (buf, "qRelocInsn:%x", adjusted_size);
485 else if (ex.reason < 0 && ex.error == MEMORY_ERROR)
487 /* Propagate memory errors silently back to the target.
488 The stub may have limited the range of addresses we
489 can write to, for example. */
494 /* Something unexpectedly bad happened. Be verbose so
495 we can tell what, and propagate the error back to the
496 stub, so it doesn't get stuck waiting for a
498 exception_fprintf (gdb_stderr, ex,
499 _("warning: relocating instruction: "));
503 else if (buf[0] == 'O' && buf[1] != 'K')
504 remote_console_output (buf + 1); /* 'O' message from stub */
506 return buf; /* Here's the actual reply. */
511 /* Handle for retreving the remote protocol data from gdbarch. */
512 static struct gdbarch_data *remote_gdbarch_data_handle;
514 static struct remote_arch_state *
515 get_remote_arch_state (void)
517 return gdbarch_data (target_gdbarch, remote_gdbarch_data_handle);
520 /* Fetch the global remote target state. */
522 static struct remote_state *
523 get_remote_state (void)
525 /* Make sure that the remote architecture state has been
526 initialized, because doing so might reallocate rs->buf. Any
527 function which calls getpkt also needs to be mindful of changes
528 to rs->buf, but this call limits the number of places which run
530 get_remote_arch_state ();
532 return get_remote_state_raw ();
536 compare_pnums (const void *lhs_, const void *rhs_)
538 const struct packet_reg * const *lhs = lhs_;
539 const struct packet_reg * const *rhs = rhs_;
541 if ((*lhs)->pnum < (*rhs)->pnum)
543 else if ((*lhs)->pnum == (*rhs)->pnum)
550 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
552 int regnum, num_remote_regs, offset;
553 struct packet_reg **remote_regs;
555 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
557 struct packet_reg *r = ®s[regnum];
559 if (register_size (gdbarch, regnum) == 0)
560 /* Do not try to fetch zero-sized (placeholder) registers. */
563 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
568 /* Define the g/G packet format as the contents of each register
569 with a remote protocol number, in order of ascending protocol
572 remote_regs = alloca (gdbarch_num_regs (gdbarch)
573 * sizeof (struct packet_reg *));
574 for (num_remote_regs = 0, regnum = 0;
575 regnum < gdbarch_num_regs (gdbarch);
577 if (regs[regnum].pnum != -1)
578 remote_regs[num_remote_regs++] = ®s[regnum];
580 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
583 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
585 remote_regs[regnum]->in_g_packet = 1;
586 remote_regs[regnum]->offset = offset;
587 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
593 /* Given the architecture described by GDBARCH, return the remote
594 protocol register's number and the register's offset in the g/G
595 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
596 If the target does not have a mapping for REGNUM, return false,
597 otherwise, return true. */
600 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
601 int *pnum, int *poffset)
604 struct packet_reg *regs;
605 struct cleanup *old_chain;
607 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
609 regs = xcalloc (gdbarch_num_regs (gdbarch), sizeof (struct packet_reg));
610 old_chain = make_cleanup (xfree, regs);
612 sizeof_g_packet = map_regcache_remote_table (gdbarch, regs);
614 *pnum = regs[regnum].pnum;
615 *poffset = regs[regnum].offset;
617 do_cleanups (old_chain);
623 init_remote_state (struct gdbarch *gdbarch)
625 struct remote_state *rs = get_remote_state_raw ();
626 struct remote_arch_state *rsa;
628 rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
630 /* Use the architecture to build a regnum<->pnum table, which will be
631 1:1 unless a feature set specifies otherwise. */
632 rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
633 gdbarch_num_regs (gdbarch),
636 /* Record the maximum possible size of the g packet - it may turn out
638 rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
640 /* Default maximum number of characters in a packet body. Many
641 remote stubs have a hardwired buffer size of 400 bytes
642 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
643 as the maximum packet-size to ensure that the packet and an extra
644 NUL character can always fit in the buffer. This stops GDB
645 trashing stubs that try to squeeze an extra NUL into what is
646 already a full buffer (As of 1999-12-04 that was most stubs). */
647 rsa->remote_packet_size = 400 - 1;
649 /* This one is filled in when a ``g'' packet is received. */
650 rsa->actual_register_packet_size = 0;
652 /* Should rsa->sizeof_g_packet needs more space than the
653 default, adjust the size accordingly. Remember that each byte is
654 encoded as two characters. 32 is the overhead for the packet
655 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
656 (``$NN:G...#NN'') is a better guess, the below has been padded a
658 if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
659 rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
661 /* Make sure that the packet buffer is plenty big enough for
662 this architecture. */
663 if (rs->buf_size < rsa->remote_packet_size)
665 rs->buf_size = 2 * rsa->remote_packet_size;
666 rs->buf = xrealloc (rs->buf, rs->buf_size);
672 /* Return the current allowed size of a remote packet. This is
673 inferred from the current architecture, and should be used to
674 limit the length of outgoing packets. */
676 get_remote_packet_size (void)
678 struct remote_state *rs = get_remote_state ();
679 struct remote_arch_state *rsa = get_remote_arch_state ();
681 if (rs->explicit_packet_size)
682 return rs->explicit_packet_size;
684 return rsa->remote_packet_size;
687 static struct packet_reg *
688 packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
690 if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch))
694 struct packet_reg *r = &rsa->regs[regnum];
696 gdb_assert (r->regnum == regnum);
701 static struct packet_reg *
702 packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
706 for (i = 0; i < gdbarch_num_regs (target_gdbarch); i++)
708 struct packet_reg *r = &rsa->regs[i];
716 /* FIXME: graces/2002-08-08: These variables should eventually be
717 bound to an instance of the target object (as in gdbarch-tdep()),
718 when such a thing exists. */
720 /* This is set to the data address of the access causing the target
721 to stop for a watchpoint. */
722 static CORE_ADDR remote_watch_data_address;
724 /* This is non-zero if target stopped for a watchpoint. */
725 static int remote_stopped_by_watchpoint_p;
727 static struct target_ops remote_ops;
729 static struct target_ops extended_remote_ops;
731 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
732 ``forever'' still use the normal timeout mechanism. This is
733 currently used by the ASYNC code to guarentee that target reads
734 during the initial connect always time-out. Once getpkt has been
735 modified to return a timeout indication and, in turn
736 remote_wait()/wait_for_inferior() have gained a timeout parameter
738 static int wait_forever_enabled_p = 1;
740 /* Allow the user to specify what sequence to send to the remote
741 when he requests a program interruption: Although ^C is usually
742 what remote systems expect (this is the default, here), it is
743 sometimes preferable to send a break. On other systems such
744 as the Linux kernel, a break followed by g, which is Magic SysRq g
745 is required in order to interrupt the execution. */
746 const char interrupt_sequence_control_c[] = "Ctrl-C";
747 const char interrupt_sequence_break[] = "BREAK";
748 const char interrupt_sequence_break_g[] = "BREAK-g";
749 static const char *interrupt_sequence_modes[] =
751 interrupt_sequence_control_c,
752 interrupt_sequence_break,
753 interrupt_sequence_break_g,
756 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
759 show_interrupt_sequence (struct ui_file *file, int from_tty,
760 struct cmd_list_element *c,
763 if (interrupt_sequence_mode == interrupt_sequence_control_c)
764 fprintf_filtered (file,
765 _("Send the ASCII ETX character (Ctrl-c) "
766 "to the remote target to interrupt the "
767 "execution of the program.\n"));
768 else if (interrupt_sequence_mode == interrupt_sequence_break)
769 fprintf_filtered (file,
770 _("send a break signal to the remote target "
771 "to interrupt the execution of the program.\n"));
772 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
773 fprintf_filtered (file,
774 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
775 "the remote target to interrupt the execution "
776 "of Linux kernel.\n"));
778 internal_error (__FILE__, __LINE__,
779 _("Invalid value for interrupt_sequence_mode: %s."),
780 interrupt_sequence_mode);
783 /* This boolean variable specifies whether interrupt_sequence is sent
784 to the remote target when gdb connects to it.
785 This is mostly needed when you debug the Linux kernel: The Linux kernel
786 expects BREAK g which is Magic SysRq g for connecting gdb. */
787 static int interrupt_on_connect = 0;
789 /* This variable is used to implement the "set/show remotebreak" commands.
790 Since these commands are now deprecated in favor of "set/show remote
791 interrupt-sequence", it no longer has any effect on the code. */
792 static int remote_break;
795 set_remotebreak (char *args, int from_tty, struct cmd_list_element *c)
798 interrupt_sequence_mode = interrupt_sequence_break;
800 interrupt_sequence_mode = interrupt_sequence_control_c;
804 show_remotebreak (struct ui_file *file, int from_tty,
805 struct cmd_list_element *c,
810 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
811 remote_open knows that we don't have a file open when the program
813 static struct serial *remote_desc = NULL;
815 /* This variable sets the number of bits in an address that are to be
816 sent in a memory ("M" or "m") packet. Normally, after stripping
817 leading zeros, the entire address would be sent. This variable
818 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
819 initial implementation of remote.c restricted the address sent in
820 memory packets to ``host::sizeof long'' bytes - (typically 32
821 bits). Consequently, for 64 bit targets, the upper 32 bits of an
822 address was never sent. Since fixing this bug may cause a break in
823 some remote targets this variable is principly provided to
824 facilitate backward compatibility. */
826 static int remote_address_size;
828 /* Temporary to track who currently owns the terminal. See
829 remote_terminal_* for more details. */
831 static int remote_async_terminal_ours_p;
833 /* The executable file to use for "run" on the remote side. */
835 static char *remote_exec_file = "";
838 /* User configurable variables for the number of characters in a
839 memory read/write packet. MIN (rsa->remote_packet_size,
840 rsa->sizeof_g_packet) is the default. Some targets need smaller
841 values (fifo overruns, et.al.) and some users need larger values
842 (speed up transfers). The variables ``preferred_*'' (the user
843 request), ``current_*'' (what was actually set) and ``forced_*''
844 (Positive - a soft limit, negative - a hard limit). */
846 struct memory_packet_config
853 /* Compute the current size of a read/write packet. Since this makes
854 use of ``actual_register_packet_size'' the computation is dynamic. */
857 get_memory_packet_size (struct memory_packet_config *config)
859 struct remote_state *rs = get_remote_state ();
860 struct remote_arch_state *rsa = get_remote_arch_state ();
862 /* NOTE: The somewhat arbitrary 16k comes from the knowledge (folk
863 law?) that some hosts don't cope very well with large alloca()
864 calls. Eventually the alloca() code will be replaced by calls to
865 xmalloc() and make_cleanups() allowing this restriction to either
866 be lifted or removed. */
867 #ifndef MAX_REMOTE_PACKET_SIZE
868 #define MAX_REMOTE_PACKET_SIZE 16384
870 /* NOTE: 20 ensures we can write at least one byte. */
871 #ifndef MIN_REMOTE_PACKET_SIZE
872 #define MIN_REMOTE_PACKET_SIZE 20
877 if (config->size <= 0)
878 what_they_get = MAX_REMOTE_PACKET_SIZE;
880 what_they_get = config->size;
884 what_they_get = get_remote_packet_size ();
885 /* Limit the packet to the size specified by the user. */
887 && what_they_get > config->size)
888 what_they_get = config->size;
890 /* Limit it to the size of the targets ``g'' response unless we have
891 permission from the stub to use a larger packet size. */
892 if (rs->explicit_packet_size == 0
893 && rsa->actual_register_packet_size > 0
894 && what_they_get > rsa->actual_register_packet_size)
895 what_they_get = rsa->actual_register_packet_size;
897 if (what_they_get > MAX_REMOTE_PACKET_SIZE)
898 what_they_get = MAX_REMOTE_PACKET_SIZE;
899 if (what_they_get < MIN_REMOTE_PACKET_SIZE)
900 what_they_get = MIN_REMOTE_PACKET_SIZE;
902 /* Make sure there is room in the global buffer for this packet
903 (including its trailing NUL byte). */
904 if (rs->buf_size < what_they_get + 1)
906 rs->buf_size = 2 * what_they_get;
907 rs->buf = xrealloc (rs->buf, 2 * what_they_get);
910 return what_they_get;
913 /* Update the size of a read/write packet. If they user wants
914 something really big then do a sanity check. */
917 set_memory_packet_size (char *args, struct memory_packet_config *config)
919 int fixed_p = config->fixed_p;
920 long size = config->size;
923 error (_("Argument required (integer, `fixed' or `limited')."));
924 else if (strcmp (args, "hard") == 0
925 || strcmp (args, "fixed") == 0)
927 else if (strcmp (args, "soft") == 0
928 || strcmp (args, "limit") == 0)
934 size = strtoul (args, &end, 0);
936 error (_("Invalid %s (bad syntax)."), config->name);
938 /* Instead of explicitly capping the size of a packet to
939 MAX_REMOTE_PACKET_SIZE or dissallowing it, the user is
940 instead allowed to set the size to something arbitrarily
942 if (size > MAX_REMOTE_PACKET_SIZE)
943 error (_("Invalid %s (too large)."), config->name);
947 if (fixed_p && !config->fixed_p)
949 if (! query (_("The target may not be able to correctly handle a %s\n"
950 "of %ld bytes. Change the packet size? "),
952 error (_("Packet size not changed."));
954 /* Update the config. */
955 config->fixed_p = fixed_p;
960 show_memory_packet_size (struct memory_packet_config *config)
962 printf_filtered (_("The %s is %ld. "), config->name, config->size);
964 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
965 get_memory_packet_size (config));
967 printf_filtered (_("Packets are limited to %ld bytes.\n"),
968 get_memory_packet_size (config));
971 static struct memory_packet_config memory_write_packet_config =
973 "memory-write-packet-size",
977 set_memory_write_packet_size (char *args, int from_tty)
979 set_memory_packet_size (args, &memory_write_packet_config);
983 show_memory_write_packet_size (char *args, int from_tty)
985 show_memory_packet_size (&memory_write_packet_config);
989 get_memory_write_packet_size (void)
991 return get_memory_packet_size (&memory_write_packet_config);
994 static struct memory_packet_config memory_read_packet_config =
996 "memory-read-packet-size",
1000 set_memory_read_packet_size (char *args, int from_tty)
1002 set_memory_packet_size (args, &memory_read_packet_config);
1006 show_memory_read_packet_size (char *args, int from_tty)
1008 show_memory_packet_size (&memory_read_packet_config);
1012 get_memory_read_packet_size (void)
1014 long size = get_memory_packet_size (&memory_read_packet_config);
1016 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1017 extra buffer size argument before the memory read size can be
1018 increased beyond this. */
1019 if (size > get_remote_packet_size ())
1020 size = get_remote_packet_size ();
1025 /* Generic configuration support for packets the stub optionally
1026 supports. Allows the user to specify the use of the packet as well
1027 as allowing GDB to auto-detect support in the remote stub. */
1031 PACKET_SUPPORT_UNKNOWN = 0,
1036 struct packet_config
1040 enum auto_boolean detect;
1041 enum packet_support support;
1044 /* Analyze a packet's return value and update the packet config
1055 update_packet_config (struct packet_config *config)
1057 switch (config->detect)
1059 case AUTO_BOOLEAN_TRUE:
1060 config->support = PACKET_ENABLE;
1062 case AUTO_BOOLEAN_FALSE:
1063 config->support = PACKET_DISABLE;
1065 case AUTO_BOOLEAN_AUTO:
1066 config->support = PACKET_SUPPORT_UNKNOWN;
1072 show_packet_config_cmd (struct packet_config *config)
1074 char *support = "internal-error";
1076 switch (config->support)
1079 support = "enabled";
1081 case PACKET_DISABLE:
1082 support = "disabled";
1084 case PACKET_SUPPORT_UNKNOWN:
1085 support = "unknown";
1088 switch (config->detect)
1090 case AUTO_BOOLEAN_AUTO:
1091 printf_filtered (_("Support for the `%s' packet "
1092 "is auto-detected, currently %s.\n"),
1093 config->name, support);
1095 case AUTO_BOOLEAN_TRUE:
1096 case AUTO_BOOLEAN_FALSE:
1097 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1098 config->name, support);
1104 add_packet_config_cmd (struct packet_config *config, const char *name,
1105 const char *title, int legacy)
1111 config->name = name;
1112 config->title = title;
1113 config->detect = AUTO_BOOLEAN_AUTO;
1114 config->support = PACKET_SUPPORT_UNKNOWN;
1115 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1117 show_doc = xstrprintf ("Show current use of remote "
1118 "protocol `%s' (%s) packet",
1120 /* set/show TITLE-packet {auto,on,off} */
1121 cmd_name = xstrprintf ("%s-packet", title);
1122 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
1123 &config->detect, set_doc,
1124 show_doc, NULL, /* help_doc */
1125 set_remote_protocol_packet_cmd,
1126 show_remote_protocol_packet_cmd,
1127 &remote_set_cmdlist, &remote_show_cmdlist);
1128 /* The command code copies the documentation strings. */
1131 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
1136 legacy_name = xstrprintf ("%s-packet", name);
1137 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1138 &remote_set_cmdlist);
1139 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1140 &remote_show_cmdlist);
1144 static enum packet_result
1145 packet_check_result (const char *buf)
1149 /* The stub recognized the packet request. Check that the
1150 operation succeeded. */
1152 && isxdigit (buf[1]) && isxdigit (buf[2])
1154 /* "Enn" - definitly an error. */
1155 return PACKET_ERROR;
1157 /* Always treat "E." as an error. This will be used for
1158 more verbose error messages, such as E.memtypes. */
1159 if (buf[0] == 'E' && buf[1] == '.')
1160 return PACKET_ERROR;
1162 /* The packet may or may not be OK. Just assume it is. */
1166 /* The stub does not support the packet. */
1167 return PACKET_UNKNOWN;
1170 static enum packet_result
1171 packet_ok (const char *buf, struct packet_config *config)
1173 enum packet_result result;
1175 result = packet_check_result (buf);
1180 /* The stub recognized the packet request. */
1181 switch (config->support)
1183 case PACKET_SUPPORT_UNKNOWN:
1185 fprintf_unfiltered (gdb_stdlog,
1186 "Packet %s (%s) is supported\n",
1187 config->name, config->title);
1188 config->support = PACKET_ENABLE;
1190 case PACKET_DISABLE:
1191 internal_error (__FILE__, __LINE__,
1192 _("packet_ok: attempt to use a disabled packet"));
1198 case PACKET_UNKNOWN:
1199 /* The stub does not support the packet. */
1200 switch (config->support)
1203 if (config->detect == AUTO_BOOLEAN_AUTO)
1204 /* If the stub previously indicated that the packet was
1205 supported then there is a protocol error.. */
1206 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1207 config->name, config->title);
1209 /* The user set it wrong. */
1210 error (_("Enabled packet %s (%s) not recognized by stub"),
1211 config->name, config->title);
1213 case PACKET_SUPPORT_UNKNOWN:
1215 fprintf_unfiltered (gdb_stdlog,
1216 "Packet %s (%s) is NOT supported\n",
1217 config->name, config->title);
1218 config->support = PACKET_DISABLE;
1220 case PACKET_DISABLE:
1242 PACKET_vFile_pwrite,
1244 PACKET_vFile_unlink,
1246 PACKET_qXfer_features,
1247 PACKET_qXfer_libraries,
1248 PACKET_qXfer_libraries_svr4,
1249 PACKET_qXfer_memory_map,
1250 PACKET_qXfer_spu_read,
1251 PACKET_qXfer_spu_write,
1252 PACKET_qXfer_osdata,
1253 PACKET_qXfer_threads,
1254 PACKET_qXfer_statictrace_read,
1255 PACKET_qXfer_traceframe_info,
1259 PACKET_QPassSignals,
1260 PACKET_qSearch_memory,
1263 PACKET_QStartNoAckMode,
1265 PACKET_qXfer_siginfo_read,
1266 PACKET_qXfer_siginfo_write,
1268 PACKET_ConditionalTracepoints,
1269 PACKET_FastTracepoints,
1270 PACKET_StaticTracepoints,
1271 PACKET_InstallInTrace,
1274 PACKET_TracepointSource,
1277 PACKET_QDisableRandomization,
1281 static struct packet_config remote_protocol_packets[PACKET_MAX];
1284 set_remote_protocol_packet_cmd (char *args, int from_tty,
1285 struct cmd_list_element *c)
1287 struct packet_config *packet;
1289 for (packet = remote_protocol_packets;
1290 packet < &remote_protocol_packets[PACKET_MAX];
1293 if (&packet->detect == c->var)
1295 update_packet_config (packet);
1299 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
1304 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1305 struct cmd_list_element *c,
1308 struct packet_config *packet;
1310 for (packet = remote_protocol_packets;
1311 packet < &remote_protocol_packets[PACKET_MAX];
1314 if (&packet->detect == c->var)
1316 show_packet_config_cmd (packet);
1320 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
1324 /* Should we try one of the 'Z' requests? */
1328 Z_PACKET_SOFTWARE_BP,
1329 Z_PACKET_HARDWARE_BP,
1336 /* For compatibility with older distributions. Provide a ``set remote
1337 Z-packet ...'' command that updates all the Z packet types. */
1339 static enum auto_boolean remote_Z_packet_detect;
1342 set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1343 struct cmd_list_element *c)
1347 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1349 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
1350 update_packet_config (&remote_protocol_packets[PACKET_Z0 + i]);
1355 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1356 struct cmd_list_element *c,
1361 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1363 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
1367 /* Should we try the 'ThreadInfo' query packet?
1369 This variable (NOT available to the user: auto-detect only!)
1370 determines whether GDB will use the new, simpler "ThreadInfo"
1371 query or the older, more complex syntax for thread queries.
1372 This is an auto-detect variable (set to true at each connect,
1373 and set to false when the target fails to recognize it). */
1375 static int use_threadinfo_query;
1376 static int use_threadextra_query;
1378 /* Tokens for use by the asynchronous signal handlers for SIGINT. */
1379 static struct async_signal_handler *sigint_remote_twice_token;
1380 static struct async_signal_handler *sigint_remote_token;
1383 /* Asynchronous signal handle registered as event loop source for
1384 when we have pending events ready to be passed to the core. */
1386 static struct async_event_handler *remote_async_inferior_event_token;
1388 /* Asynchronous signal handle registered as event loop source for when
1389 the remote sent us a %Stop notification. The registered callback
1390 will do a vStopped sequence to pull the rest of the events out of
1391 the remote side into our event queue. */
1393 static struct async_event_handler *remote_async_get_pending_events_token;
1396 static ptid_t magic_null_ptid;
1397 static ptid_t not_sent_ptid;
1398 static ptid_t any_thread_ptid;
1400 /* These are the threads which we last sent to the remote system. The
1401 TID member will be -1 for all or -2 for not sent yet. */
1403 static ptid_t general_thread;
1404 static ptid_t continue_thread;
1406 /* This the traceframe which we last selected on the remote system.
1407 It will be -1 if no traceframe is selected. */
1408 static int remote_traceframe_number = -1;
1410 /* Find out if the stub attached to PID (and hence GDB should offer to
1411 detach instead of killing it when bailing out). */
1414 remote_query_attached (int pid)
1416 struct remote_state *rs = get_remote_state ();
1418 if (remote_protocol_packets[PACKET_qAttached].support == PACKET_DISABLE)
1421 if (remote_multi_process_p (rs))
1422 sprintf (rs->buf, "qAttached:%x", pid);
1424 sprintf (rs->buf, "qAttached");
1427 getpkt (&rs->buf, &rs->buf_size, 0);
1429 switch (packet_ok (rs->buf,
1430 &remote_protocol_packets[PACKET_qAttached]))
1433 if (strcmp (rs->buf, "1") == 0)
1437 warning (_("Remote failure reply: %s"), rs->buf);
1439 case PACKET_UNKNOWN:
1446 /* Add PID to GDB's inferior table. Since we can be connected to a
1447 remote system before before knowing about any inferior, mark the
1448 target with execution when we find the first inferior. If ATTACHED
1449 is 1, then we had just attached to this inferior. If it is 0, then
1450 we just created this inferior. If it is -1, then try querying the
1451 remote stub to find out if it had attached to the inferior or
1454 static struct inferior *
1455 remote_add_inferior (int pid, int attached)
1457 struct inferior *inf;
1459 /* Check whether this process we're learning about is to be
1460 considered attached, or if is to be considered to have been
1461 spawned by the stub. */
1463 attached = remote_query_attached (pid);
1465 if (gdbarch_has_global_solist (target_gdbarch))
1467 /* If the target shares code across all inferiors, then every
1468 attach adds a new inferior. */
1469 inf = add_inferior (pid);
1471 /* ... and every inferior is bound to the same program space.
1472 However, each inferior may still have its own address
1474 inf->aspace = maybe_new_address_space ();
1475 inf->pspace = current_program_space;
1479 /* In the traditional debugging scenario, there's a 1-1 match
1480 between program/address spaces. We simply bind the inferior
1481 to the program space's address space. */
1482 inf = current_inferior ();
1483 inferior_appeared (inf, pid);
1486 inf->attach_flag = attached;
1491 /* Add thread PTID to GDB's thread list. Tag it as executing/running
1492 according to RUNNING. */
1495 remote_add_thread (ptid_t ptid, int running)
1499 set_executing (ptid, running);
1500 set_running (ptid, running);
1503 /* Come here when we learn about a thread id from the remote target.
1504 It may be the first time we hear about such thread, so take the
1505 opportunity to add it to GDB's thread list. In case this is the
1506 first time we're noticing its corresponding inferior, add it to
1507 GDB's inferior list as well. */
1510 remote_notice_new_inferior (ptid_t currthread, int running)
1512 /* If this is a new thread, add it to GDB's thread list.
1513 If we leave it up to WFI to do this, bad things will happen. */
1515 if (in_thread_list (currthread) && is_exited (currthread))
1517 /* We're seeing an event on a thread id we knew had exited.
1518 This has to be a new thread reusing the old id. Add it. */
1519 remote_add_thread (currthread, running);
1523 if (!in_thread_list (currthread))
1525 struct inferior *inf = NULL;
1526 int pid = ptid_get_pid (currthread);
1528 if (ptid_is_pid (inferior_ptid)
1529 && pid == ptid_get_pid (inferior_ptid))
1531 /* inferior_ptid has no thread member yet. This can happen
1532 with the vAttach -> remote_wait,"TAAthread:" path if the
1533 stub doesn't support qC. This is the first stop reported
1534 after an attach, so this is the main thread. Update the
1535 ptid in the thread list. */
1536 if (in_thread_list (pid_to_ptid (pid)))
1537 thread_change_ptid (inferior_ptid, currthread);
1540 remote_add_thread (currthread, running);
1541 inferior_ptid = currthread;
1546 if (ptid_equal (magic_null_ptid, inferior_ptid))
1548 /* inferior_ptid is not set yet. This can happen with the
1549 vRun -> remote_wait,"TAAthread:" path if the stub
1550 doesn't support qC. This is the first stop reported
1551 after an attach, so this is the main thread. Update the
1552 ptid in the thread list. */
1553 thread_change_ptid (inferior_ptid, currthread);
1557 /* When connecting to a target remote, or to a target
1558 extended-remote which already was debugging an inferior, we
1559 may not know about it yet. Add it before adding its child
1560 thread, so notifications are emitted in a sensible order. */
1561 if (!in_inferior_list (ptid_get_pid (currthread)))
1562 inf = remote_add_inferior (ptid_get_pid (currthread), -1);
1564 /* This is really a new thread. Add it. */
1565 remote_add_thread (currthread, running);
1567 /* If we found a new inferior, let the common code do whatever
1568 it needs to with it (e.g., read shared libraries, insert
1571 notice_new_inferior (currthread, running, 0);
1575 /* Return the private thread data, creating it if necessary. */
1577 struct private_thread_info *
1578 demand_private_info (ptid_t ptid)
1580 struct thread_info *info = find_thread_ptid (ptid);
1586 info->private = xmalloc (sizeof (*(info->private)));
1587 info->private_dtor = free_private_thread_info;
1588 info->private->core = -1;
1589 info->private->extra = 0;
1592 return info->private;
1595 /* Call this function as a result of
1596 1) A halt indication (T packet) containing a thread id
1597 2) A direct query of currthread
1598 3) Successful execution of set thread */
1601 record_currthread (ptid_t currthread)
1603 general_thread = currthread;
1606 static char *last_pass_packet;
1608 /* If 'QPassSignals' is supported, tell the remote stub what signals
1609 it can simply pass through to the inferior without reporting. */
1612 remote_pass_signals (int numsigs, unsigned char *pass_signals)
1614 if (remote_protocol_packets[PACKET_QPassSignals].support != PACKET_DISABLE)
1616 char *pass_packet, *p;
1619 gdb_assert (numsigs < 256);
1620 for (i = 0; i < numsigs; i++)
1622 if (pass_signals[i])
1625 pass_packet = xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
1626 strcpy (pass_packet, "QPassSignals:");
1627 p = pass_packet + strlen (pass_packet);
1628 for (i = 0; i < numsigs; i++)
1630 if (pass_signals[i])
1633 *p++ = tohex (i >> 4);
1634 *p++ = tohex (i & 15);
1643 if (!last_pass_packet || strcmp (last_pass_packet, pass_packet))
1645 struct remote_state *rs = get_remote_state ();
1646 char *buf = rs->buf;
1648 putpkt (pass_packet);
1649 getpkt (&rs->buf, &rs->buf_size, 0);
1650 packet_ok (buf, &remote_protocol_packets[PACKET_QPassSignals]);
1651 if (last_pass_packet)
1652 xfree (last_pass_packet);
1653 last_pass_packet = pass_packet;
1656 xfree (pass_packet);
1660 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
1661 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
1662 thread. If GEN is set, set the general thread, if not, then set
1663 the step/continue thread. */
1665 set_thread (struct ptid ptid, int gen)
1667 struct remote_state *rs = get_remote_state ();
1668 ptid_t state = gen ? general_thread : continue_thread;
1669 char *buf = rs->buf;
1670 char *endbuf = rs->buf + get_remote_packet_size ();
1672 if (ptid_equal (state, ptid))
1676 *buf++ = gen ? 'g' : 'c';
1677 if (ptid_equal (ptid, magic_null_ptid))
1678 xsnprintf (buf, endbuf - buf, "0");
1679 else if (ptid_equal (ptid, any_thread_ptid))
1680 xsnprintf (buf, endbuf - buf, "0");
1681 else if (ptid_equal (ptid, minus_one_ptid))
1682 xsnprintf (buf, endbuf - buf, "-1");
1684 write_ptid (buf, endbuf, ptid);
1686 getpkt (&rs->buf, &rs->buf_size, 0);
1688 general_thread = ptid;
1690 continue_thread = ptid;
1694 set_general_thread (struct ptid ptid)
1696 set_thread (ptid, 1);
1700 set_continue_thread (struct ptid ptid)
1702 set_thread (ptid, 0);
1705 /* Change the remote current process. Which thread within the process
1706 ends up selected isn't important, as long as it is the same process
1707 as what INFERIOR_PTID points to.
1709 This comes from that fact that there is no explicit notion of
1710 "selected process" in the protocol. The selected process for
1711 general operations is the process the selected general thread
1715 set_general_process (void)
1717 struct remote_state *rs = get_remote_state ();
1719 /* If the remote can't handle multiple processes, don't bother. */
1720 if (!remote_multi_process_p (rs))
1723 /* We only need to change the remote current thread if it's pointing
1724 at some other process. */
1725 if (ptid_get_pid (general_thread) != ptid_get_pid (inferior_ptid))
1726 set_general_thread (inferior_ptid);
1730 /* Return nonzero if the thread PTID is still alive on the remote
1734 remote_thread_alive (struct target_ops *ops, ptid_t ptid)
1736 struct remote_state *rs = get_remote_state ();
1739 if (ptid_equal (ptid, magic_null_ptid))
1740 /* The main thread is always alive. */
1743 if (ptid_get_pid (ptid) != 0 && ptid_get_tid (ptid) == 0)
1744 /* The main thread is always alive. This can happen after a
1745 vAttach, if the remote side doesn't support
1750 endp = rs->buf + get_remote_packet_size ();
1753 write_ptid (p, endp, ptid);
1756 getpkt (&rs->buf, &rs->buf_size, 0);
1757 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
1760 /* About these extended threadlist and threadinfo packets. They are
1761 variable length packets but, the fields within them are often fixed
1762 length. They are redundent enough to send over UDP as is the
1763 remote protocol in general. There is a matching unit test module
1766 #define OPAQUETHREADBYTES 8
1768 /* a 64 bit opaque identifier */
1769 typedef unsigned char threadref[OPAQUETHREADBYTES];
1771 /* WARNING: This threadref data structure comes from the remote O.S.,
1772 libstub protocol encoding, and remote.c. It is not particularly
1775 /* Right now, the internal structure is int. We want it to be bigger.
1776 Plan to fix this. */
1778 typedef int gdb_threadref; /* Internal GDB thread reference. */
1780 /* gdb_ext_thread_info is an internal GDB data structure which is
1781 equivalent to the reply of the remote threadinfo packet. */
1783 struct gdb_ext_thread_info
1785 threadref threadid; /* External form of thread reference. */
1786 int active; /* Has state interesting to GDB?
1788 char display[256]; /* Brief state display, name,
1789 blocked/suspended. */
1790 char shortname[32]; /* To be used to name threads. */
1791 char more_display[256]; /* Long info, statistics, queue depth,
1795 /* The volume of remote transfers can be limited by submitting
1796 a mask containing bits specifying the desired information.
1797 Use a union of these values as the 'selection' parameter to
1798 get_thread_info. FIXME: Make these TAG names more thread specific. */
1800 #define TAG_THREADID 1
1801 #define TAG_EXISTS 2
1802 #define TAG_DISPLAY 4
1803 #define TAG_THREADNAME 8
1804 #define TAG_MOREDISPLAY 16
1806 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
1808 char *unpack_varlen_hex (char *buff, ULONGEST *result);
1810 static char *unpack_nibble (char *buf, int *val);
1812 static char *pack_nibble (char *buf, int nibble);
1814 static char *pack_hex_byte (char *pkt, int /* unsigned char */ byte);
1816 static char *unpack_byte (char *buf, int *value);
1818 static char *pack_int (char *buf, int value);
1820 static char *unpack_int (char *buf, int *value);
1822 static char *unpack_string (char *src, char *dest, int length);
1824 static char *pack_threadid (char *pkt, threadref *id);
1826 static char *unpack_threadid (char *inbuf, threadref *id);
1828 void int_to_threadref (threadref *id, int value);
1830 static int threadref_to_int (threadref *ref);
1832 static void copy_threadref (threadref *dest, threadref *src);
1834 static int threadmatch (threadref *dest, threadref *src);
1836 static char *pack_threadinfo_request (char *pkt, int mode,
1839 static int remote_unpack_thread_info_response (char *pkt,
1840 threadref *expectedref,
1841 struct gdb_ext_thread_info
1845 static int remote_get_threadinfo (threadref *threadid,
1846 int fieldset, /*TAG mask */
1847 struct gdb_ext_thread_info *info);
1849 static char *pack_threadlist_request (char *pkt, int startflag,
1851 threadref *nextthread);
1853 static int parse_threadlist_response (char *pkt,
1855 threadref *original_echo,
1856 threadref *resultlist,
1859 static int remote_get_threadlist (int startflag,
1860 threadref *nextthread,
1864 threadref *threadlist);
1866 typedef int (*rmt_thread_action) (threadref *ref, void *context);
1868 static int remote_threadlist_iterator (rmt_thread_action stepfunction,
1869 void *context, int looplimit);
1871 static int remote_newthread_step (threadref *ref, void *context);
1874 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
1875 buffer we're allowed to write to. Returns
1876 BUF+CHARACTERS_WRITTEN. */
1879 write_ptid (char *buf, const char *endbuf, ptid_t ptid)
1882 struct remote_state *rs = get_remote_state ();
1884 if (remote_multi_process_p (rs))
1886 pid = ptid_get_pid (ptid);
1888 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
1890 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
1892 tid = ptid_get_tid (ptid);
1894 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
1896 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
1901 /* Extract a PTID from BUF. If non-null, OBUF is set to the to one
1902 passed the last parsed char. Returns null_ptid on error. */
1905 read_ptid (char *buf, char **obuf)
1909 ULONGEST pid = 0, tid = 0;
1913 /* Multi-process ptid. */
1914 pp = unpack_varlen_hex (p + 1, &pid);
1916 error (_("invalid remote ptid: %s"), p);
1919 pp = unpack_varlen_hex (p + 1, &tid);
1922 return ptid_build (pid, 0, tid);
1925 /* No multi-process. Just a tid. */
1926 pp = unpack_varlen_hex (p, &tid);
1928 /* Since the stub is not sending a process id, then default to
1929 what's in inferior_ptid, unless it's null at this point. If so,
1930 then since there's no way to know the pid of the reported
1931 threads, use the magic number. */
1932 if (ptid_equal (inferior_ptid, null_ptid))
1933 pid = ptid_get_pid (magic_null_ptid);
1935 pid = ptid_get_pid (inferior_ptid);
1939 return ptid_build (pid, 0, tid);
1942 /* Encode 64 bits in 16 chars of hex. */
1944 static const char hexchars[] = "0123456789abcdef";
1947 ishex (int ch, int *val)
1949 if ((ch >= 'a') && (ch <= 'f'))
1951 *val = ch - 'a' + 10;
1954 if ((ch >= 'A') && (ch <= 'F'))
1956 *val = ch - 'A' + 10;
1959 if ((ch >= '0') && (ch <= '9'))
1970 if (ch >= 'a' && ch <= 'f')
1971 return ch - 'a' + 10;
1972 if (ch >= '0' && ch <= '9')
1974 if (ch >= 'A' && ch <= 'F')
1975 return ch - 'A' + 10;
1980 stub_unpack_int (char *buff, int fieldlength)
1987 nibble = stubhex (*buff++);
1991 retval = retval << 4;
1997 unpack_varlen_hex (char *buff, /* packet to parse */
2001 ULONGEST retval = 0;
2003 while (ishex (*buff, &nibble))
2006 retval = retval << 4;
2007 retval |= nibble & 0x0f;
2014 unpack_nibble (char *buf, int *val)
2016 *val = fromhex (*buf++);
2021 pack_nibble (char *buf, int nibble)
2023 *buf++ = hexchars[(nibble & 0x0f)];
2028 pack_hex_byte (char *pkt, int byte)
2030 *pkt++ = hexchars[(byte >> 4) & 0xf];
2031 *pkt++ = hexchars[(byte & 0xf)];
2036 unpack_byte (char *buf, int *value)
2038 *value = stub_unpack_int (buf, 2);
2043 pack_int (char *buf, int value)
2045 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2046 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2047 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2048 buf = pack_hex_byte (buf, (value & 0xff));
2053 unpack_int (char *buf, int *value)
2055 *value = stub_unpack_int (buf, 8);
2059 #if 0 /* Currently unused, uncomment when needed. */
2060 static char *pack_string (char *pkt, char *string);
2063 pack_string (char *pkt, char *string)
2068 len = strlen (string);
2070 len = 200; /* Bigger than most GDB packets, junk??? */
2071 pkt = pack_hex_byte (pkt, len);
2075 if ((ch == '\0') || (ch == '#'))
2076 ch = '*'; /* Protect encapsulation. */
2081 #endif /* 0 (unused) */
2084 unpack_string (char *src, char *dest, int length)
2093 pack_threadid (char *pkt, threadref *id)
2096 unsigned char *altid;
2098 altid = (unsigned char *) id;
2099 limit = pkt + BUF_THREAD_ID_SIZE;
2101 pkt = pack_hex_byte (pkt, *altid++);
2107 unpack_threadid (char *inbuf, threadref *id)
2110 char *limit = inbuf + BUF_THREAD_ID_SIZE;
2113 altref = (char *) id;
2115 while (inbuf < limit)
2117 x = stubhex (*inbuf++);
2118 y = stubhex (*inbuf++);
2119 *altref++ = (x << 4) | y;
2124 /* Externally, threadrefs are 64 bits but internally, they are still
2125 ints. This is due to a mismatch of specifications. We would like
2126 to use 64bit thread references internally. This is an adapter
2130 int_to_threadref (threadref *id, int value)
2132 unsigned char *scan;
2134 scan = (unsigned char *) id;
2140 *scan++ = (value >> 24) & 0xff;
2141 *scan++ = (value >> 16) & 0xff;
2142 *scan++ = (value >> 8) & 0xff;
2143 *scan++ = (value & 0xff);
2147 threadref_to_int (threadref *ref)
2150 unsigned char *scan;
2156 value = (value << 8) | ((*scan++) & 0xff);
2161 copy_threadref (threadref *dest, threadref *src)
2164 unsigned char *csrc, *cdest;
2166 csrc = (unsigned char *) src;
2167 cdest = (unsigned char *) dest;
2174 threadmatch (threadref *dest, threadref *src)
2176 /* Things are broken right now, so just assume we got a match. */
2178 unsigned char *srcp, *destp;
2180 srcp = (char *) src;
2181 destp = (char *) dest;
2185 result &= (*srcp++ == *destp++) ? 1 : 0;
2192 threadid:1, # always request threadid
2199 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
2202 pack_threadinfo_request (char *pkt, int mode, threadref *id)
2204 *pkt++ = 'q'; /* Info Query */
2205 *pkt++ = 'P'; /* process or thread info */
2206 pkt = pack_int (pkt, mode); /* mode */
2207 pkt = pack_threadid (pkt, id); /* threadid */
2208 *pkt = '\0'; /* terminate */
2212 /* These values tag the fields in a thread info response packet. */
2213 /* Tagging the fields allows us to request specific fields and to
2214 add more fields as time goes by. */
2216 #define TAG_THREADID 1 /* Echo the thread identifier. */
2217 #define TAG_EXISTS 2 /* Is this process defined enough to
2218 fetch registers and its stack? */
2219 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
2220 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
2221 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
2225 remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2226 struct gdb_ext_thread_info *info)
2228 struct remote_state *rs = get_remote_state ();
2232 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
2235 /* info->threadid = 0; FIXME: implement zero_threadref. */
2237 info->display[0] = '\0';
2238 info->shortname[0] = '\0';
2239 info->more_display[0] = '\0';
2241 /* Assume the characters indicating the packet type have been
2243 pkt = unpack_int (pkt, &mask); /* arg mask */
2244 pkt = unpack_threadid (pkt, &ref);
2247 warning (_("Incomplete response to threadinfo request."));
2248 if (!threadmatch (&ref, expectedref))
2249 { /* This is an answer to a different request. */
2250 warning (_("ERROR RMT Thread info mismatch."));
2253 copy_threadref (&info->threadid, &ref);
2255 /* Loop on tagged fields , try to bail if somthing goes wrong. */
2257 /* Packets are terminated with nulls. */
2258 while ((pkt < limit) && mask && *pkt)
2260 pkt = unpack_int (pkt, &tag); /* tag */
2261 pkt = unpack_byte (pkt, &length); /* length */
2262 if (!(tag & mask)) /* Tags out of synch with mask. */
2264 warning (_("ERROR RMT: threadinfo tag mismatch."));
2268 if (tag == TAG_THREADID)
2272 warning (_("ERROR RMT: length of threadid is not 16."));
2276 pkt = unpack_threadid (pkt, &ref);
2277 mask = mask & ~TAG_THREADID;
2280 if (tag == TAG_EXISTS)
2282 info->active = stub_unpack_int (pkt, length);
2284 mask = mask & ~(TAG_EXISTS);
2287 warning (_("ERROR RMT: 'exists' length too long."));
2293 if (tag == TAG_THREADNAME)
2295 pkt = unpack_string (pkt, &info->shortname[0], length);
2296 mask = mask & ~TAG_THREADNAME;
2299 if (tag == TAG_DISPLAY)
2301 pkt = unpack_string (pkt, &info->display[0], length);
2302 mask = mask & ~TAG_DISPLAY;
2305 if (tag == TAG_MOREDISPLAY)
2307 pkt = unpack_string (pkt, &info->more_display[0], length);
2308 mask = mask & ~TAG_MOREDISPLAY;
2311 warning (_("ERROR RMT: unknown thread info tag."));
2312 break; /* Not a tag we know about. */
2318 remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
2319 struct gdb_ext_thread_info *info)
2321 struct remote_state *rs = get_remote_state ();
2324 pack_threadinfo_request (rs->buf, fieldset, threadid);
2326 getpkt (&rs->buf, &rs->buf_size, 0);
2328 if (rs->buf[0] == '\0')
2331 result = remote_unpack_thread_info_response (rs->buf + 2,
2336 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
2339 pack_threadlist_request (char *pkt, int startflag, int threadcount,
2340 threadref *nextthread)
2342 *pkt++ = 'q'; /* info query packet */
2343 *pkt++ = 'L'; /* Process LIST or threadLIST request */
2344 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
2345 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
2346 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
2351 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2354 parse_threadlist_response (char *pkt, int result_limit,
2355 threadref *original_echo, threadref *resultlist,
2358 struct remote_state *rs = get_remote_state ();
2360 int count, resultcount, done;
2363 /* Assume the 'q' and 'M chars have been stripped. */
2364 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
2365 /* done parse past here */
2366 pkt = unpack_byte (pkt, &count); /* count field */
2367 pkt = unpack_nibble (pkt, &done);
2368 /* The first threadid is the argument threadid. */
2369 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
2370 while ((count-- > 0) && (pkt < limit))
2372 pkt = unpack_threadid (pkt, resultlist++);
2373 if (resultcount++ >= result_limit)
2382 remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2383 int *done, int *result_count, threadref *threadlist)
2385 struct remote_state *rs = get_remote_state ();
2386 static threadref echo_nextthread;
2389 /* Trancate result limit to be smaller than the packet size. */
2390 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2391 >= get_remote_packet_size ())
2392 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
2394 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2396 getpkt (&rs->buf, &rs->buf_size, 0);
2398 if (*rs->buf == '\0')
2402 parse_threadlist_response (rs->buf + 2, result_limit, &echo_nextthread,
2405 if (!threadmatch (&echo_nextthread, nextthread))
2407 /* FIXME: This is a good reason to drop the packet. */
2408 /* Possably, there is a duplicate response. */
2410 retransmit immediatly - race conditions
2411 retransmit after timeout - yes
2413 wait for packet, then exit
2415 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
2416 return 0; /* I choose simply exiting. */
2418 if (*result_count <= 0)
2422 warning (_("RMT ERROR : failed to get remote thread list."));
2425 return result; /* break; */
2427 if (*result_count > result_limit)
2430 warning (_("RMT ERROR: threadlist response longer than requested."));
2436 /* This is the interface between remote and threads, remotes upper
2439 /* remote_find_new_threads retrieves the thread list and for each
2440 thread in the list, looks up the thread in GDB's internal list,
2441 adding the thread if it does not already exist. This involves
2442 getting partial thread lists from the remote target so, polling the
2443 quit_flag is required. */
2446 /* About this many threadisds fit in a packet. */
2448 #define MAXTHREADLISTRESULTS 32
2451 remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2454 int done, i, result_count;
2458 static threadref nextthread;
2459 static threadref resultthreadlist[MAXTHREADLISTRESULTS];
2464 if (loopcount++ > looplimit)
2467 warning (_("Remote fetch threadlist -infinite loop-."));
2470 if (!remote_get_threadlist (startflag, &nextthread, MAXTHREADLISTRESULTS,
2471 &done, &result_count, resultthreadlist))
2476 /* Clear for later iterations. */
2478 /* Setup to resume next batch of thread references, set nextthread. */
2479 if (result_count >= 1)
2480 copy_threadref (&nextthread, &resultthreadlist[result_count - 1]);
2482 while (result_count--)
2483 if (!(result = (*stepfunction) (&resultthreadlist[i++], context)))
2490 remote_newthread_step (threadref *ref, void *context)
2492 int pid = ptid_get_pid (inferior_ptid);
2493 ptid_t ptid = ptid_build (pid, 0, threadref_to_int (ref));
2495 if (!in_thread_list (ptid))
2497 return 1; /* continue iterator */
2500 #define CRAZY_MAX_THREADS 1000
2503 remote_current_thread (ptid_t oldpid)
2505 struct remote_state *rs = get_remote_state ();
2508 getpkt (&rs->buf, &rs->buf_size, 0);
2509 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
2510 return read_ptid (&rs->buf[2], NULL);
2515 /* Find new threads for info threads command.
2516 * Original version, using John Metzler's thread protocol.
2520 remote_find_new_threads (void)
2522 remote_threadlist_iterator (remote_newthread_step, 0,
2526 #if defined(HAVE_LIBEXPAT)
2528 typedef struct thread_item
2534 DEF_VEC_O(thread_item_t);
2536 struct threads_parsing_context
2538 VEC (thread_item_t) *items;
2542 start_thread (struct gdb_xml_parser *parser,
2543 const struct gdb_xml_element *element,
2544 void *user_data, VEC(gdb_xml_value_s) *attributes)
2546 struct threads_parsing_context *data = user_data;
2548 struct thread_item item;
2550 struct gdb_xml_value *attr;
2552 id = xml_find_attribute (attributes, "id")->value;
2553 item.ptid = read_ptid (id, NULL);
2555 attr = xml_find_attribute (attributes, "core");
2557 item.core = *(ULONGEST *) attr->value;
2563 VEC_safe_push (thread_item_t, data->items, &item);
2567 end_thread (struct gdb_xml_parser *parser,
2568 const struct gdb_xml_element *element,
2569 void *user_data, const char *body_text)
2571 struct threads_parsing_context *data = user_data;
2573 if (body_text && *body_text)
2574 VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
2577 const struct gdb_xml_attribute thread_attributes[] = {
2578 { "id", GDB_XML_AF_NONE, NULL, NULL },
2579 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
2580 { NULL, GDB_XML_AF_NONE, NULL, NULL }
2583 const struct gdb_xml_element thread_children[] = {
2584 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2587 const struct gdb_xml_element threads_children[] = {
2588 { "thread", thread_attributes, thread_children,
2589 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
2590 start_thread, end_thread },
2591 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2594 const struct gdb_xml_element threads_elements[] = {
2595 { "threads", NULL, threads_children,
2596 GDB_XML_EF_NONE, NULL, NULL },
2597 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2600 /* Discard the contents of the constructed thread info context. */
2603 clear_threads_parsing_context (void *p)
2605 struct threads_parsing_context *context = p;
2607 struct thread_item *item;
2609 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2610 xfree (item->extra);
2612 VEC_free (thread_item_t, context->items);
2618 * Find all threads for info threads command.
2619 * Uses new thread protocol contributed by Cisco.
2620 * Falls back and attempts to use the older method (above)
2621 * if the target doesn't respond to the new method.
2625 remote_threads_info (struct target_ops *ops)
2627 struct remote_state *rs = get_remote_state ();
2631 if (remote_desc == 0) /* paranoia */
2632 error (_("Command can only be used when connected to the remote target."));
2634 #if defined(HAVE_LIBEXPAT)
2635 if (remote_protocol_packets[PACKET_qXfer_threads].support == PACKET_ENABLE)
2637 char *xml = target_read_stralloc (¤t_target,
2638 TARGET_OBJECT_THREADS, NULL);
2640 struct cleanup *back_to = make_cleanup (xfree, xml);
2644 struct threads_parsing_context context;
2646 context.items = NULL;
2647 make_cleanup (clear_threads_parsing_context, &context);
2649 if (gdb_xml_parse_quick (_("threads"), "threads.dtd",
2650 threads_elements, xml, &context) == 0)
2653 struct thread_item *item;
2656 VEC_iterate (thread_item_t, context.items, i, item);
2659 if (!ptid_equal (item->ptid, null_ptid))
2661 struct private_thread_info *info;
2662 /* In non-stop mode, we assume new found threads
2663 are running until proven otherwise with a
2664 stop reply. In all-stop, we can only get
2665 here if all threads are stopped. */
2666 int running = non_stop ? 1 : 0;
2668 remote_notice_new_inferior (item->ptid, running);
2670 info = demand_private_info (item->ptid);
2671 info->core = item->core;
2672 info->extra = item->extra;
2679 do_cleanups (back_to);
2684 if (use_threadinfo_query)
2686 putpkt ("qfThreadInfo");
2687 getpkt (&rs->buf, &rs->buf_size, 0);
2689 if (bufp[0] != '\0') /* q packet recognized */
2691 while (*bufp++ == 'm') /* reply contains one or more TID */
2695 new_thread = read_ptid (bufp, &bufp);
2696 if (!ptid_equal (new_thread, null_ptid))
2698 /* In non-stop mode, we assume new found threads
2699 are running until proven otherwise with a
2700 stop reply. In all-stop, we can only get
2701 here if all threads are stopped. */
2702 int running = non_stop ? 1 : 0;
2704 remote_notice_new_inferior (new_thread, running);
2707 while (*bufp++ == ','); /* comma-separated list */
2708 putpkt ("qsThreadInfo");
2709 getpkt (&rs->buf, &rs->buf_size, 0);
2716 /* Only qfThreadInfo is supported in non-stop mode. */
2720 /* Else fall back to old method based on jmetzler protocol. */
2721 use_threadinfo_query = 0;
2722 remote_find_new_threads ();
2727 * Collect a descriptive string about the given thread.
2728 * The target may say anything it wants to about the thread
2729 * (typically info about its blocked / runnable state, name, etc.).
2730 * This string will appear in the info threads display.
2732 * Optional: targets are not required to implement this function.
2736 remote_threads_extra_info (struct thread_info *tp)
2738 struct remote_state *rs = get_remote_state ();
2742 struct gdb_ext_thread_info threadinfo;
2743 static char display_buf[100]; /* arbitrary... */
2744 int n = 0; /* position in display_buf */
2746 if (remote_desc == 0) /* paranoia */
2747 internal_error (__FILE__, __LINE__,
2748 _("remote_threads_extra_info"));
2750 if (ptid_equal (tp->ptid, magic_null_ptid)
2751 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_tid (tp->ptid) == 0))
2752 /* This is the main thread which was added by GDB. The remote
2753 server doesn't know about it. */
2756 if (remote_protocol_packets[PACKET_qXfer_threads].support == PACKET_ENABLE)
2758 struct thread_info *info = find_thread_ptid (tp->ptid);
2760 if (info && info->private)
2761 return info->private->extra;
2766 if (use_threadextra_query)
2769 char *endb = rs->buf + get_remote_packet_size ();
2771 xsnprintf (b, endb - b, "qThreadExtraInfo,");
2773 write_ptid (b, endb, tp->ptid);
2776 getpkt (&rs->buf, &rs->buf_size, 0);
2777 if (rs->buf[0] != 0)
2779 n = min (strlen (rs->buf) / 2, sizeof (display_buf));
2780 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
2781 display_buf [result] = '\0';
2786 /* If the above query fails, fall back to the old method. */
2787 use_threadextra_query = 0;
2788 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
2789 | TAG_MOREDISPLAY | TAG_DISPLAY;
2790 int_to_threadref (&id, ptid_get_tid (tp->ptid));
2791 if (remote_get_threadinfo (&id, set, &threadinfo))
2792 if (threadinfo.active)
2794 if (*threadinfo.shortname)
2795 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
2796 " Name: %s,", threadinfo.shortname);
2797 if (*threadinfo.display)
2798 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
2799 " State: %s,", threadinfo.display);
2800 if (*threadinfo.more_display)
2801 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
2802 " Priority: %s", threadinfo.more_display);
2806 /* For purely cosmetic reasons, clear up trailing commas. */
2807 if (',' == display_buf[n-1])
2808 display_buf[n-1] = ' ';
2817 remote_static_tracepoint_marker_at (CORE_ADDR addr,
2818 struct static_tracepoint_marker *marker)
2820 struct remote_state *rs = get_remote_state ();
2823 sprintf (p, "qTSTMat:");
2825 p += hexnumstr (p, addr);
2827 getpkt (&rs->buf, &rs->buf_size, 0);
2831 error (_("Remote failure reply: %s"), p);
2835 parse_static_tracepoint_marker_definition (p, &p, marker);
2843 free_current_marker (void *arg)
2845 struct static_tracepoint_marker **marker_p = arg;
2847 if (*marker_p != NULL)
2849 release_static_tracepoint_marker (*marker_p);
2856 static VEC(static_tracepoint_marker_p) *
2857 remote_static_tracepoint_markers_by_strid (const char *strid)
2859 struct remote_state *rs = get_remote_state ();
2860 VEC(static_tracepoint_marker_p) *markers = NULL;
2861 struct static_tracepoint_marker *marker = NULL;
2862 struct cleanup *old_chain;
2865 /* Ask for a first packet of static tracepoint marker
2868 getpkt (&rs->buf, &rs->buf_size, 0);
2871 error (_("Remote failure reply: %s"), p);
2873 old_chain = make_cleanup (free_current_marker, &marker);
2878 marker = XCNEW (struct static_tracepoint_marker);
2882 parse_static_tracepoint_marker_definition (p, &p, marker);
2884 if (strid == NULL || strcmp (strid, marker->str_id) == 0)
2886 VEC_safe_push (static_tracepoint_marker_p,
2892 release_static_tracepoint_marker (marker);
2893 memset (marker, 0, sizeof (*marker));
2896 while (*p++ == ','); /* comma-separated list */
2897 /* Ask for another packet of static tracepoint definition. */
2899 getpkt (&rs->buf, &rs->buf_size, 0);
2903 do_cleanups (old_chain);
2908 /* Implement the to_get_ada_task_ptid function for the remote targets. */
2911 remote_get_ada_task_ptid (long lwp, long thread)
2913 return ptid_build (ptid_get_pid (inferior_ptid), 0, lwp);
2917 /* Restart the remote side; this is an extended protocol operation. */
2920 extended_remote_restart (void)
2922 struct remote_state *rs = get_remote_state ();
2924 /* Send the restart command; for reasons I don't understand the
2925 remote side really expects a number after the "R". */
2926 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
2929 remote_fileio_reset ();
2932 /* Clean up connection to a remote debugger. */
2935 remote_close (int quitting)
2937 if (remote_desc == NULL)
2938 return; /* already closed */
2940 /* Make sure we leave stdin registered in the event loop, and we
2941 don't leave the async SIGINT signal handler installed. */
2942 remote_terminal_ours ();
2944 serial_close (remote_desc);
2947 /* We don't have a connection to the remote stub anymore. Get rid
2948 of all the inferiors and their threads we were controlling.
2949 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
2950 will be unable to find the thread corresponding to (pid, 0, 0). */
2951 inferior_ptid = null_ptid;
2952 discard_all_inferiors ();
2954 /* We're no longer interested in any of these events. */
2955 discard_pending_stop_replies (-1);
2957 if (remote_async_inferior_event_token)
2958 delete_async_event_handler (&remote_async_inferior_event_token);
2959 if (remote_async_get_pending_events_token)
2960 delete_async_event_handler (&remote_async_get_pending_events_token);
2963 /* Query the remote side for the text, data and bss offsets. */
2968 struct remote_state *rs = get_remote_state ();
2971 int lose, num_segments = 0, do_sections, do_segments;
2972 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
2973 struct section_offsets *offs;
2974 struct symfile_segment_data *data;
2976 if (symfile_objfile == NULL)
2979 putpkt ("qOffsets");
2980 getpkt (&rs->buf, &rs->buf_size, 0);
2983 if (buf[0] == '\000')
2984 return; /* Return silently. Stub doesn't support
2988 warning (_("Remote failure reply: %s"), buf);
2992 /* Pick up each field in turn. This used to be done with scanf, but
2993 scanf will make trouble if CORE_ADDR size doesn't match
2994 conversion directives correctly. The following code will work
2995 with any size of CORE_ADDR. */
2996 text_addr = data_addr = bss_addr = 0;
3000 if (strncmp (ptr, "Text=", 5) == 0)
3003 /* Don't use strtol, could lose on big values. */
3004 while (*ptr && *ptr != ';')
3005 text_addr = (text_addr << 4) + fromhex (*ptr++);
3007 if (strncmp (ptr, ";Data=", 6) == 0)
3010 while (*ptr && *ptr != ';')
3011 data_addr = (data_addr << 4) + fromhex (*ptr++);
3016 if (!lose && strncmp (ptr, ";Bss=", 5) == 0)
3019 while (*ptr && *ptr != ';')
3020 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
3022 if (bss_addr != data_addr)
3023 warning (_("Target reported unsupported offsets: %s"), buf);
3028 else if (strncmp (ptr, "TextSeg=", 8) == 0)
3031 /* Don't use strtol, could lose on big values. */
3032 while (*ptr && *ptr != ';')
3033 text_addr = (text_addr << 4) + fromhex (*ptr++);
3036 if (strncmp (ptr, ";DataSeg=", 9) == 0)
3039 while (*ptr && *ptr != ';')
3040 data_addr = (data_addr << 4) + fromhex (*ptr++);
3048 error (_("Malformed response to offset query, %s"), buf);
3049 else if (*ptr != '\0')
3050 warning (_("Target reported unsupported offsets: %s"), buf);
3052 offs = ((struct section_offsets *)
3053 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
3054 memcpy (offs, symfile_objfile->section_offsets,
3055 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
3057 data = get_symfile_segment_data (symfile_objfile->obfd);
3058 do_segments = (data != NULL);
3059 do_sections = num_segments == 0;
3061 if (num_segments > 0)
3063 segments[0] = text_addr;
3064 segments[1] = data_addr;
3066 /* If we have two segments, we can still try to relocate everything
3067 by assuming that the .text and .data offsets apply to the whole
3068 text and data segments. Convert the offsets given in the packet
3069 to base addresses for symfile_map_offsets_to_segments. */
3070 else if (data && data->num_segments == 2)
3072 segments[0] = data->segment_bases[0] + text_addr;
3073 segments[1] = data->segment_bases[1] + data_addr;
3076 /* If the object file has only one segment, assume that it is text
3077 rather than data; main programs with no writable data are rare,
3078 but programs with no code are useless. Of course the code might
3079 have ended up in the data segment... to detect that we would need
3080 the permissions here. */
3081 else if (data && data->num_segments == 1)
3083 segments[0] = data->segment_bases[0] + text_addr;
3086 /* There's no way to relocate by segment. */
3092 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3093 offs, num_segments, segments);
3095 if (ret == 0 && !do_sections)
3096 error (_("Can not handle qOffsets TextSeg "
3097 "response with this symbol file"));
3104 free_symfile_segment_data (data);
3108 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3110 /* This is a temporary kludge to force data and bss to use the
3111 same offsets because that's what nlmconv does now. The real
3112 solution requires changes to the stub and remote.c that I
3113 don't have time to do right now. */
3115 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3116 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3119 objfile_relocate (symfile_objfile, offs);
3122 /* Callback for iterate_over_threads. Set the STOP_REQUESTED flags in
3123 threads we know are stopped already. This is used during the
3124 initial remote connection in non-stop mode --- threads that are
3125 reported as already being stopped are left stopped. */
3128 set_stop_requested_callback (struct thread_info *thread, void *data)
3130 /* If we have a stop reply for this thread, it must be stopped. */
3131 if (peek_stop_reply (thread->ptid))
3132 set_stop_requested (thread->ptid, 1);
3137 /* Send interrupt_sequence to remote target. */
3139 send_interrupt_sequence (void)
3141 if (interrupt_sequence_mode == interrupt_sequence_control_c)
3142 serial_write (remote_desc, "\x03", 1);
3143 else if (interrupt_sequence_mode == interrupt_sequence_break)
3144 serial_send_break (remote_desc);
3145 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3147 serial_send_break (remote_desc);
3148 serial_write (remote_desc, "g", 1);
3151 internal_error (__FILE__, __LINE__,
3152 _("Invalid value for interrupt_sequence_mode: %s."),
3153 interrupt_sequence_mode);
3157 remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
3159 struct remote_state *rs = get_remote_state ();
3160 struct packet_config *noack_config;
3161 char *wait_status = NULL;
3163 immediate_quit++; /* Allow user to interrupt it. */
3165 if (interrupt_on_connect)
3166 send_interrupt_sequence ();
3168 /* Ack any packet which the remote side has already sent. */
3169 serial_write (remote_desc, "+", 1);
3171 /* Signal other parts that we're going through the initial setup,
3172 and so things may not be stable yet. */
3173 rs->starting_up = 1;
3175 /* The first packet we send to the target is the optional "supported
3176 packets" request. If the target can answer this, it will tell us
3177 which later probes to skip. */
3178 remote_query_supported ();
3180 /* If the stub wants to get a QAllow, compose one and send it. */
3181 if (remote_protocol_packets[PACKET_QAllow].support != PACKET_DISABLE)
3182 remote_set_permissions ();
3184 /* Next, we possibly activate noack mode.
3186 If the QStartNoAckMode packet configuration is set to AUTO,
3187 enable noack mode if the stub reported a wish for it with
3190 If set to TRUE, then enable noack mode even if the stub didn't
3191 report it in qSupported. If the stub doesn't reply OK, the
3192 session ends with an error.
3194 If FALSE, then don't activate noack mode, regardless of what the
3195 stub claimed should be the default with qSupported. */
3197 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
3199 if (noack_config->detect == AUTO_BOOLEAN_TRUE
3200 || (noack_config->detect == AUTO_BOOLEAN_AUTO
3201 && noack_config->support == PACKET_ENABLE))
3203 putpkt ("QStartNoAckMode");
3204 getpkt (&rs->buf, &rs->buf_size, 0);
3205 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
3211 /* Tell the remote that we are using the extended protocol. */
3213 getpkt (&rs->buf, &rs->buf_size, 0);
3216 /* Next, if the target can specify a description, read it. We do
3217 this before anything involving memory or registers. */
3218 target_find_description ();
3220 /* Next, now that we know something about the target, update the
3221 address spaces in the program spaces. */
3222 update_address_spaces ();
3224 /* On OSs where the list of libraries is global to all
3225 processes, we fetch them early. */
3226 if (gdbarch_has_global_solist (target_gdbarch))
3227 solib_add (NULL, from_tty, target, auto_solib_add);
3231 if (!rs->non_stop_aware)
3232 error (_("Non-stop mode requested, but remote "
3233 "does not support non-stop"));
3235 putpkt ("QNonStop:1");
3236 getpkt (&rs->buf, &rs->buf_size, 0);
3238 if (strcmp (rs->buf, "OK") != 0)
3239 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
3241 /* Find about threads and processes the stub is already
3242 controlling. We default to adding them in the running state.
3243 The '?' query below will then tell us about which threads are
3245 remote_threads_info (target);
3247 else if (rs->non_stop_aware)
3249 /* Don't assume that the stub can operate in all-stop mode.
3250 Request it explicitely. */
3251 putpkt ("QNonStop:0");
3252 getpkt (&rs->buf, &rs->buf_size, 0);
3254 if (strcmp (rs->buf, "OK") != 0)
3255 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
3258 /* Check whether the target is running now. */
3260 getpkt (&rs->buf, &rs->buf_size, 0);
3264 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
3267 error (_("The target is not running (try extended-remote?)"));
3269 /* We're connected, but not running. Drop out before we
3270 call start_remote. */
3271 rs->starting_up = 0;
3276 /* Save the reply for later. */
3277 wait_status = alloca (strlen (rs->buf) + 1);
3278 strcpy (wait_status, rs->buf);
3281 /* Let the stub know that we want it to return the thread. */
3282 set_continue_thread (minus_one_ptid);
3284 /* Without this, some commands which require an active target
3285 (such as kill) won't work. This variable serves (at least)
3286 double duty as both the pid of the target process (if it has
3287 such), and as a flag indicating that a target is active.
3288 These functions should be split out into seperate variables,
3289 especially since GDB will someday have a notion of debugging
3290 several processes. */
3291 inferior_ptid = magic_null_ptid;
3293 /* Now, if we have thread information, update inferior_ptid. */
3294 inferior_ptid = remote_current_thread (inferior_ptid);
3296 remote_add_inferior (ptid_get_pid (inferior_ptid), -1);
3298 /* Always add the main thread. */
3299 add_thread_silent (inferior_ptid);
3301 /* init_wait_for_inferior should be called before get_offsets in order
3302 to manage `inserted' flag in bp loc in a correct state.
3303 breakpoint_init_inferior, called from init_wait_for_inferior, set
3304 `inserted' flag to 0, while before breakpoint_re_set, called from
3305 start_remote, set `inserted' flag to 1. In the initialization of
3306 inferior, breakpoint_init_inferior should be called first, and then
3307 breakpoint_re_set can be called. If this order is broken, state of
3308 `inserted' flag is wrong, and cause some problems on breakpoint
3310 init_wait_for_inferior ();
3312 get_offsets (); /* Get text, data & bss offsets. */
3314 /* If we could not find a description using qXfer, and we know
3315 how to do it some other way, try again. This is not
3316 supported for non-stop; it could be, but it is tricky if
3317 there are no stopped threads when we connect. */
3318 if (remote_read_description_p (target)
3319 && gdbarch_target_desc (target_gdbarch) == NULL)
3321 target_clear_description ();
3322 target_find_description ();
3325 /* Use the previously fetched status. */
3326 gdb_assert (wait_status != NULL);
3327 strcpy (rs->buf, wait_status);
3328 rs->cached_wait_status = 1;
3331 start_remote (from_tty); /* Initialize gdb process mechanisms. */
3335 /* Clear WFI global state. Do this before finding about new
3336 threads and inferiors, and setting the current inferior.
3337 Otherwise we would clear the proceed status of the current
3338 inferior when we want its stop_soon state to be preserved
3339 (see notice_new_inferior). */
3340 init_wait_for_inferior ();
3342 /* In non-stop, we will either get an "OK", meaning that there
3343 are no stopped threads at this time; or, a regular stop
3344 reply. In the latter case, there may be more than one thread
3345 stopped --- we pull them all out using the vStopped
3347 if (strcmp (rs->buf, "OK") != 0)
3349 struct stop_reply *stop_reply;
3350 struct cleanup *old_chain;
3352 stop_reply = stop_reply_xmalloc ();
3353 old_chain = make_cleanup (do_stop_reply_xfree, stop_reply);
3355 remote_parse_stop_reply (rs->buf, stop_reply);
3356 discard_cleanups (old_chain);
3358 /* get_pending_stop_replies acks this one, and gets the rest
3360 pending_stop_reply = stop_reply;
3361 remote_get_pending_stop_replies ();
3363 /* Make sure that threads that were stopped remain
3365 iterate_over_threads (set_stop_requested_callback, NULL);
3368 if (target_can_async_p ())
3369 target_async (inferior_event_handler, 0);
3371 if (thread_count () == 0)
3374 error (_("The target is not running (try extended-remote?)"));
3376 /* We're connected, but not running. Drop out before we
3377 call start_remote. */
3378 rs->starting_up = 0;
3382 /* Let the stub know that we want it to return the thread. */
3384 /* Force the stub to choose a thread. */
3385 set_general_thread (null_ptid);
3388 inferior_ptid = remote_current_thread (minus_one_ptid);
3389 if (ptid_equal (inferior_ptid, minus_one_ptid))
3390 error (_("remote didn't report the current thread in non-stop mode"));
3392 get_offsets (); /* Get text, data & bss offsets. */
3394 /* In non-stop mode, any cached wait status will be stored in
3395 the stop reply queue. */
3396 gdb_assert (wait_status == NULL);
3398 /* Report all signals during attach/startup. */
3399 remote_pass_signals (0, NULL);
3402 /* If we connected to a live target, do some additional setup. */
3403 if (target_has_execution)
3405 if (exec_bfd) /* No use without an exec file. */
3406 remote_check_symbols (symfile_objfile);
3409 /* Possibly the target has been engaged in a trace run started
3410 previously; find out where things are at. */
3411 if (remote_get_trace_status (current_trace_status ()) != -1)
3413 struct uploaded_tp *uploaded_tps = NULL;
3414 struct uploaded_tsv *uploaded_tsvs = NULL;
3416 if (current_trace_status ()->running)
3417 printf_filtered (_("Trace is already running on the target.\n"));
3419 /* Get trace state variables first, they may be checked when
3420 parsing uploaded commands. */
3422 remote_upload_trace_state_variables (&uploaded_tsvs);
3424 merge_uploaded_trace_state_variables (&uploaded_tsvs);
3426 remote_upload_tracepoints (&uploaded_tps);
3428 merge_uploaded_tracepoints (&uploaded_tps);
3431 /* The thread and inferior lists are now synchronized with the
3432 target, our symbols have been relocated, and we're merged the
3433 target's tracepoints with ours. We're done with basic start
3435 rs->starting_up = 0;
3437 /* If breakpoints are global, insert them now. */
3438 if (gdbarch_has_global_breakpoints (target_gdbarch)
3439 && breakpoints_always_inserted_mode ())
3440 insert_breakpoints ();
3443 /* Open a connection to a remote debugger.
3444 NAME is the filename used for communication. */
3447 remote_open (char *name, int from_tty)
3449 remote_open_1 (name, from_tty, &remote_ops, 0);
3452 /* Open a connection to a remote debugger using the extended
3453 remote gdb protocol. NAME is the filename used for communication. */
3456 extended_remote_open (char *name, int from_tty)
3458 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
3461 /* Generic code for opening a connection to a remote target. */
3464 init_all_packet_configs (void)
3468 for (i = 0; i < PACKET_MAX; i++)
3469 update_packet_config (&remote_protocol_packets[i]);
3472 /* Symbol look-up. */
3475 remote_check_symbols (struct objfile *objfile)
3477 struct remote_state *rs = get_remote_state ();
3478 char *msg, *reply, *tmp;
3479 struct minimal_symbol *sym;
3482 /* The remote side has no concept of inferiors that aren't running
3483 yet, it only knows about running processes. If we're connected
3484 but our current inferior is not running, we should not invite the
3485 remote target to request symbol lookups related to its
3486 (unrelated) current process. */
3487 if (!target_has_execution)
3490 if (remote_protocol_packets[PACKET_qSymbol].support == PACKET_DISABLE)
3493 /* Make sure the remote is pointing at the right process. Note
3494 there's no way to select "no process". */
3495 set_general_process ();
3497 /* Allocate a message buffer. We can't reuse the input buffer in RS,
3498 because we need both at the same time. */
3499 msg = alloca (get_remote_packet_size ());
3501 /* Invite target to request symbol lookups. */
3503 putpkt ("qSymbol::");
3504 getpkt (&rs->buf, &rs->buf_size, 0);
3505 packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSymbol]);
3508 while (strncmp (reply, "qSymbol:", 8) == 0)
3511 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
3513 sym = lookup_minimal_symbol (msg, NULL, NULL);
3515 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
3518 int addr_size = gdbarch_addr_bit (target_gdbarch) / 8;
3519 CORE_ADDR sym_addr = SYMBOL_VALUE_ADDRESS (sym);
3521 /* If this is a function address, return the start of code
3522 instead of any data function descriptor. */
3523 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch,
3527 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
3528 phex_nz (sym_addr, addr_size), &reply[8]);
3532 getpkt (&rs->buf, &rs->buf_size, 0);
3537 static struct serial *
3538 remote_serial_open (char *name)
3540 static int udp_warning = 0;
3542 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
3543 of in ser-tcp.c, because it is the remote protocol assuming that the
3544 serial connection is reliable and not the serial connection promising
3546 if (!udp_warning && strncmp (name, "udp:", 4) == 0)
3548 warning (_("The remote protocol may be unreliable over UDP.\n"
3549 "Some events may be lost, rendering further debugging "
3554 return serial_open (name);
3557 /* Inform the target of our permission settings. The permission flags
3558 work without this, but if the target knows the settings, it can do
3559 a couple things. First, it can add its own check, to catch cases
3560 that somehow manage to get by the permissions checks in target
3561 methods. Second, if the target is wired to disallow particular
3562 settings (for instance, a system in the field that is not set up to
3563 be able to stop at a breakpoint), it can object to any unavailable
3567 remote_set_permissions (void)
3569 struct remote_state *rs = get_remote_state ();
3571 sprintf (rs->buf, "QAllow:"
3572 "WriteReg:%x;WriteMem:%x;"
3573 "InsertBreak:%x;InsertTrace:%x;"
3574 "InsertFastTrace:%x;Stop:%x",
3575 may_write_registers, may_write_memory,
3576 may_insert_breakpoints, may_insert_tracepoints,
3577 may_insert_fast_tracepoints, may_stop);
3579 getpkt (&rs->buf, &rs->buf_size, 0);
3581 /* If the target didn't like the packet, warn the user. Do not try
3582 to undo the user's settings, that would just be maddening. */
3583 if (strcmp (rs->buf, "OK") != 0)
3584 warning (_("Remote refused setting permissions with: %s"), rs->buf);
3587 /* This type describes each known response to the qSupported
3589 struct protocol_feature
3591 /* The name of this protocol feature. */
3594 /* The default for this protocol feature. */
3595 enum packet_support default_support;
3597 /* The function to call when this feature is reported, or after
3598 qSupported processing if the feature is not supported.
3599 The first argument points to this structure. The second
3600 argument indicates whether the packet requested support be
3601 enabled, disabled, or probed (or the default, if this function
3602 is being called at the end of processing and this feature was
3603 not reported). The third argument may be NULL; if not NULL, it
3604 is a NUL-terminated string taken from the packet following
3605 this feature's name and an equals sign. */
3606 void (*func) (const struct protocol_feature *, enum packet_support,
3609 /* The corresponding packet for this feature. Only used if
3610 FUNC is remote_supported_packet. */
3615 remote_supported_packet (const struct protocol_feature *feature,
3616 enum packet_support support,
3617 const char *argument)
3621 warning (_("Remote qSupported response supplied an unexpected value for"
3622 " \"%s\"."), feature->name);
3626 if (remote_protocol_packets[feature->packet].support
3627 == PACKET_SUPPORT_UNKNOWN)
3628 remote_protocol_packets[feature->packet].support = support;
3632 remote_packet_size (const struct protocol_feature *feature,
3633 enum packet_support support, const char *value)
3635 struct remote_state *rs = get_remote_state ();
3640 if (support != PACKET_ENABLE)
3643 if (value == NULL || *value == '\0')
3645 warning (_("Remote target reported \"%s\" without a size."),
3651 packet_size = strtol (value, &value_end, 16);
3652 if (errno != 0 || *value_end != '\0' || packet_size < 0)
3654 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
3655 feature->name, value);
3659 if (packet_size > MAX_REMOTE_PACKET_SIZE)
3661 warning (_("limiting remote suggested packet size (%d bytes) to %d"),
3662 packet_size, MAX_REMOTE_PACKET_SIZE);
3663 packet_size = MAX_REMOTE_PACKET_SIZE;
3666 /* Record the new maximum packet size. */
3667 rs->explicit_packet_size = packet_size;
3671 remote_multi_process_feature (const struct protocol_feature *feature,
3672 enum packet_support support, const char *value)
3674 struct remote_state *rs = get_remote_state ();
3676 rs->multi_process_aware = (support == PACKET_ENABLE);
3680 remote_non_stop_feature (const struct protocol_feature *feature,
3681 enum packet_support support, const char *value)
3683 struct remote_state *rs = get_remote_state ();
3685 rs->non_stop_aware = (support == PACKET_ENABLE);
3689 remote_cond_tracepoint_feature (const struct protocol_feature *feature,
3690 enum packet_support support,
3693 struct remote_state *rs = get_remote_state ();
3695 rs->cond_tracepoints = (support == PACKET_ENABLE);
3699 remote_fast_tracepoint_feature (const struct protocol_feature *feature,
3700 enum packet_support support,
3703 struct remote_state *rs = get_remote_state ();
3705 rs->fast_tracepoints = (support == PACKET_ENABLE);
3709 remote_static_tracepoint_feature (const struct protocol_feature *feature,
3710 enum packet_support support,
3713 struct remote_state *rs = get_remote_state ();
3715 rs->static_tracepoints = (support == PACKET_ENABLE);
3719 remote_install_in_trace_feature (const struct protocol_feature *feature,
3720 enum packet_support support,
3723 struct remote_state *rs = get_remote_state ();
3725 rs->install_in_trace = (support == PACKET_ENABLE);
3729 remote_disconnected_tracing_feature (const struct protocol_feature *feature,
3730 enum packet_support support,
3733 struct remote_state *rs = get_remote_state ();
3735 rs->disconnected_tracing = (support == PACKET_ENABLE);
3739 remote_enable_disable_tracepoint_feature (const struct protocol_feature *feature,
3740 enum packet_support support,
3743 struct remote_state *rs = get_remote_state ();
3745 rs->enable_disable_tracepoints = (support == PACKET_ENABLE);
3749 remote_string_tracing_feature (const struct protocol_feature *feature,
3750 enum packet_support support,
3753 struct remote_state *rs = get_remote_state ();
3755 rs->string_tracing = (support == PACKET_ENABLE);
3758 static struct protocol_feature remote_protocol_features[] = {
3759 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
3760 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
3761 PACKET_qXfer_auxv },
3762 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
3763 PACKET_qXfer_features },
3764 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
3765 PACKET_qXfer_libraries },
3766 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
3767 PACKET_qXfer_libraries_svr4 },
3768 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
3769 PACKET_qXfer_memory_map },
3770 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
3771 PACKET_qXfer_spu_read },
3772 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
3773 PACKET_qXfer_spu_write },
3774 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
3775 PACKET_qXfer_osdata },
3776 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
3777 PACKET_qXfer_threads },
3778 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
3779 PACKET_qXfer_traceframe_info },
3780 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
3781 PACKET_QPassSignals },
3782 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
3783 PACKET_QStartNoAckMode },
3784 { "multiprocess", PACKET_DISABLE, remote_multi_process_feature, -1 },
3785 { "QNonStop", PACKET_DISABLE, remote_non_stop_feature, -1 },
3786 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
3787 PACKET_qXfer_siginfo_read },
3788 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
3789 PACKET_qXfer_siginfo_write },
3790 { "ConditionalTracepoints", PACKET_DISABLE, remote_cond_tracepoint_feature,
3791 PACKET_ConditionalTracepoints },
3792 { "FastTracepoints", PACKET_DISABLE, remote_fast_tracepoint_feature,
3793 PACKET_FastTracepoints },
3794 { "StaticTracepoints", PACKET_DISABLE, remote_static_tracepoint_feature,
3795 PACKET_StaticTracepoints },
3796 {"InstallInTrace", PACKET_DISABLE, remote_install_in_trace_feature,
3797 PACKET_InstallInTrace},
3798 { "DisconnectedTracing", PACKET_DISABLE, remote_disconnected_tracing_feature,
3800 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
3802 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
3804 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
3805 PACKET_TracepointSource },
3806 { "QAllow", PACKET_DISABLE, remote_supported_packet,
3808 { "EnableDisableTracepoints", PACKET_DISABLE,
3809 remote_enable_disable_tracepoint_feature, -1 },
3810 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
3811 PACKET_qXfer_fdpic },
3812 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
3813 PACKET_QDisableRandomization },
3814 { "tracenz", PACKET_DISABLE,
3815 remote_string_tracing_feature, -1 },
3818 static char *remote_support_xml;
3820 /* Register string appended to "xmlRegisters=" in qSupported query. */
3823 register_remote_support_xml (const char *xml)
3825 #if defined(HAVE_LIBEXPAT)
3826 if (remote_support_xml == NULL)
3827 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
3830 char *copy = xstrdup (remote_support_xml + 13);
3831 char *p = strtok (copy, ",");
3835 if (strcmp (p, xml) == 0)
3842 while ((p = strtok (NULL, ",")) != NULL);
3845 remote_support_xml = reconcat (remote_support_xml,
3846 remote_support_xml, ",", xml,
3853 remote_query_supported_append (char *msg, const char *append)
3856 return reconcat (msg, msg, ";", append, (char *) NULL);
3858 return xstrdup (append);
3862 remote_query_supported (void)
3864 struct remote_state *rs = get_remote_state ();
3867 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
3869 /* The packet support flags are handled differently for this packet
3870 than for most others. We treat an error, a disabled packet, and
3871 an empty response identically: any features which must be reported
3872 to be used will be automatically disabled. An empty buffer
3873 accomplishes this, since that is also the representation for a list
3874 containing no features. */
3877 if (remote_protocol_packets[PACKET_qSupported].support != PACKET_DISABLE)
3880 struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
3883 q = remote_query_supported_append (q, "multiprocess+");
3885 if (remote_support_xml)
3886 q = remote_query_supported_append (q, remote_support_xml);
3888 q = remote_query_supported_append (q, "qRelocInsn+");
3890 q = reconcat (q, "qSupported:", q, (char *) NULL);
3893 do_cleanups (old_chain);
3895 getpkt (&rs->buf, &rs->buf_size, 0);
3897 /* If an error occured, warn, but do not return - just reset the
3898 buffer to empty and go on to disable features. */
3899 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
3902 warning (_("Remote failure reply: %s"), rs->buf);
3907 memset (seen, 0, sizeof (seen));
3912 enum packet_support is_supported;
3913 char *p, *end, *name_end, *value;
3915 /* First separate out this item from the rest of the packet. If
3916 there's another item after this, we overwrite the separator
3917 (terminated strings are much easier to work with). */
3919 end = strchr (p, ';');
3922 end = p + strlen (p);
3932 warning (_("empty item in \"qSupported\" response"));
3937 name_end = strchr (p, '=');
3940 /* This is a name=value entry. */
3941 is_supported = PACKET_ENABLE;
3942 value = name_end + 1;
3951 is_supported = PACKET_ENABLE;
3955 is_supported = PACKET_DISABLE;
3959 is_supported = PACKET_SUPPORT_UNKNOWN;
3963 warning (_("unrecognized item \"%s\" "
3964 "in \"qSupported\" response"), p);
3970 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
3971 if (strcmp (remote_protocol_features[i].name, p) == 0)
3973 const struct protocol_feature *feature;
3976 feature = &remote_protocol_features[i];
3977 feature->func (feature, is_supported, value);
3982 /* If we increased the packet size, make sure to increase the global
3983 buffer size also. We delay this until after parsing the entire
3984 qSupported packet, because this is the same buffer we were
3986 if (rs->buf_size < rs->explicit_packet_size)
3988 rs->buf_size = rs->explicit_packet_size;
3989 rs->buf = xrealloc (rs->buf, rs->buf_size);
3992 /* Handle the defaults for unmentioned features. */
3993 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
3996 const struct protocol_feature *feature;
3998 feature = &remote_protocol_features[i];
3999 feature->func (feature, feature->default_support, NULL);
4005 remote_open_1 (char *name, int from_tty,
4006 struct target_ops *target, int extended_p)
4008 struct remote_state *rs = get_remote_state ();
4011 error (_("To open a remote debug connection, you need to specify what\n"
4012 "serial device is attached to the remote system\n"
4013 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
4015 /* See FIXME above. */
4016 if (!target_async_permitted)
4017 wait_forever_enabled_p = 1;
4019 /* If we're connected to a running target, target_preopen will kill it.
4020 But if we're connected to a target system with no running process,
4021 then we will still be connected when it returns. Ask this question
4022 first, before target_preopen has a chance to kill anything. */
4023 if (remote_desc != NULL && !have_inferiors ())
4026 || query (_("Already connected to a remote target. Disconnect? ")))
4029 error (_("Still connected."));
4032 target_preopen (from_tty);
4034 unpush_target (target);
4036 /* This time without a query. If we were connected to an
4037 extended-remote target and target_preopen killed the running
4038 process, we may still be connected. If we are starting "target
4039 remote" now, the extended-remote target will not have been
4040 removed by unpush_target. */
4041 if (remote_desc != NULL && !have_inferiors ())
4044 /* Make sure we send the passed signals list the next time we resume. */
4045 xfree (last_pass_packet);
4046 last_pass_packet = NULL;
4048 remote_fileio_reset ();
4049 reopen_exec_file ();
4052 remote_desc = remote_serial_open (name);
4054 perror_with_name (name);
4056 if (baud_rate != -1)
4058 if (serial_setbaudrate (remote_desc, baud_rate))
4060 /* The requested speed could not be set. Error out to
4061 top level after closing remote_desc. Take care to
4062 set remote_desc to NULL to avoid closing remote_desc
4064 serial_close (remote_desc);
4066 perror_with_name (name);
4070 serial_raw (remote_desc);
4072 /* If there is something sitting in the buffer we might take it as a
4073 response to a command, which would be bad. */
4074 serial_flush_input (remote_desc);
4078 puts_filtered ("Remote debugging using ");
4079 puts_filtered (name);
4080 puts_filtered ("\n");
4082 push_target (target); /* Switch to using remote target now. */
4084 /* Register extra event sources in the event loop. */
4085 remote_async_inferior_event_token
4086 = create_async_event_handler (remote_async_inferior_event_handler,
4088 remote_async_get_pending_events_token
4089 = create_async_event_handler (remote_async_get_pending_events_handler,
4092 /* Reset the target state; these things will be queried either by
4093 remote_query_supported or as they are needed. */
4094 init_all_packet_configs ();
4095 rs->cached_wait_status = 0;
4096 rs->explicit_packet_size = 0;
4098 rs->multi_process_aware = 0;
4099 rs->extended = extended_p;
4100 rs->non_stop_aware = 0;
4101 rs->waiting_for_stop_reply = 0;
4102 rs->ctrlc_pending_p = 0;
4104 general_thread = not_sent_ptid;
4105 continue_thread = not_sent_ptid;
4106 remote_traceframe_number = -1;
4108 /* Probe for ability to use "ThreadInfo" query, as required. */
4109 use_threadinfo_query = 1;
4110 use_threadextra_query = 1;
4112 if (target_async_permitted)
4114 /* With this target we start out by owning the terminal. */
4115 remote_async_terminal_ours_p = 1;
4117 /* FIXME: cagney/1999-09-23: During the initial connection it is
4118 assumed that the target is already ready and able to respond to
4119 requests. Unfortunately remote_start_remote() eventually calls
4120 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
4121 around this. Eventually a mechanism that allows
4122 wait_for_inferior() to expect/get timeouts will be
4124 wait_forever_enabled_p = 0;
4127 /* First delete any symbols previously loaded from shared libraries. */
4128 no_shared_libraries (NULL, 0);
4131 init_thread_list ();
4133 /* Start the remote connection. If error() or QUIT, discard this
4134 target (we'd otherwise be in an inconsistent state) and then
4135 propogate the error on up the exception chain. This ensures that
4136 the caller doesn't stumble along blindly assuming that the
4137 function succeeded. The CLI doesn't have this problem but other
4138 UI's, such as MI do.
4140 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
4141 this function should return an error indication letting the
4142 caller restore the previous state. Unfortunately the command
4143 ``target remote'' is directly wired to this function making that
4144 impossible. On a positive note, the CLI side of this problem has
4145 been fixed - the function set_cmd_context() makes it possible for
4146 all the ``target ....'' commands to share a common callback
4147 function. See cli-dump.c. */
4149 volatile struct gdb_exception ex;
4151 TRY_CATCH (ex, RETURN_MASK_ALL)
4153 remote_start_remote (from_tty, target, extended_p);
4157 /* Pop the partially set up target - unless something else did
4158 already before throwing the exception. */
4159 if (remote_desc != NULL)
4161 if (target_async_permitted)
4162 wait_forever_enabled_p = 1;
4163 throw_exception (ex);
4167 if (target_async_permitted)
4168 wait_forever_enabled_p = 1;
4171 /* This takes a program previously attached to and detaches it. After
4172 this is done, GDB can be used to debug some other program. We
4173 better not have left any breakpoints in the target program or it'll
4174 die when it hits one. */
4177 remote_detach_1 (char *args, int from_tty, int extended)
4179 int pid = ptid_get_pid (inferior_ptid);
4180 struct remote_state *rs = get_remote_state ();
4183 error (_("Argument given to \"detach\" when remotely debugging."));
4185 if (!target_has_execution)
4186 error (_("No process to detach from."));
4188 /* Tell the remote target to detach. */
4189 if (remote_multi_process_p (rs))
4190 sprintf (rs->buf, "D;%x", pid);
4192 strcpy (rs->buf, "D");
4195 getpkt (&rs->buf, &rs->buf_size, 0);
4197 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
4199 else if (rs->buf[0] == '\0')
4200 error (_("Remote doesn't know how to detach"));
4202 error (_("Can't detach process."));
4206 if (remote_multi_process_p (rs))
4207 printf_filtered (_("Detached from remote %s.\n"),
4208 target_pid_to_str (pid_to_ptid (pid)));
4212 puts_filtered (_("Detached from remote process.\n"));
4214 puts_filtered (_("Ending remote debugging.\n"));
4218 discard_pending_stop_replies (pid);
4219 target_mourn_inferior ();
4223 remote_detach (struct target_ops *ops, char *args, int from_tty)
4225 remote_detach_1 (args, from_tty, 0);
4229 extended_remote_detach (struct target_ops *ops, char *args, int from_tty)
4231 remote_detach_1 (args, from_tty, 1);
4234 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
4237 remote_disconnect (struct target_ops *target, char *args, int from_tty)
4240 error (_("Argument given to \"disconnect\" when remotely debugging."));
4242 /* Make sure we unpush even the extended remote targets; mourn
4243 won't do it. So call remote_mourn_1 directly instead of
4244 target_mourn_inferior. */
4245 remote_mourn_1 (target);
4248 puts_filtered ("Ending remote debugging.\n");
4251 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
4252 be chatty about it. */
4255 extended_remote_attach_1 (struct target_ops *target, char *args, int from_tty)
4257 struct remote_state *rs = get_remote_state ();
4259 char *wait_status = NULL;
4261 pid = parse_pid_to_attach (args);
4263 /* Remote PID can be freely equal to getpid, do not check it here the same
4264 way as in other targets. */
4266 if (remote_protocol_packets[PACKET_vAttach].support == PACKET_DISABLE)
4267 error (_("This target does not support attaching to a process"));
4269 sprintf (rs->buf, "vAttach;%x", pid);
4271 getpkt (&rs->buf, &rs->buf_size, 0);
4273 if (packet_ok (rs->buf,
4274 &remote_protocol_packets[PACKET_vAttach]) == PACKET_OK)
4277 printf_unfiltered (_("Attached to %s\n"),
4278 target_pid_to_str (pid_to_ptid (pid)));
4282 /* Save the reply for later. */
4283 wait_status = alloca (strlen (rs->buf) + 1);
4284 strcpy (wait_status, rs->buf);
4286 else if (strcmp (rs->buf, "OK") != 0)
4287 error (_("Attaching to %s failed with: %s"),
4288 target_pid_to_str (pid_to_ptid (pid)),
4291 else if (remote_protocol_packets[PACKET_vAttach].support == PACKET_DISABLE)
4292 error (_("This target does not support attaching to a process"));
4294 error (_("Attaching to %s failed"),
4295 target_pid_to_str (pid_to_ptid (pid)));
4297 set_current_inferior (remote_add_inferior (pid, 1));
4299 inferior_ptid = pid_to_ptid (pid);
4303 struct thread_info *thread;
4305 /* Get list of threads. */
4306 remote_threads_info (target);
4308 thread = first_thread_of_process (pid);
4310 inferior_ptid = thread->ptid;
4312 inferior_ptid = pid_to_ptid (pid);
4314 /* Invalidate our notion of the remote current thread. */
4315 record_currthread (minus_one_ptid);
4319 /* Now, if we have thread information, update inferior_ptid. */
4320 inferior_ptid = remote_current_thread (inferior_ptid);
4322 /* Add the main thread to the thread list. */
4323 add_thread_silent (inferior_ptid);
4326 /* Next, if the target can specify a description, read it. We do
4327 this before anything involving memory or registers. */
4328 target_find_description ();
4332 /* Use the previously fetched status. */
4333 gdb_assert (wait_status != NULL);
4335 if (target_can_async_p ())
4337 struct stop_reply *stop_reply;
4338 struct cleanup *old_chain;
4340 stop_reply = stop_reply_xmalloc ();
4341 old_chain = make_cleanup (do_stop_reply_xfree, stop_reply);
4342 remote_parse_stop_reply (wait_status, stop_reply);
4343 discard_cleanups (old_chain);
4344 push_stop_reply (stop_reply);
4346 target_async (inferior_event_handler, 0);
4350 gdb_assert (wait_status != NULL);
4351 strcpy (rs->buf, wait_status);
4352 rs->cached_wait_status = 1;
4356 gdb_assert (wait_status == NULL);
4360 extended_remote_attach (struct target_ops *ops, char *args, int from_tty)
4362 extended_remote_attach_1 (ops, args, from_tty);
4365 /* Convert hex digit A to a number. */
4370 if (a >= '0' && a <= '9')
4372 else if (a >= 'a' && a <= 'f')
4373 return a - 'a' + 10;
4374 else if (a >= 'A' && a <= 'F')
4375 return a - 'A' + 10;
4377 error (_("Reply contains invalid hex digit %d"), a);
4381 hex2bin (const char *hex, gdb_byte *bin, int count)
4385 for (i = 0; i < count; i++)
4387 if (hex[0] == 0 || hex[1] == 0)
4389 /* Hex string is short, or of uneven length.
4390 Return the count that has been converted so far. */
4393 *bin++ = fromhex (hex[0]) * 16 + fromhex (hex[1]);
4399 /* Convert number NIB to a hex digit. */
4407 return 'a' + nib - 10;
4411 bin2hex (const gdb_byte *bin, char *hex, int count)
4415 /* May use a length, or a nul-terminated string as input. */
4417 count = strlen ((char *) bin);
4419 for (i = 0; i < count; i++)
4421 *hex++ = tohex ((*bin >> 4) & 0xf);
4422 *hex++ = tohex (*bin++ & 0xf);
4428 /* Check for the availability of vCont. This function should also check
4432 remote_vcont_probe (struct remote_state *rs)
4436 strcpy (rs->buf, "vCont?");
4438 getpkt (&rs->buf, &rs->buf_size, 0);
4441 /* Make sure that the features we assume are supported. */
4442 if (strncmp (buf, "vCont", 5) == 0)
4445 int support_s, support_S, support_c, support_C;
4451 rs->support_vCont_t = 0;
4452 while (p && *p == ';')
4455 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
4457 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
4459 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
4461 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
4463 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
4464 rs->support_vCont_t = 1;
4466 p = strchr (p, ';');
4469 /* If s, S, c, and C are not all supported, we can't use vCont. Clearing
4470 BUF will make packet_ok disable the packet. */
4471 if (!support_s || !support_S || !support_c || !support_C)
4475 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
4478 /* Helper function for building "vCont" resumptions. Write a
4479 resumption to P. ENDP points to one-passed-the-end of the buffer
4480 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
4481 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
4482 resumed thread should be single-stepped and/or signalled. If PTID
4483 equals minus_one_ptid, then all threads are resumed; if PTID
4484 represents a process, then all threads of the process are resumed;
4485 the thread to be stepped and/or signalled is given in the global
4489 append_resumption (char *p, char *endp,
4490 ptid_t ptid, int step, enum target_signal siggnal)
4492 struct remote_state *rs = get_remote_state ();
4494 if (step && siggnal != TARGET_SIGNAL_0)
4495 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
4497 p += xsnprintf (p, endp - p, ";s");
4498 else if (siggnal != TARGET_SIGNAL_0)
4499 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
4501 p += xsnprintf (p, endp - p, ";c");
4503 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
4507 /* All (-1) threads of process. */
4508 nptid = ptid_build (ptid_get_pid (ptid), 0, -1);
4510 p += xsnprintf (p, endp - p, ":");
4511 p = write_ptid (p, endp, nptid);
4513 else if (!ptid_equal (ptid, minus_one_ptid))
4515 p += xsnprintf (p, endp - p, ":");
4516 p = write_ptid (p, endp, ptid);
4522 /* Resume the remote inferior by using a "vCont" packet. The thread
4523 to be resumed is PTID; STEP and SIGGNAL indicate whether the
4524 resumed thread should be single-stepped and/or signalled. If PTID
4525 equals minus_one_ptid, then all threads are resumed; the thread to
4526 be stepped and/or signalled is given in the global INFERIOR_PTID.
4527 This function returns non-zero iff it resumes the inferior.
4529 This function issues a strict subset of all possible vCont commands at the
4533 remote_vcont_resume (ptid_t ptid, int step, enum target_signal siggnal)
4535 struct remote_state *rs = get_remote_state ();
4539 if (remote_protocol_packets[PACKET_vCont].support == PACKET_SUPPORT_UNKNOWN)
4540 remote_vcont_probe (rs);
4542 if (remote_protocol_packets[PACKET_vCont].support == PACKET_DISABLE)
4546 endp = rs->buf + get_remote_packet_size ();
4548 /* If we could generate a wider range of packets, we'd have to worry
4549 about overflowing BUF. Should there be a generic
4550 "multi-part-packet" packet? */
4552 p += xsnprintf (p, endp - p, "vCont");
4554 if (ptid_equal (ptid, magic_null_ptid))
4556 /* MAGIC_NULL_PTID means that we don't have any active threads,
4557 so we don't have any TID numbers the inferior will
4558 understand. Make sure to only send forms that do not specify
4560 append_resumption (p, endp, minus_one_ptid, step, siggnal);
4562 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
4564 /* Resume all threads (of all processes, or of a single
4565 process), with preference for INFERIOR_PTID. This assumes
4566 inferior_ptid belongs to the set of all threads we are about
4568 if (step || siggnal != TARGET_SIGNAL_0)
4570 /* Step inferior_ptid, with or without signal. */
4571 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
4574 /* And continue others without a signal. */
4575 append_resumption (p, endp, ptid, /*step=*/ 0, TARGET_SIGNAL_0);
4579 /* Scheduler locking; resume only PTID. */
4580 append_resumption (p, endp, ptid, step, siggnal);
4583 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
4588 /* In non-stop, the stub replies to vCont with "OK". The stop
4589 reply will be reported asynchronously by means of a `%Stop'
4591 getpkt (&rs->buf, &rs->buf_size, 0);
4592 if (strcmp (rs->buf, "OK") != 0)
4593 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
4599 /* Tell the remote machine to resume. */
4601 static enum target_signal last_sent_signal = TARGET_SIGNAL_0;
4603 static int last_sent_step;
4606 remote_resume (struct target_ops *ops,
4607 ptid_t ptid, int step, enum target_signal siggnal)
4609 struct remote_state *rs = get_remote_state ();
4612 last_sent_signal = siggnal;
4613 last_sent_step = step;
4615 /* The vCont packet doesn't need to specify threads via Hc. */
4616 /* No reverse support (yet) for vCont. */
4617 if (execution_direction != EXEC_REVERSE)
4618 if (remote_vcont_resume (ptid, step, siggnal))
4621 /* All other supported resume packets do use Hc, so set the continue
4623 if (ptid_equal (ptid, minus_one_ptid))
4624 set_continue_thread (any_thread_ptid);
4626 set_continue_thread (ptid);
4629 if (execution_direction == EXEC_REVERSE)
4631 /* We don't pass signals to the target in reverse exec mode. */
4632 if (info_verbose && siggnal != TARGET_SIGNAL_0)
4633 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
4637 && remote_protocol_packets[PACKET_bs].support == PACKET_DISABLE)
4638 error (_("Remote reverse-step not supported."));
4640 && remote_protocol_packets[PACKET_bc].support == PACKET_DISABLE)
4641 error (_("Remote reverse-continue not supported."));
4643 strcpy (buf, step ? "bs" : "bc");
4645 else if (siggnal != TARGET_SIGNAL_0)
4647 buf[0] = step ? 'S' : 'C';
4648 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
4649 buf[2] = tohex (((int) siggnal) & 0xf);
4653 strcpy (buf, step ? "s" : "c");
4658 /* We are about to start executing the inferior, let's register it
4659 with the event loop. NOTE: this is the one place where all the
4660 execution commands end up. We could alternatively do this in each
4661 of the execution commands in infcmd.c. */
4662 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
4663 into infcmd.c in order to allow inferior function calls to work
4664 NOT asynchronously. */
4665 if (target_can_async_p ())
4666 target_async (inferior_event_handler, 0);
4668 /* We've just told the target to resume. The remote server will
4669 wait for the inferior to stop, and then send a stop reply. In
4670 the mean time, we can't start another command/query ourselves
4671 because the stub wouldn't be ready to process it. This applies
4672 only to the base all-stop protocol, however. In non-stop (which
4673 only supports vCont), the stub replies with an "OK", and is
4674 immediate able to process further serial input. */
4676 rs->waiting_for_stop_reply = 1;
4680 /* Set up the signal handler for SIGINT, while the target is
4681 executing, ovewriting the 'regular' SIGINT signal handler. */
4683 initialize_sigint_signal_handler (void)
4685 signal (SIGINT, handle_remote_sigint);
4688 /* Signal handler for SIGINT, while the target is executing. */
4690 handle_remote_sigint (int sig)
4692 signal (sig, handle_remote_sigint_twice);
4693 mark_async_signal_handler_wrapper (sigint_remote_token);
4696 /* Signal handler for SIGINT, installed after SIGINT has already been
4697 sent once. It will take effect the second time that the user sends
4700 handle_remote_sigint_twice (int sig)
4702 signal (sig, handle_remote_sigint);
4703 mark_async_signal_handler_wrapper (sigint_remote_twice_token);
4706 /* Perform the real interruption of the target execution, in response
4709 async_remote_interrupt (gdb_client_data arg)
4712 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
4714 target_stop (inferior_ptid);
4717 /* Perform interrupt, if the first attempt did not succeed. Just give
4718 up on the target alltogether. */
4720 async_remote_interrupt_twice (gdb_client_data arg)
4723 fprintf_unfiltered (gdb_stdlog, "remote_interrupt_twice called\n");
4728 /* Reinstall the usual SIGINT handlers, after the target has
4731 cleanup_sigint_signal_handler (void *dummy)
4733 signal (SIGINT, handle_sigint);
4736 /* Send ^C to target to halt it. Target will respond, and send us a
4738 static void (*ofunc) (int);
4740 /* The command line interface's stop routine. This function is installed
4741 as a signal handler for SIGINT. The first time a user requests a
4742 stop, we call remote_stop to send a break or ^C. If there is no
4743 response from the target (it didn't stop when the user requested it),
4744 we ask the user if he'd like to detach from the target. */
4746 remote_interrupt (int signo)
4748 /* If this doesn't work, try more severe steps. */
4749 signal (signo, remote_interrupt_twice);
4751 gdb_call_async_signal_handler (sigint_remote_token, 1);
4754 /* The user typed ^C twice. */
4757 remote_interrupt_twice (int signo)
4759 signal (signo, ofunc);
4760 gdb_call_async_signal_handler (sigint_remote_twice_token, 1);
4761 signal (signo, remote_interrupt);
4764 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
4765 thread, all threads of a remote process, or all threads of all
4769 remote_stop_ns (ptid_t ptid)
4771 struct remote_state *rs = get_remote_state ();
4773 char *endp = rs->buf + get_remote_packet_size ();
4775 if (remote_protocol_packets[PACKET_vCont].support == PACKET_SUPPORT_UNKNOWN)
4776 remote_vcont_probe (rs);
4778 if (!rs->support_vCont_t)
4779 error (_("Remote server does not support stopping threads"));
4781 if (ptid_equal (ptid, minus_one_ptid)
4782 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
4783 p += xsnprintf (p, endp - p, "vCont;t");
4788 p += xsnprintf (p, endp - p, "vCont;t:");
4790 if (ptid_is_pid (ptid))
4791 /* All (-1) threads of process. */
4792 nptid = ptid_build (ptid_get_pid (ptid), 0, -1);
4795 /* Small optimization: if we already have a stop reply for
4796 this thread, no use in telling the stub we want this
4798 if (peek_stop_reply (ptid))
4804 write_ptid (p, endp, nptid);
4807 /* In non-stop, we get an immediate OK reply. The stop reply will
4808 come in asynchronously by notification. */
4810 getpkt (&rs->buf, &rs->buf_size, 0);
4811 if (strcmp (rs->buf, "OK") != 0)
4812 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
4815 /* All-stop version of target_stop. Sends a break or a ^C to stop the
4816 remote target. It is undefined which thread of which process
4817 reports the stop. */
4820 remote_stop_as (ptid_t ptid)
4822 struct remote_state *rs = get_remote_state ();
4824 rs->ctrlc_pending_p = 1;
4826 /* If the inferior is stopped already, but the core didn't know
4827 about it yet, just ignore the request. The cached wait status
4828 will be collected in remote_wait. */
4829 if (rs->cached_wait_status)
4832 /* Send interrupt_sequence to remote target. */
4833 send_interrupt_sequence ();
4836 /* This is the generic stop called via the target vector. When a target
4837 interrupt is requested, either by the command line or the GUI, we
4838 will eventually end up here. */
4841 remote_stop (ptid_t ptid)
4844 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
4847 remote_stop_ns (ptid);
4849 remote_stop_as (ptid);
4852 /* Ask the user what to do when an interrupt is received. */
4855 interrupt_query (void)
4857 target_terminal_ours ();
4859 if (target_can_async_p ())
4861 signal (SIGINT, handle_sigint);
4862 deprecated_throw_reason (RETURN_QUIT);
4866 if (query (_("Interrupted while waiting for the program.\n\
4867 Give up (and stop debugging it)? ")))
4870 deprecated_throw_reason (RETURN_QUIT);
4874 target_terminal_inferior ();
4877 /* Enable/disable target terminal ownership. Most targets can use
4878 terminal groups to control terminal ownership. Remote targets are
4879 different in that explicit transfer of ownership to/from GDB/target
4883 remote_terminal_inferior (void)
4885 if (!target_async_permitted)
4886 /* Nothing to do. */
4889 /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
4890 idempotent. The event-loop GDB talking to an asynchronous target
4891 with a synchronous command calls this function from both
4892 event-top.c and infrun.c/infcmd.c. Once GDB stops trying to
4893 transfer the terminal to the target when it shouldn't this guard
4895 if (!remote_async_terminal_ours_p)
4897 delete_file_handler (input_fd);
4898 remote_async_terminal_ours_p = 0;
4899 initialize_sigint_signal_handler ();
4900 /* NOTE: At this point we could also register our selves as the
4901 recipient of all input. Any characters typed could then be
4902 passed on down to the target. */
4906 remote_terminal_ours (void)
4908 if (!target_async_permitted)
4909 /* Nothing to do. */
4912 /* See FIXME in remote_terminal_inferior. */
4913 if (remote_async_terminal_ours_p)
4915 cleanup_sigint_signal_handler (NULL);
4916 add_file_handler (input_fd, stdin_event_handler, 0);
4917 remote_async_terminal_ours_p = 1;
4921 remote_console_output (char *msg)
4925 for (p = msg; p[0] && p[1]; p += 2)
4928 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
4932 fputs_unfiltered (tb, gdb_stdtarg);
4934 gdb_flush (gdb_stdtarg);
4937 typedef struct cached_reg
4940 gdb_byte data[MAX_REGISTER_SIZE];
4943 DEF_VEC_O(cached_reg_t);
4947 struct stop_reply *next;
4951 struct target_waitstatus ws;
4953 /* Expedited registers. This makes remote debugging a bit more
4954 efficient for those targets that provide critical registers as
4955 part of their normal status mechanism (as another roundtrip to
4956 fetch them is avoided). */
4957 VEC(cached_reg_t) *regcache;
4959 int stopped_by_watchpoint_p;
4960 CORE_ADDR watch_data_address;
4968 /* The list of already fetched and acknowledged stop events. */
4969 static struct stop_reply *stop_reply_queue;
4971 static struct stop_reply *
4972 stop_reply_xmalloc (void)
4974 struct stop_reply *r = XMALLOC (struct stop_reply);
4981 stop_reply_xfree (struct stop_reply *r)
4985 VEC_free (cached_reg_t, r->regcache);
4990 /* Discard all pending stop replies of inferior PID. If PID is -1,
4991 discard everything. */
4994 discard_pending_stop_replies (int pid)
4996 struct stop_reply *prev = NULL, *reply, *next;
4998 /* Discard the in-flight notification. */
4999 if (pending_stop_reply != NULL
5001 || ptid_get_pid (pending_stop_reply->ptid) == pid))
5003 stop_reply_xfree (pending_stop_reply);
5004 pending_stop_reply = NULL;
5007 /* Discard the stop replies we have already pulled with
5009 for (reply = stop_reply_queue; reply; reply = next)
5013 || ptid_get_pid (reply->ptid) == pid)
5015 if (reply == stop_reply_queue)
5016 stop_reply_queue = reply->next;
5018 prev->next = reply->next;
5020 stop_reply_xfree (reply);
5027 /* Cleanup wrapper. */
5030 do_stop_reply_xfree (void *arg)
5032 struct stop_reply *r = arg;
5034 stop_reply_xfree (r);
5037 /* Look for a queued stop reply belonging to PTID. If one is found,
5038 remove it from the queue, and return it. Returns NULL if none is
5039 found. If there are still queued events left to process, tell the
5040 event loop to get back to target_wait soon. */
5042 static struct stop_reply *
5043 queued_stop_reply (ptid_t ptid)
5045 struct stop_reply *it;
5046 struct stop_reply **it_link;
5048 it = stop_reply_queue;
5049 it_link = &stop_reply_queue;
5052 if (ptid_match (it->ptid, ptid))
5054 *it_link = it->next;
5059 it_link = &it->next;
5063 if (stop_reply_queue)
5064 /* There's still at least an event left. */
5065 mark_async_event_handler (remote_async_inferior_event_token);
5070 /* Push a fully parsed stop reply in the stop reply queue. Since we
5071 know that we now have at least one queued event left to pass to the
5072 core side, tell the event loop to get back to target_wait soon. */
5075 push_stop_reply (struct stop_reply *new_event)
5077 struct stop_reply *event;
5079 if (stop_reply_queue)
5081 for (event = stop_reply_queue;
5082 event && event->next;
5083 event = event->next)
5086 event->next = new_event;
5089 stop_reply_queue = new_event;
5091 mark_async_event_handler (remote_async_inferior_event_token);
5094 /* Returns true if we have a stop reply for PTID. */
5097 peek_stop_reply (ptid_t ptid)
5099 struct stop_reply *it;
5101 for (it = stop_reply_queue; it; it = it->next)
5102 if (ptid_equal (ptid, it->ptid))
5104 if (it->ws.kind == TARGET_WAITKIND_STOPPED)
5111 /* Parse the stop reply in BUF. Either the function succeeds, and the
5112 result is stored in EVENT, or throws an error. */
5115 remote_parse_stop_reply (char *buf, struct stop_reply *event)
5117 struct remote_arch_state *rsa = get_remote_arch_state ();
5121 event->ptid = null_ptid;
5122 event->ws.kind = TARGET_WAITKIND_IGNORE;
5123 event->ws.value.integer = 0;
5124 event->solibs_changed = 0;
5125 event->replay_event = 0;
5126 event->stopped_by_watchpoint_p = 0;
5127 event->regcache = NULL;
5132 case 'T': /* Status with PC, SP, FP, ... */
5133 /* Expedited reply, containing Signal, {regno, reg} repeat. */
5134 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
5136 n... = register number
5137 r... = register contents
5140 p = &buf[3]; /* after Txx */
5148 /* If the packet contains a register number, save it in
5149 pnum and set p1 to point to the character following it.
5150 Otherwise p1 points to p. */
5152 /* If this packet is an awatch packet, don't parse the 'a'
5153 as a register number. */
5155 if (strncmp (p, "awatch", strlen("awatch")) != 0
5156 && strncmp (p, "core", strlen ("core") != 0))
5158 /* Read the ``P'' register number. */
5159 pnum = strtol (p, &p_temp, 16);
5165 if (p1 == p) /* No register number present here. */
5167 p1 = strchr (p, ':');
5169 error (_("Malformed packet(a) (missing colon): %s\n\
5172 if (strncmp (p, "thread", p1 - p) == 0)
5173 event->ptid = read_ptid (++p1, &p);
5174 else if ((strncmp (p, "watch", p1 - p) == 0)
5175 || (strncmp (p, "rwatch", p1 - p) == 0)
5176 || (strncmp (p, "awatch", p1 - p) == 0))
5178 event->stopped_by_watchpoint_p = 1;
5179 p = unpack_varlen_hex (++p1, &addr);
5180 event->watch_data_address = (CORE_ADDR) addr;
5182 else if (strncmp (p, "library", p1 - p) == 0)
5186 while (*p_temp && *p_temp != ';')
5189 event->solibs_changed = 1;
5192 else if (strncmp (p, "replaylog", p1 - p) == 0)
5194 /* NO_HISTORY event.
5195 p1 will indicate "begin" or "end", but
5196 it makes no difference for now, so ignore it. */
5197 event->replay_event = 1;
5198 p_temp = strchr (p1 + 1, ';');
5202 else if (strncmp (p, "core", p1 - p) == 0)
5206 p = unpack_varlen_hex (++p1, &c);
5211 /* Silently skip unknown optional info. */
5212 p_temp = strchr (p1 + 1, ';');
5219 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
5220 cached_reg_t cached_reg;
5225 error (_("Malformed packet(b) (missing colon): %s\n\
5231 error (_("Remote sent bad register number %s: %s\n\
5233 hex_string (pnum), p, buf);
5235 cached_reg.num = reg->regnum;
5237 fieldsize = hex2bin (p, cached_reg.data,
5238 register_size (target_gdbarch,
5241 if (fieldsize < register_size (target_gdbarch,
5243 warning (_("Remote reply is too short: %s"), buf);
5245 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
5249 error (_("Remote register badly formatted: %s\nhere: %s"),
5254 case 'S': /* Old style status, just signal only. */
5255 if (event->solibs_changed)
5256 event->ws.kind = TARGET_WAITKIND_LOADED;
5257 else if (event->replay_event)
5258 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
5261 event->ws.kind = TARGET_WAITKIND_STOPPED;
5262 event->ws.value.sig = (enum target_signal)
5263 (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
5266 case 'W': /* Target exited. */
5273 /* GDB used to accept only 2 hex chars here. Stubs should
5274 only send more if they detect GDB supports multi-process
5276 p = unpack_varlen_hex (&buf[1], &value);
5280 /* The remote process exited. */
5281 event->ws.kind = TARGET_WAITKIND_EXITED;
5282 event->ws.value.integer = value;
5286 /* The remote process exited with a signal. */
5287 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
5288 event->ws.value.sig = (enum target_signal) value;
5291 /* If no process is specified, assume inferior_ptid. */
5292 pid = ptid_get_pid (inferior_ptid);
5301 else if (strncmp (p,
5302 "process:", sizeof ("process:") - 1) == 0)
5306 p += sizeof ("process:") - 1;
5307 unpack_varlen_hex (p, &upid);
5311 error (_("unknown stop reply packet: %s"), buf);
5314 error (_("unknown stop reply packet: %s"), buf);
5315 event->ptid = pid_to_ptid (pid);
5320 if (non_stop && ptid_equal (event->ptid, null_ptid))
5321 error (_("No process or thread specified in stop reply: %s"), buf);
5324 /* When the stub wants to tell GDB about a new stop reply, it sends a
5325 stop notification (%Stop). Those can come it at any time, hence,
5326 we have to make sure that any pending putpkt/getpkt sequence we're
5327 making is finished, before querying the stub for more events with
5328 vStopped. E.g., if we started a vStopped sequence immediatelly
5329 upon receiving the %Stop notification, something like this could
5337 1.6) <-- (registers reply to step #1.3)
5339 Obviously, the reply in step #1.6 would be unexpected to a vStopped
5342 To solve this, whenever we parse a %Stop notification sucessfully,
5343 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
5344 doing whatever we were doing:
5350 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
5351 2.5) <-- (registers reply to step #2.3)
5353 Eventualy after step #2.5, we return to the event loop, which
5354 notices there's an event on the
5355 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
5356 associated callback --- the function below. At this point, we're
5357 always safe to start a vStopped sequence. :
5360 2.7) <-- T05 thread:2
5366 remote_get_pending_stop_replies (void)
5368 struct remote_state *rs = get_remote_state ();
5370 if (pending_stop_reply)
5373 putpkt ("vStopped");
5375 /* Now we can rely on it. */
5376 push_stop_reply (pending_stop_reply);
5377 pending_stop_reply = NULL;
5381 getpkt (&rs->buf, &rs->buf_size, 0);
5382 if (strcmp (rs->buf, "OK") == 0)
5386 struct cleanup *old_chain;
5387 struct stop_reply *stop_reply = stop_reply_xmalloc ();
5389 old_chain = make_cleanup (do_stop_reply_xfree, stop_reply);
5390 remote_parse_stop_reply (rs->buf, stop_reply);
5393 putpkt ("vStopped");
5395 if (stop_reply->ws.kind != TARGET_WAITKIND_IGNORE)
5397 /* Now we can rely on it. */
5398 discard_cleanups (old_chain);
5399 push_stop_reply (stop_reply);
5402 /* We got an unknown stop reply. */
5403 do_cleanups (old_chain);
5410 /* Called when it is decided that STOP_REPLY holds the info of the
5411 event that is to be returned to the core. This function always
5412 destroys STOP_REPLY. */
5415 process_stop_reply (struct stop_reply *stop_reply,
5416 struct target_waitstatus *status)
5420 *status = stop_reply->ws;
5421 ptid = stop_reply->ptid;
5423 /* If no thread/process was reported by the stub, assume the current
5425 if (ptid_equal (ptid, null_ptid))
5426 ptid = inferior_ptid;
5428 if (status->kind != TARGET_WAITKIND_EXITED
5429 && status->kind != TARGET_WAITKIND_SIGNALLED)
5431 /* Expedited registers. */
5432 if (stop_reply->regcache)
5434 struct regcache *regcache
5435 = get_thread_arch_regcache (ptid, target_gdbarch);
5440 VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
5442 regcache_raw_supply (regcache, reg->num, reg->data);
5443 VEC_free (cached_reg_t, stop_reply->regcache);
5446 remote_stopped_by_watchpoint_p = stop_reply->stopped_by_watchpoint_p;
5447 remote_watch_data_address = stop_reply->watch_data_address;
5449 remote_notice_new_inferior (ptid, 0);
5450 demand_private_info (ptid)->core = stop_reply->core;
5453 stop_reply_xfree (stop_reply);
5457 /* The non-stop mode version of target_wait. */
5460 remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
5462 struct remote_state *rs = get_remote_state ();
5463 struct stop_reply *stop_reply;
5466 /* If in non-stop mode, get out of getpkt even if a
5467 notification is received. */
5469 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
5476 case 'E': /* Error of some sort. */
5477 /* We're out of sync with the target now. Did it continue
5478 or not? We can't tell which thread it was in non-stop,
5479 so just ignore this. */
5480 warning (_("Remote failure reply: %s"), rs->buf);
5482 case 'O': /* Console output. */
5483 remote_console_output (rs->buf + 1);
5486 warning (_("Invalid remote reply: %s"), rs->buf);
5490 /* Acknowledge a pending stop reply that may have arrived in the
5492 if (pending_stop_reply != NULL)
5493 remote_get_pending_stop_replies ();
5495 /* If indeed we noticed a stop reply, we're done. */
5496 stop_reply = queued_stop_reply (ptid);
5497 if (stop_reply != NULL)
5498 return process_stop_reply (stop_reply, status);
5500 /* Still no event. If we're just polling for an event, then
5501 return to the event loop. */
5502 if (options & TARGET_WNOHANG)
5504 status->kind = TARGET_WAITKIND_IGNORE;
5505 return minus_one_ptid;
5508 /* Otherwise do a blocking wait. */
5509 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
5514 /* Wait until the remote machine stops, then return, storing status in
5515 STATUS just as `wait' would. */
5518 remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
5520 struct remote_state *rs = get_remote_state ();
5521 ptid_t event_ptid = null_ptid;
5523 struct stop_reply *stop_reply;
5527 status->kind = TARGET_WAITKIND_IGNORE;
5528 status->value.integer = 0;
5530 stop_reply = queued_stop_reply (ptid);
5531 if (stop_reply != NULL)
5532 return process_stop_reply (stop_reply, status);
5534 if (rs->cached_wait_status)
5535 /* Use the cached wait status, but only once. */
5536 rs->cached_wait_status = 0;
5541 if (!target_is_async_p ())
5543 ofunc = signal (SIGINT, remote_interrupt);
5544 /* If the user hit C-c before this packet, or between packets,
5545 pretend that it was hit right here. */
5549 remote_interrupt (SIGINT);
5553 /* FIXME: cagney/1999-09-27: If we're in async mode we should
5554 _never_ wait for ever -> test on target_is_async_p().
5555 However, before we do that we need to ensure that the caller
5556 knows how to take the target into/out of async mode. */
5557 ret = getpkt_sane (&rs->buf, &rs->buf_size, wait_forever_enabled_p);
5558 if (!target_is_async_p ())
5559 signal (SIGINT, ofunc);
5564 remote_stopped_by_watchpoint_p = 0;
5566 /* We got something. */
5567 rs->waiting_for_stop_reply = 0;
5569 /* Assume that the target has acknowledged Ctrl-C unless we receive
5570 an 'F' or 'O' packet. */
5571 if (buf[0] != 'F' && buf[0] != 'O')
5572 rs->ctrlc_pending_p = 0;
5576 case 'E': /* Error of some sort. */
5577 /* We're out of sync with the target now. Did it continue or
5578 not? Not is more likely, so report a stop. */
5579 warning (_("Remote failure reply: %s"), buf);
5580 status->kind = TARGET_WAITKIND_STOPPED;
5581 status->value.sig = TARGET_SIGNAL_0;
5583 case 'F': /* File-I/O request. */
5584 remote_fileio_request (buf, rs->ctrlc_pending_p);
5585 rs->ctrlc_pending_p = 0;
5587 case 'T': case 'S': case 'X': case 'W':
5589 struct stop_reply *stop_reply;
5590 struct cleanup *old_chain;
5592 stop_reply = stop_reply_xmalloc ();
5593 old_chain = make_cleanup (do_stop_reply_xfree, stop_reply);
5594 remote_parse_stop_reply (buf, stop_reply);
5595 discard_cleanups (old_chain);
5596 event_ptid = process_stop_reply (stop_reply, status);
5599 case 'O': /* Console output. */
5600 remote_console_output (buf + 1);
5602 /* The target didn't really stop; keep waiting. */
5603 rs->waiting_for_stop_reply = 1;
5607 if (last_sent_signal != TARGET_SIGNAL_0)
5609 /* Zero length reply means that we tried 'S' or 'C' and the
5610 remote system doesn't support it. */
5611 target_terminal_ours_for_output ();
5613 ("Can't send signals to this remote system. %s not sent.\n",
5614 target_signal_to_name (last_sent_signal));
5615 last_sent_signal = TARGET_SIGNAL_0;
5616 target_terminal_inferior ();
5618 strcpy ((char *) buf, last_sent_step ? "s" : "c");
5619 putpkt ((char *) buf);
5621 /* We just told the target to resume, so a stop reply is in
5623 rs->waiting_for_stop_reply = 1;
5626 /* else fallthrough */
5628 warning (_("Invalid remote reply: %s"), buf);
5630 rs->waiting_for_stop_reply = 1;
5634 if (status->kind == TARGET_WAITKIND_IGNORE)
5636 /* Nothing interesting happened. If we're doing a non-blocking
5637 poll, we're done. Otherwise, go back to waiting. */
5638 if (options & TARGET_WNOHANG)
5639 return minus_one_ptid;
5643 else if (status->kind != TARGET_WAITKIND_EXITED
5644 && status->kind != TARGET_WAITKIND_SIGNALLED)
5646 if (!ptid_equal (event_ptid, null_ptid))
5647 record_currthread (event_ptid);
5649 event_ptid = inferior_ptid;
5652 /* A process exit. Invalidate our notion of current thread. */
5653 record_currthread (minus_one_ptid);
5658 /* Wait until the remote machine stops, then return, storing status in
5659 STATUS just as `wait' would. */
5662 remote_wait (struct target_ops *ops,
5663 ptid_t ptid, struct target_waitstatus *status, int options)
5668 event_ptid = remote_wait_ns (ptid, status, options);
5670 event_ptid = remote_wait_as (ptid, status, options);
5672 if (target_can_async_p ())
5674 /* If there are are events left in the queue tell the event loop
5676 if (stop_reply_queue)
5677 mark_async_event_handler (remote_async_inferior_event_token);
5683 /* Fetch a single register using a 'p' packet. */
5686 fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
5688 struct remote_state *rs = get_remote_state ();
5690 char regp[MAX_REGISTER_SIZE];
5693 if (remote_protocol_packets[PACKET_p].support == PACKET_DISABLE)
5696 if (reg->pnum == -1)
5701 p += hexnumstr (p, reg->pnum);
5704 getpkt (&rs->buf, &rs->buf_size, 0);
5708 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
5712 case PACKET_UNKNOWN:
5715 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
5716 gdbarch_register_name (get_regcache_arch (regcache),
5721 /* If this register is unfetchable, tell the regcache. */
5724 regcache_raw_supply (regcache, reg->regnum, NULL);
5728 /* Otherwise, parse and supply the value. */
5734 error (_("fetch_register_using_p: early buf termination"));
5736 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
5739 regcache_raw_supply (regcache, reg->regnum, regp);
5743 /* Fetch the registers included in the target's 'g' packet. */
5746 send_g_packet (void)
5748 struct remote_state *rs = get_remote_state ();
5751 sprintf (rs->buf, "g");
5752 remote_send (&rs->buf, &rs->buf_size);
5754 /* We can get out of synch in various cases. If the first character
5755 in the buffer is not a hex character, assume that has happened
5756 and try to fetch another packet to read. */
5757 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
5758 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
5759 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
5760 && rs->buf[0] != 'x') /* New: unavailable register value. */
5763 fprintf_unfiltered (gdb_stdlog,
5764 "Bad register packet; fetching a new packet\n");
5765 getpkt (&rs->buf, &rs->buf_size, 0);
5768 buf_len = strlen (rs->buf);
5770 /* Sanity check the received packet. */
5771 if (buf_len % 2 != 0)
5772 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
5778 process_g_packet (struct regcache *regcache)
5780 struct gdbarch *gdbarch = get_regcache_arch (regcache);
5781 struct remote_state *rs = get_remote_state ();
5782 struct remote_arch_state *rsa = get_remote_arch_state ();
5787 buf_len = strlen (rs->buf);
5789 /* Further sanity checks, with knowledge of the architecture. */
5790 if (buf_len > 2 * rsa->sizeof_g_packet)
5791 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
5793 /* Save the size of the packet sent to us by the target. It is used
5794 as a heuristic when determining the max size of packets that the
5795 target can safely receive. */
5796 if (rsa->actual_register_packet_size == 0)
5797 rsa->actual_register_packet_size = buf_len;
5799 /* If this is smaller than we guessed the 'g' packet would be,
5800 update our records. A 'g' reply that doesn't include a register's
5801 value implies either that the register is not available, or that
5802 the 'p' packet must be used. */
5803 if (buf_len < 2 * rsa->sizeof_g_packet)
5805 rsa->sizeof_g_packet = buf_len / 2;
5807 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
5809 if (rsa->regs[i].pnum == -1)
5812 if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
5813 rsa->regs[i].in_g_packet = 0;
5815 rsa->regs[i].in_g_packet = 1;
5819 regs = alloca (rsa->sizeof_g_packet);
5821 /* Unimplemented registers read as all bits zero. */
5822 memset (regs, 0, rsa->sizeof_g_packet);
5824 /* Reply describes registers byte by byte, each byte encoded as two
5825 hex characters. Suck them all up, then supply them to the
5826 register cacheing/storage mechanism. */
5829 for (i = 0; i < rsa->sizeof_g_packet; i++)
5831 if (p[0] == 0 || p[1] == 0)
5832 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
5833 internal_error (__FILE__, __LINE__,
5834 _("unexpected end of 'g' packet reply"));
5836 if (p[0] == 'x' && p[1] == 'x')
5837 regs[i] = 0; /* 'x' */
5839 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
5843 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
5845 struct packet_reg *r = &rsa->regs[i];
5849 if (r->offset * 2 >= strlen (rs->buf))
5850 /* This shouldn't happen - we adjusted in_g_packet above. */
5851 internal_error (__FILE__, __LINE__,
5852 _("unexpected end of 'g' packet reply"));
5853 else if (rs->buf[r->offset * 2] == 'x')
5855 gdb_assert (r->offset * 2 < strlen (rs->buf));
5856 /* The register isn't available, mark it as such (at
5857 the same time setting the value to zero). */
5858 regcache_raw_supply (regcache, r->regnum, NULL);
5861 regcache_raw_supply (regcache, r->regnum,
5868 fetch_registers_using_g (struct regcache *regcache)
5871 process_g_packet (regcache);
5874 /* Make the remote selected traceframe match GDB's selected
5878 set_remote_traceframe (void)
5882 if (remote_traceframe_number == get_traceframe_number ())
5885 /* Avoid recursion, remote_trace_find calls us again. */
5886 remote_traceframe_number = get_traceframe_number ();
5888 newnum = target_trace_find (tfind_number,
5889 get_traceframe_number (), 0, 0, NULL);
5891 /* Should not happen. If it does, all bets are off. */
5892 if (newnum != get_traceframe_number ())
5893 warning (_("could not set remote traceframe"));
5897 remote_fetch_registers (struct target_ops *ops,
5898 struct regcache *regcache, int regnum)
5900 struct remote_arch_state *rsa = get_remote_arch_state ();
5903 set_remote_traceframe ();
5904 set_general_thread (inferior_ptid);
5908 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
5910 gdb_assert (reg != NULL);
5912 /* If this register might be in the 'g' packet, try that first -
5913 we are likely to read more than one register. If this is the
5914 first 'g' packet, we might be overly optimistic about its
5915 contents, so fall back to 'p'. */
5916 if (reg->in_g_packet)
5918 fetch_registers_using_g (regcache);
5919 if (reg->in_g_packet)
5923 if (fetch_register_using_p (regcache, reg))
5926 /* This register is not available. */
5927 regcache_raw_supply (regcache, reg->regnum, NULL);
5932 fetch_registers_using_g (regcache);
5934 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
5935 if (!rsa->regs[i].in_g_packet)
5936 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
5938 /* This register is not available. */
5939 regcache_raw_supply (regcache, i, NULL);
5943 /* Prepare to store registers. Since we may send them all (using a
5944 'G' request), we have to read out the ones we don't want to change
5948 remote_prepare_to_store (struct regcache *regcache)
5950 struct remote_arch_state *rsa = get_remote_arch_state ();
5952 gdb_byte buf[MAX_REGISTER_SIZE];
5954 /* Make sure the entire registers array is valid. */
5955 switch (remote_protocol_packets[PACKET_P].support)
5957 case PACKET_DISABLE:
5958 case PACKET_SUPPORT_UNKNOWN:
5959 /* Make sure all the necessary registers are cached. */
5960 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
5961 if (rsa->regs[i].in_g_packet)
5962 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
5969 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
5970 packet was not recognized. */
5973 store_register_using_P (const struct regcache *regcache,
5974 struct packet_reg *reg)
5976 struct gdbarch *gdbarch = get_regcache_arch (regcache);
5977 struct remote_state *rs = get_remote_state ();
5978 /* Try storing a single register. */
5979 char *buf = rs->buf;
5980 gdb_byte regp[MAX_REGISTER_SIZE];
5983 if (remote_protocol_packets[PACKET_P].support == PACKET_DISABLE)
5986 if (reg->pnum == -1)
5989 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
5990 p = buf + strlen (buf);
5991 regcache_raw_collect (regcache, reg->regnum, regp);
5992 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
5994 getpkt (&rs->buf, &rs->buf_size, 0);
5996 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
6001 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
6002 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
6003 case PACKET_UNKNOWN:
6006 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
6010 /* Store register REGNUM, or all registers if REGNUM == -1, from the
6011 contents of the register cache buffer. FIXME: ignores errors. */
6014 store_registers_using_G (const struct regcache *regcache)
6016 struct remote_state *rs = get_remote_state ();
6017 struct remote_arch_state *rsa = get_remote_arch_state ();
6021 /* Extract all the registers in the regcache copying them into a
6026 regs = alloca (rsa->sizeof_g_packet);
6027 memset (regs, 0, rsa->sizeof_g_packet);
6028 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6030 struct packet_reg *r = &rsa->regs[i];
6033 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
6037 /* Command describes registers byte by byte,
6038 each byte encoded as two hex characters. */
6041 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
6043 bin2hex (regs, p, rsa->sizeof_g_packet);
6045 getpkt (&rs->buf, &rs->buf_size, 0);
6046 if (packet_check_result (rs->buf) == PACKET_ERROR)
6047 error (_("Could not write registers; remote failure reply '%s'"),
6051 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
6052 of the register cache buffer. FIXME: ignores errors. */
6055 remote_store_registers (struct target_ops *ops,
6056 struct regcache *regcache, int regnum)
6058 struct remote_arch_state *rsa = get_remote_arch_state ();
6061 set_remote_traceframe ();
6062 set_general_thread (inferior_ptid);
6066 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
6068 gdb_assert (reg != NULL);
6070 /* Always prefer to store registers using the 'P' packet if
6071 possible; we often change only a small number of registers.
6072 Sometimes we change a larger number; we'd need help from a
6073 higher layer to know to use 'G'. */
6074 if (store_register_using_P (regcache, reg))
6077 /* For now, don't complain if we have no way to write the
6078 register. GDB loses track of unavailable registers too
6079 easily. Some day, this may be an error. We don't have
6080 any way to read the register, either... */
6081 if (!reg->in_g_packet)
6084 store_registers_using_G (regcache);
6088 store_registers_using_G (regcache);
6090 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6091 if (!rsa->regs[i].in_g_packet)
6092 if (!store_register_using_P (regcache, &rsa->regs[i]))
6093 /* See above for why we do not issue an error here. */
6098 /* Return the number of hex digits in num. */
6101 hexnumlen (ULONGEST num)
6105 for (i = 0; num != 0; i++)
6111 /* Set BUF to the minimum number of hex digits representing NUM. */
6114 hexnumstr (char *buf, ULONGEST num)
6116 int len = hexnumlen (num);
6118 return hexnumnstr (buf, num, len);
6122 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
6125 hexnumnstr (char *buf, ULONGEST num, int width)
6131 for (i = width - 1; i >= 0; i--)
6133 buf[i] = "0123456789abcdef"[(num & 0xf)];
6140 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
6143 remote_address_masked (CORE_ADDR addr)
6145 int address_size = remote_address_size;
6147 /* If "remoteaddresssize" was not set, default to target address size. */
6149 address_size = gdbarch_addr_bit (target_gdbarch);
6151 if (address_size > 0
6152 && address_size < (sizeof (ULONGEST) * 8))
6154 /* Only create a mask when that mask can safely be constructed
6155 in a ULONGEST variable. */
6158 mask = (mask << address_size) - 1;
6164 /* Convert BUFFER, binary data at least LEN bytes long, into escaped
6165 binary data in OUT_BUF. Set *OUT_LEN to the length of the data
6166 encoded in OUT_BUF, and return the number of bytes in OUT_BUF
6167 (which may be more than *OUT_LEN due to escape characters). The
6168 total number of bytes in the output buffer will be at most
6172 remote_escape_output (const gdb_byte *buffer, int len,
6173 gdb_byte *out_buf, int *out_len,
6176 int input_index, output_index;
6179 for (input_index = 0; input_index < len; input_index++)
6181 gdb_byte b = buffer[input_index];
6183 if (b == '$' || b == '#' || b == '}')
6185 /* These must be escaped. */
6186 if (output_index + 2 > out_maxlen)
6188 out_buf[output_index++] = '}';
6189 out_buf[output_index++] = b ^ 0x20;
6193 if (output_index + 1 > out_maxlen)
6195 out_buf[output_index++] = b;
6199 *out_len = input_index;
6200 return output_index;
6203 /* Convert BUFFER, escaped data LEN bytes long, into binary data
6204 in OUT_BUF. Return the number of bytes written to OUT_BUF.
6205 Raise an error if the total number of bytes exceeds OUT_MAXLEN.
6207 This function reverses remote_escape_output. It allows more
6208 escaped characters than that function does, in particular because
6209 '*' must be escaped to avoid the run-length encoding processing
6210 in reading packets. */
6213 remote_unescape_input (const gdb_byte *buffer, int len,
6214 gdb_byte *out_buf, int out_maxlen)
6216 int input_index, output_index;
6221 for (input_index = 0; input_index < len; input_index++)
6223 gdb_byte b = buffer[input_index];
6225 if (output_index + 1 > out_maxlen)
6227 warning (_("Received too much data from remote target;"
6228 " ignoring overflow."));
6229 return output_index;
6234 out_buf[output_index++] = b ^ 0x20;
6240 out_buf[output_index++] = b;
6244 error (_("Unmatched escape character in target response."));
6246 return output_index;
6249 /* Determine whether the remote target supports binary downloading.
6250 This is accomplished by sending a no-op memory write of zero length
6251 to the target at the specified address. It does not suffice to send
6252 the whole packet, since many stubs strip the eighth bit and
6253 subsequently compute a wrong checksum, which causes real havoc with
6256 NOTE: This can still lose if the serial line is not eight-bit
6257 clean. In cases like this, the user should clear "remote
6261 check_binary_download (CORE_ADDR addr)
6263 struct remote_state *rs = get_remote_state ();
6265 switch (remote_protocol_packets[PACKET_X].support)
6267 case PACKET_DISABLE:
6271 case PACKET_SUPPORT_UNKNOWN:
6277 p += hexnumstr (p, (ULONGEST) addr);
6279 p += hexnumstr (p, (ULONGEST) 0);
6283 putpkt_binary (rs->buf, (int) (p - rs->buf));
6284 getpkt (&rs->buf, &rs->buf_size, 0);
6286 if (rs->buf[0] == '\0')
6289 fprintf_unfiltered (gdb_stdlog,
6290 "binary downloading NOT "
6291 "supported by target\n");
6292 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
6297 fprintf_unfiltered (gdb_stdlog,
6298 "binary downloading supported by target\n");
6299 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
6306 /* Write memory data directly to the remote machine.
6307 This does not inform the data cache; the data cache uses this.
6308 HEADER is the starting part of the packet.
6309 MEMADDR is the address in the remote memory space.
6310 MYADDR is the address of the buffer in our space.
6311 LEN is the number of bytes.
6312 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
6313 should send data as binary ('X'), or hex-encoded ('M').
6315 The function creates packet of the form
6316 <HEADER><ADDRESS>,<LENGTH>:<DATA>
6318 where encoding of <DATA> is termined by PACKET_FORMAT.
6320 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
6323 Returns the number of bytes transferred, or 0 (setting errno) for
6324 error. Only transfer a single packet. */
6327 remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
6328 const gdb_byte *myaddr, int len,
6329 char packet_format, int use_length)
6331 struct remote_state *rs = get_remote_state ();
6341 if (packet_format != 'X' && packet_format != 'M')
6342 internal_error (__FILE__, __LINE__,
6343 _("remote_write_bytes_aux: bad packet format"));
6348 payload_size = get_memory_write_packet_size ();
6350 /* The packet buffer will be large enough for the payload;
6351 get_memory_packet_size ensures this. */
6354 /* Compute the size of the actual payload by subtracting out the
6355 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
6357 payload_size -= strlen ("$,:#NN");
6359 /* The comma won't be used. */
6361 header_length = strlen (header);
6362 payload_size -= header_length;
6363 payload_size -= hexnumlen (memaddr);
6365 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
6367 strcat (rs->buf, header);
6368 p = rs->buf + strlen (header);
6370 /* Compute a best guess of the number of bytes actually transfered. */
6371 if (packet_format == 'X')
6373 /* Best guess at number of bytes that will fit. */
6374 todo = min (len, payload_size);
6376 payload_size -= hexnumlen (todo);
6377 todo = min (todo, payload_size);
6381 /* Num bytes that will fit. */
6382 todo = min (len, payload_size / 2);
6384 payload_size -= hexnumlen (todo);
6385 todo = min (todo, payload_size / 2);
6389 internal_error (__FILE__, __LINE__,
6390 _("minimum packet size too small to write data"));
6392 /* If we already need another packet, then try to align the end
6393 of this packet to a useful boundary. */
6394 if (todo > 2 * REMOTE_ALIGN_WRITES && todo < len)
6395 todo = ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
6397 /* Append "<memaddr>". */
6398 memaddr = remote_address_masked (memaddr);
6399 p += hexnumstr (p, (ULONGEST) memaddr);
6406 /* Append <len>. Retain the location/size of <len>. It may need to
6407 be adjusted once the packet body has been created. */
6409 plenlen = hexnumstr (p, (ULONGEST) todo);
6417 /* Append the packet body. */
6418 if (packet_format == 'X')
6420 /* Binary mode. Send target system values byte by byte, in
6421 increasing byte addresses. Only escape certain critical
6423 payload_length = remote_escape_output (myaddr, todo, p, &nr_bytes,
6426 /* If not all TODO bytes fit, then we'll need another packet. Make
6427 a second try to keep the end of the packet aligned. Don't do
6428 this if the packet is tiny. */
6429 if (nr_bytes < todo && nr_bytes > 2 * REMOTE_ALIGN_WRITES)
6433 new_nr_bytes = (((memaddr + nr_bytes) & ~(REMOTE_ALIGN_WRITES - 1))
6435 if (new_nr_bytes != nr_bytes)
6436 payload_length = remote_escape_output (myaddr, new_nr_bytes,
6441 p += payload_length;
6442 if (use_length && nr_bytes < todo)
6444 /* Escape chars have filled up the buffer prematurely,
6445 and we have actually sent fewer bytes than planned.
6446 Fix-up the length field of the packet. Use the same
6447 number of characters as before. */
6448 plen += hexnumnstr (plen, (ULONGEST) nr_bytes, plenlen);
6449 *plen = ':'; /* overwrite \0 from hexnumnstr() */
6454 /* Normal mode: Send target system values byte by byte, in
6455 increasing byte addresses. Each byte is encoded as a two hex
6457 nr_bytes = bin2hex (myaddr, p, todo);
6461 putpkt_binary (rs->buf, (int) (p - rs->buf));
6462 getpkt (&rs->buf, &rs->buf_size, 0);
6464 if (rs->buf[0] == 'E')
6466 /* There is no correspondance between what the remote protocol
6467 uses for errors and errno codes. We would like a cleaner way
6468 of representing errors (big enough to include errno codes,
6469 bfd_error codes, and others). But for now just return EIO. */
6474 /* Return NR_BYTES, not TODO, in case escape chars caused us to send
6475 fewer bytes than we'd planned. */
6479 /* Write memory data directly to the remote machine.
6480 This does not inform the data cache; the data cache uses this.
6481 MEMADDR is the address in the remote memory space.
6482 MYADDR is the address of the buffer in our space.
6483 LEN is the number of bytes.
6485 Returns number of bytes transferred, or 0 (setting errno) for
6486 error. Only transfer a single packet. */
6489 remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, int len)
6491 char *packet_format = 0;
6493 /* Check whether the target supports binary download. */
6494 check_binary_download (memaddr);
6496 switch (remote_protocol_packets[PACKET_X].support)
6499 packet_format = "X";
6501 case PACKET_DISABLE:
6502 packet_format = "M";
6504 case PACKET_SUPPORT_UNKNOWN:
6505 internal_error (__FILE__, __LINE__,
6506 _("remote_write_bytes: bad internal state"));
6508 internal_error (__FILE__, __LINE__, _("bad switch"));
6511 return remote_write_bytes_aux (packet_format,
6512 memaddr, myaddr, len, packet_format[0], 1);
6515 /* Read memory data directly from the remote machine.
6516 This does not use the data cache; the data cache uses this.
6517 MEMADDR is the address in the remote memory space.
6518 MYADDR is the address of the buffer in our space.
6519 LEN is the number of bytes.
6521 Returns number of bytes transferred, or 0 for error. */
6524 remote_read_bytes (CORE_ADDR memaddr, gdb_byte *myaddr, int len)
6526 struct remote_state *rs = get_remote_state ();
6527 int max_buf_size; /* Max size of packet output buffer. */
6535 max_buf_size = get_memory_read_packet_size ();
6536 /* The packet buffer will be large enough for the payload;
6537 get_memory_packet_size ensures this. */
6539 /* Number if bytes that will fit. */
6540 todo = min (len, max_buf_size / 2);
6542 /* Construct "m"<memaddr>","<len>". */
6543 memaddr = remote_address_masked (memaddr);
6546 p += hexnumstr (p, (ULONGEST) memaddr);
6548 p += hexnumstr (p, (ULONGEST) todo);
6551 getpkt (&rs->buf, &rs->buf_size, 0);
6552 if (rs->buf[0] == 'E'
6553 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
6554 && rs->buf[3] == '\0')
6556 /* There is no correspondance between what the remote protocol
6557 uses for errors and errno codes. We would like a cleaner way
6558 of representing errors (big enough to include errno codes,
6559 bfd_error codes, and others). But for now just return
6564 /* Reply describes memory byte by byte, each byte encoded as two hex
6567 i = hex2bin (p, myaddr, todo);
6568 /* Return what we have. Let higher layers handle partial reads. */
6573 /* Remote notification handler. */
6576 handle_notification (char *buf, size_t length)
6578 if (strncmp (buf, "Stop:", 5) == 0)
6580 if (pending_stop_reply)
6582 /* We've already parsed the in-flight stop-reply, but the
6583 stub for some reason thought we didn't, possibly due to
6584 timeout on its side. Just ignore it. */
6586 fprintf_unfiltered (gdb_stdlog, "ignoring resent notification\n");
6590 struct cleanup *old_chain;
6591 struct stop_reply *reply = stop_reply_xmalloc ();
6593 old_chain = make_cleanup (do_stop_reply_xfree, reply);
6595 remote_parse_stop_reply (buf + 5, reply);
6597 discard_cleanups (old_chain);
6599 /* Be careful to only set it after parsing, since an error
6600 may be thrown then. */
6601 pending_stop_reply = reply;
6603 /* Notify the event loop there's a stop reply to acknowledge
6604 and that there may be more events to fetch. */
6605 mark_async_event_handler (remote_async_get_pending_events_token);
6608 fprintf_unfiltered (gdb_stdlog, "stop notification captured\n");
6612 /* We ignore notifications we don't recognize, for compatibility
6613 with newer stubs. */
6618 /* Read or write LEN bytes from inferior memory at MEMADDR,
6619 transferring to or from debugger address BUFFER. Write to inferior
6620 if SHOULD_WRITE is nonzero. Returns length of data written or
6621 read; 0 for error. TARGET is unused. */
6624 remote_xfer_memory (CORE_ADDR mem_addr, gdb_byte *buffer, int mem_len,
6625 int should_write, struct mem_attrib *attrib,
6626 struct target_ops *target)
6630 set_remote_traceframe ();
6631 set_general_thread (inferior_ptid);
6634 res = remote_write_bytes (mem_addr, buffer, mem_len);
6636 res = remote_read_bytes (mem_addr, buffer, mem_len);
6641 /* Sends a packet with content determined by the printf format string
6642 FORMAT and the remaining arguments, then gets the reply. Returns
6643 whether the packet was a success, a failure, or unknown. */
6645 static enum packet_result
6646 remote_send_printf (const char *format, ...)
6648 struct remote_state *rs = get_remote_state ();
6649 int max_size = get_remote_packet_size ();
6652 va_start (ap, format);
6655 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
6656 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
6658 if (putpkt (rs->buf) < 0)
6659 error (_("Communication problem with target."));
6662 getpkt (&rs->buf, &rs->buf_size, 0);
6664 return packet_check_result (rs->buf);
6668 restore_remote_timeout (void *p)
6670 int value = *(int *)p;
6672 remote_timeout = value;
6675 /* Flash writing can take quite some time. We'll set
6676 effectively infinite timeout for flash operations.
6677 In future, we'll need to decide on a better approach. */
6678 static const int remote_flash_timeout = 1000;
6681 remote_flash_erase (struct target_ops *ops,
6682 ULONGEST address, LONGEST length)
6684 int addr_size = gdbarch_addr_bit (target_gdbarch) / 8;
6685 int saved_remote_timeout = remote_timeout;
6686 enum packet_result ret;
6687 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
6688 &saved_remote_timeout);
6690 remote_timeout = remote_flash_timeout;
6692 ret = remote_send_printf ("vFlashErase:%s,%s",
6693 phex (address, addr_size),
6697 case PACKET_UNKNOWN:
6698 error (_("Remote target does not support flash erase"));
6700 error (_("Error erasing flash with vFlashErase packet"));
6705 do_cleanups (back_to);
6709 remote_flash_write (struct target_ops *ops,
6710 ULONGEST address, LONGEST length,
6711 const gdb_byte *data)
6713 int saved_remote_timeout = remote_timeout;
6715 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
6716 &saved_remote_timeout);
6718 remote_timeout = remote_flash_timeout;
6719 ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length, 'X', 0);
6720 do_cleanups (back_to);
6726 remote_flash_done (struct target_ops *ops)
6728 int saved_remote_timeout = remote_timeout;
6730 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
6731 &saved_remote_timeout);
6733 remote_timeout = remote_flash_timeout;
6734 ret = remote_send_printf ("vFlashDone");
6735 do_cleanups (back_to);
6739 case PACKET_UNKNOWN:
6740 error (_("Remote target does not support vFlashDone"));
6742 error (_("Error finishing flash operation"));
6749 remote_files_info (struct target_ops *ignore)
6751 puts_filtered ("Debugging a target over a serial line.\n");
6754 /* Stuff for dealing with the packets which are part of this protocol.
6755 See comment at top of file for details. */
6757 /* Read a single character from the remote end. */
6760 readchar (int timeout)
6764 ch = serial_readchar (remote_desc, timeout);
6769 switch ((enum serial_rc) ch)
6773 error (_("Remote connection closed"));
6777 perror_with_name (_("Remote communication error. "
6778 "Target disconnected."));
6780 case SERIAL_TIMEOUT:
6786 /* Send the command in *BUF to the remote machine, and read the reply
6787 into *BUF. Report an error if we get an error reply. Resize
6788 *BUF using xrealloc if necessary to hold the result, and update
6792 remote_send (char **buf,
6796 getpkt (buf, sizeof_buf, 0);
6798 if ((*buf)[0] == 'E')
6799 error (_("Remote failure reply: %s"), *buf);
6802 /* Return a pointer to an xmalloc'ed string representing an escaped
6803 version of BUF, of len N. E.g. \n is converted to \\n, \t to \\t,
6804 etc. The caller is responsible for releasing the returned
6808 escape_buffer (const char *buf, int n)
6810 struct cleanup *old_chain;
6811 struct ui_file *stb;
6814 stb = mem_fileopen ();
6815 old_chain = make_cleanup_ui_file_delete (stb);
6817 fputstrn_unfiltered (buf, n, 0, stb);
6818 str = ui_file_xstrdup (stb, NULL);
6819 do_cleanups (old_chain);
6823 /* Display a null-terminated packet on stdout, for debugging, using C
6827 print_packet (char *buf)
6829 puts_filtered ("\"");
6830 fputstr_filtered (buf, '"', gdb_stdout);
6831 puts_filtered ("\"");
6837 return putpkt_binary (buf, strlen (buf));
6840 /* Send a packet to the remote machine, with error checking. The data
6841 of the packet is in BUF. The string in BUF can be at most
6842 get_remote_packet_size () - 5 to account for the $, # and checksum,
6843 and for a possible /0 if we are debugging (remote_debug) and want
6844 to print the sent packet as a string. */
6847 putpkt_binary (char *buf, int cnt)
6849 struct remote_state *rs = get_remote_state ();
6851 unsigned char csum = 0;
6852 char *buf2 = alloca (cnt + 6);
6858 /* Catch cases like trying to read memory or listing threads while
6859 we're waiting for a stop reply. The remote server wouldn't be
6860 ready to handle this request, so we'd hang and timeout. We don't
6861 have to worry about this in synchronous mode, because in that
6862 case it's not possible to issue a command while the target is
6863 running. This is not a problem in non-stop mode, because in that
6864 case, the stub is always ready to process serial input. */
6865 if (!non_stop && target_can_async_p () && rs->waiting_for_stop_reply)
6866 error (_("Cannot execute this command while the target is running."));
6868 /* We're sending out a new packet. Make sure we don't look at a
6869 stale cached response. */
6870 rs->cached_wait_status = 0;
6872 /* Copy the packet into buffer BUF2, encapsulating it
6873 and giving it a checksum. */
6878 for (i = 0; i < cnt; i++)
6884 *p++ = tohex ((csum >> 4) & 0xf);
6885 *p++ = tohex (csum & 0xf);
6887 /* Send it over and over until we get a positive ack. */
6891 int started_error_output = 0;
6895 struct cleanup *old_chain;
6899 str = escape_buffer (buf2, p - buf2);
6900 old_chain = make_cleanup (xfree, str);
6901 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
6902 gdb_flush (gdb_stdlog);
6903 do_cleanups (old_chain);
6905 if (serial_write (remote_desc, buf2, p - buf2))
6906 perror_with_name (_("putpkt: write failed"));
6908 /* If this is a no acks version of the remote protocol, send the
6909 packet and move on. */
6913 /* Read until either a timeout occurs (-2) or '+' is read.
6914 Handle any notification that arrives in the mean time. */
6917 ch = readchar (remote_timeout);
6925 case SERIAL_TIMEOUT:
6928 if (started_error_output)
6930 putchar_unfiltered ('\n');
6931 started_error_output = 0;
6940 fprintf_unfiltered (gdb_stdlog, "Ack\n");
6944 fprintf_unfiltered (gdb_stdlog, "Nak\n");
6946 case SERIAL_TIMEOUT:
6950 break; /* Retransmit buffer. */
6954 fprintf_unfiltered (gdb_stdlog,
6955 "Packet instead of Ack, ignoring it\n");
6956 /* It's probably an old response sent because an ACK
6957 was lost. Gobble up the packet and ack it so it
6958 doesn't get retransmitted when we resend this
6961 serial_write (remote_desc, "+", 1);
6962 continue; /* Now, go look for +. */
6969 /* If we got a notification, handle it, and go back to looking
6971 /* We've found the start of a notification. Now
6972 collect the data. */
6973 val = read_frame (&rs->buf, &rs->buf_size);
6978 struct cleanup *old_chain;
6981 str = escape_buffer (rs->buf, val);
6982 old_chain = make_cleanup (xfree, str);
6983 fprintf_unfiltered (gdb_stdlog,
6984 " Notification received: %s\n",
6986 do_cleanups (old_chain);
6988 handle_notification (rs->buf, val);
6989 /* We're in sync now, rewait for the ack. */
6996 if (!started_error_output)
6998 started_error_output = 1;
6999 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
7001 fputc_unfiltered (ch & 0177, gdb_stdlog);
7002 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
7011 if (!started_error_output)
7013 started_error_output = 1;
7014 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
7016 fputc_unfiltered (ch & 0177, gdb_stdlog);
7020 break; /* Here to retransmit. */
7024 /* This is wrong. If doing a long backtrace, the user should be
7025 able to get out next time we call QUIT, without anything as
7026 violent as interrupt_query. If we want to provide a way out of
7027 here without getting to the next QUIT, it should be based on
7028 hitting ^C twice as in remote_wait. */
7039 /* Come here after finding the start of a frame when we expected an
7040 ack. Do our best to discard the rest of this packet. */
7049 c = readchar (remote_timeout);
7052 case SERIAL_TIMEOUT:
7053 /* Nothing we can do. */
7056 /* Discard the two bytes of checksum and stop. */
7057 c = readchar (remote_timeout);
7059 c = readchar (remote_timeout);
7062 case '*': /* Run length encoding. */
7063 /* Discard the repeat count. */
7064 c = readchar (remote_timeout);
7069 /* A regular character. */
7075 /* Come here after finding the start of the frame. Collect the rest
7076 into *BUF, verifying the checksum, length, and handling run-length
7077 compression. NUL terminate the buffer. If there is not enough room,
7078 expand *BUF using xrealloc.
7080 Returns -1 on error, number of characters in buffer (ignoring the
7081 trailing NULL) on success. (could be extended to return one of the
7082 SERIAL status indications). */
7085 read_frame (char **buf_p,
7092 struct remote_state *rs = get_remote_state ();
7099 c = readchar (remote_timeout);
7102 case SERIAL_TIMEOUT:
7104 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
7108 fputs_filtered ("Saw new packet start in middle of old one\n",
7110 return -1; /* Start a new packet, count retries. */
7113 unsigned char pktcsum;
7119 check_0 = readchar (remote_timeout);
7121 check_1 = readchar (remote_timeout);
7123 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
7126 fputs_filtered ("Timeout in checksum, retrying\n",
7130 else if (check_0 < 0 || check_1 < 0)
7133 fputs_filtered ("Communication error in checksum\n",
7138 /* Don't recompute the checksum; with no ack packets we
7139 don't have any way to indicate a packet retransmission
7144 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
7145 if (csum == pktcsum)
7150 struct cleanup *old_chain;
7153 str = escape_buffer (buf, bc);
7154 old_chain = make_cleanup (xfree, str);
7155 fprintf_unfiltered (gdb_stdlog,
7156 "Bad checksum, sentsum=0x%x, "
7157 "csum=0x%x, buf=%s\n",
7158 pktcsum, csum, str);
7159 do_cleanups (old_chain);
7161 /* Number of characters in buffer ignoring trailing
7165 case '*': /* Run length encoding. */
7170 c = readchar (remote_timeout);
7172 repeat = c - ' ' + 3; /* Compute repeat count. */
7174 /* The character before ``*'' is repeated. */
7176 if (repeat > 0 && repeat <= 255 && bc > 0)
7178 if (bc + repeat - 1 >= *sizeof_buf - 1)
7180 /* Make some more room in the buffer. */
7181 *sizeof_buf += repeat;
7182 *buf_p = xrealloc (*buf_p, *sizeof_buf);
7186 memset (&buf[bc], buf[bc - 1], repeat);
7192 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
7196 if (bc >= *sizeof_buf - 1)
7198 /* Make some more room in the buffer. */
7200 *buf_p = xrealloc (*buf_p, *sizeof_buf);
7211 /* Read a packet from the remote machine, with error checking, and
7212 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
7213 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
7214 rather than timing out; this is used (in synchronous mode) to wait
7215 for a target that is is executing user code to stop. */
7216 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
7217 don't have to change all the calls to getpkt to deal with the
7218 return value, because at the moment I don't know what the right
7219 thing to do it for those. */
7227 timed_out = getpkt_sane (buf, sizeof_buf, forever);
7231 /* Read a packet from the remote machine, with error checking, and
7232 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
7233 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
7234 rather than timing out; this is used (in synchronous mode) to wait
7235 for a target that is is executing user code to stop. If FOREVER ==
7236 0, this function is allowed to time out gracefully and return an
7237 indication of this to the caller. Otherwise return the number of
7238 bytes read. If EXPECTING_NOTIF, consider receiving a notification
7239 enough reason to return to the caller. */
7242 getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
7243 int expecting_notif)
7245 struct remote_state *rs = get_remote_state ();
7251 /* We're reading a new response. Make sure we don't look at a
7252 previously cached response. */
7253 rs->cached_wait_status = 0;
7255 strcpy (*buf, "timeout");
7258 timeout = watchdog > 0 ? watchdog : -1;
7259 else if (expecting_notif)
7260 timeout = 0; /* There should already be a char in the buffer. If
7263 timeout = remote_timeout;
7267 /* Process any number of notifications, and then return when
7271 /* If we get a timeout or bad checksm, retry up to MAX_TRIES
7273 for (tries = 1; tries <= MAX_TRIES; tries++)
7275 /* This can loop forever if the remote side sends us
7276 characters continuously, but if it pauses, we'll get
7277 SERIAL_TIMEOUT from readchar because of timeout. Then
7278 we'll count that as a retry.
7280 Note that even when forever is set, we will only wait
7281 forever prior to the start of a packet. After that, we
7282 expect characters to arrive at a brisk pace. They should
7283 show up within remote_timeout intervals. */
7285 c = readchar (timeout);
7286 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
7288 if (c == SERIAL_TIMEOUT)
7290 if (expecting_notif)
7291 return -1; /* Don't complain, it's normal to not get
7292 anything in this case. */
7294 if (forever) /* Watchdog went off? Kill the target. */
7298 error (_("Watchdog timeout has expired. Target detached."));
7301 fputs_filtered ("Timed out.\n", gdb_stdlog);
7305 /* We've found the start of a packet or notification.
7306 Now collect the data. */
7307 val = read_frame (buf, sizeof_buf);
7312 serial_write (remote_desc, "-", 1);
7315 if (tries > MAX_TRIES)
7317 /* We have tried hard enough, and just can't receive the
7318 packet/notification. Give up. */
7319 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
7321 /* Skip the ack char if we're in no-ack mode. */
7322 if (!rs->noack_mode)
7323 serial_write (remote_desc, "+", 1);
7327 /* If we got an ordinary packet, return that to our caller. */
7332 struct cleanup *old_chain;
7335 str = escape_buffer (*buf, val);
7336 old_chain = make_cleanup (xfree, str);
7337 fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
7338 do_cleanups (old_chain);
7341 /* Skip the ack char if we're in no-ack mode. */
7342 if (!rs->noack_mode)
7343 serial_write (remote_desc, "+", 1);
7347 /* If we got a notification, handle it, and go back to looking
7351 gdb_assert (c == '%');
7355 struct cleanup *old_chain;
7358 str = escape_buffer (*buf, val);
7359 old_chain = make_cleanup (xfree, str);
7360 fprintf_unfiltered (gdb_stdlog,
7361 " Notification received: %s\n",
7363 do_cleanups (old_chain);
7366 handle_notification (*buf, val);
7368 /* Notifications require no acknowledgement. */
7370 if (expecting_notif)
7377 getpkt_sane (char **buf, long *sizeof_buf, int forever)
7379 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0);
7383 getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever)
7385 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1);
7389 /* A helper function that just calls putpkt; for type correctness. */
7392 putpkt_for_catch_errors (void *arg)
7394 return putpkt (arg);
7398 remote_kill (struct target_ops *ops)
7400 /* Use catch_errors so the user can quit from gdb even when we
7401 aren't on speaking terms with the remote system. */
7402 catch_errors (putpkt_for_catch_errors, "k", "", RETURN_MASK_ERROR);
7404 /* Don't wait for it to die. I'm not really sure it matters whether
7405 we do or not. For the existing stubs, kill is a noop. */
7406 target_mourn_inferior ();
7410 remote_vkill (int pid, struct remote_state *rs)
7412 if (remote_protocol_packets[PACKET_vKill].support == PACKET_DISABLE)
7415 /* Tell the remote target to detach. */
7416 sprintf (rs->buf, "vKill;%x", pid);
7418 getpkt (&rs->buf, &rs->buf_size, 0);
7420 if (packet_ok (rs->buf,
7421 &remote_protocol_packets[PACKET_vKill]) == PACKET_OK)
7423 else if (remote_protocol_packets[PACKET_vKill].support == PACKET_DISABLE)
7430 extended_remote_kill (struct target_ops *ops)
7433 int pid = ptid_get_pid (inferior_ptid);
7434 struct remote_state *rs = get_remote_state ();
7436 res = remote_vkill (pid, rs);
7437 if (res == -1 && !remote_multi_process_p (rs))
7439 /* Don't try 'k' on a multi-process aware stub -- it has no way
7440 to specify the pid. */
7444 getpkt (&rs->buf, &rs->buf_size, 0);
7445 if (rs->buf[0] != 'O' || rs->buf[0] != 'K')
7448 /* Don't wait for it to die. I'm not really sure it matters whether
7449 we do or not. For the existing stubs, kill is a noop. */
7455 error (_("Can't kill process"));
7457 target_mourn_inferior ();
7461 remote_mourn (struct target_ops *ops)
7463 remote_mourn_1 (ops);
7466 /* Worker function for remote_mourn. */
7468 remote_mourn_1 (struct target_ops *target)
7470 unpush_target (target);
7472 /* remote_close takes care of doing most of the clean up. */
7473 generic_mourn_inferior ();
7477 extended_remote_mourn_1 (struct target_ops *target)
7479 struct remote_state *rs = get_remote_state ();
7481 /* In case we got here due to an error, but we're going to stay
7483 rs->waiting_for_stop_reply = 0;
7485 /* We're no longer interested in these events. */
7486 discard_pending_stop_replies (ptid_get_pid (inferior_ptid));
7488 /* If the current general thread belonged to the process we just
7489 detached from or has exited, the remote side current general
7490 thread becomes undefined. Considering a case like this:
7492 - We just got here due to a detach.
7493 - The process that we're detaching from happens to immediately
7494 report a global breakpoint being hit in non-stop mode, in the
7495 same thread we had selected before.
7496 - GDB attaches to this process again.
7497 - This event happens to be the next event we handle.
7499 GDB would consider that the current general thread didn't need to
7500 be set on the stub side (with Hg), since for all it knew,
7501 GENERAL_THREAD hadn't changed.
7503 Notice that although in all-stop mode, the remote server always
7504 sets the current thread to the thread reporting the stop event,
7505 that doesn't happen in non-stop mode; in non-stop, the stub *must
7506 not* change the current thread when reporting a breakpoint hit,
7507 due to the decoupling of event reporting and event handling.
7509 To keep things simple, we always invalidate our notion of the
7511 record_currthread (minus_one_ptid);
7513 /* Unlike "target remote", we do not want to unpush the target; then
7514 the next time the user says "run", we won't be connected. */
7516 /* Call common code to mark the inferior as not running. */
7517 generic_mourn_inferior ();
7519 if (!have_inferiors ())
7521 if (!remote_multi_process_p (rs))
7523 /* Check whether the target is running now - some remote stubs
7524 automatically restart after kill. */
7526 getpkt (&rs->buf, &rs->buf_size, 0);
7528 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
7530 /* Assume that the target has been restarted. Set
7531 inferior_ptid so that bits of core GDB realizes
7532 there's something here, e.g., so that the user can
7533 say "kill" again. */
7534 inferior_ptid = magic_null_ptid;
7541 extended_remote_mourn (struct target_ops *ops)
7543 extended_remote_mourn_1 (ops);
7547 extended_remote_supports_disable_randomization (void)
7549 return (remote_protocol_packets[PACKET_QDisableRandomization].support
7554 extended_remote_disable_randomization (int val)
7556 struct remote_state *rs = get_remote_state ();
7559 sprintf (rs->buf, "QDisableRandomization:%x", val);
7561 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
7563 error (_("Target does not support QDisableRandomization."));
7564 if (strcmp (reply, "OK") != 0)
7565 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
7569 extended_remote_run (char *args)
7571 struct remote_state *rs = get_remote_state ();
7574 /* If the user has disabled vRun support, or we have detected that
7575 support is not available, do not try it. */
7576 if (remote_protocol_packets[PACKET_vRun].support == PACKET_DISABLE)
7579 strcpy (rs->buf, "vRun;");
7580 len = strlen (rs->buf);
7582 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
7583 error (_("Remote file name too long for run packet"));
7584 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len, 0);
7586 gdb_assert (args != NULL);
7589 struct cleanup *back_to;
7593 argv = gdb_buildargv (args);
7594 back_to = make_cleanup ((void (*) (void *)) freeargv, argv);
7595 for (i = 0; argv[i] != NULL; i++)
7597 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
7598 error (_("Argument list too long for run packet"));
7599 rs->buf[len++] = ';';
7600 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len, 0);
7602 do_cleanups (back_to);
7605 rs->buf[len++] = '\0';
7608 getpkt (&rs->buf, &rs->buf_size, 0);
7610 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]) == PACKET_OK)
7612 /* We have a wait response; we don't need it, though. All is well. */
7615 else if (remote_protocol_packets[PACKET_vRun].support == PACKET_DISABLE)
7616 /* It wasn't disabled before, but it is now. */
7620 if (remote_exec_file[0] == '\0')
7621 error (_("Running the default executable on the remote target failed; "
7622 "try \"set remote exec-file\"?"));
7624 error (_("Running \"%s\" on the remote target failed"),
7629 /* In the extended protocol we want to be able to do things like
7630 "run" and have them basically work as expected. So we need
7631 a special create_inferior function. We support changing the
7632 executable file and the command line arguments, but not the
7636 extended_remote_create_inferior_1 (char *exec_file, char *args,
7637 char **env, int from_tty)
7639 /* If running asynchronously, register the target file descriptor
7640 with the event loop. */
7641 if (target_can_async_p ())
7642 target_async (inferior_event_handler, 0);
7644 /* Disable address space randomization if requested (and supported). */
7645 if (extended_remote_supports_disable_randomization ())
7646 extended_remote_disable_randomization (disable_randomization);
7648 /* Now restart the remote server. */
7649 if (extended_remote_run (args) == -1)
7651 /* vRun was not supported. Fail if we need it to do what the
7653 if (remote_exec_file[0])
7654 error (_("Remote target does not support \"set remote exec-file\""));
7656 error (_("Remote target does not support \"set args\" or run <ARGS>"));
7658 /* Fall back to "R". */
7659 extended_remote_restart ();
7662 if (!have_inferiors ())
7664 /* Clean up from the last time we ran, before we mark the target
7665 running again. This will mark breakpoints uninserted, and
7666 get_offsets may insert breakpoints. */
7667 init_thread_list ();
7668 init_wait_for_inferior ();
7671 /* Now mark the inferior as running before we do anything else. */
7672 inferior_ptid = magic_null_ptid;
7674 /* Now, if we have thread information, update inferior_ptid. */
7675 inferior_ptid = remote_current_thread (inferior_ptid);
7677 remote_add_inferior (ptid_get_pid (inferior_ptid), 0);
7678 add_thread_silent (inferior_ptid);
7680 /* Get updated offsets, if the stub uses qOffsets. */
7685 extended_remote_create_inferior (struct target_ops *ops,
7686 char *exec_file, char *args,
7687 char **env, int from_tty)
7689 extended_remote_create_inferior_1 (exec_file, args, env, from_tty);
7693 /* Insert a breakpoint. On targets that have software breakpoint
7694 support, we ask the remote target to do the work; on targets
7695 which don't, we insert a traditional memory breakpoint. */
7698 remote_insert_breakpoint (struct gdbarch *gdbarch,
7699 struct bp_target_info *bp_tgt)
7701 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
7702 If it succeeds, then set the support to PACKET_ENABLE. If it
7703 fails, and the user has explicitly requested the Z support then
7704 report an error, otherwise, mark it disabled and go on. */
7706 if (remote_protocol_packets[PACKET_Z0].support != PACKET_DISABLE)
7708 CORE_ADDR addr = bp_tgt->placed_address;
7709 struct remote_state *rs;
7713 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
7715 rs = get_remote_state ();
7721 addr = (ULONGEST) remote_address_masked (addr);
7722 p += hexnumstr (p, addr);
7723 sprintf (p, ",%d", bpsize);
7726 getpkt (&rs->buf, &rs->buf_size, 0);
7728 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
7733 bp_tgt->placed_address = addr;
7734 bp_tgt->placed_size = bpsize;
7736 case PACKET_UNKNOWN:
7741 return memory_insert_breakpoint (gdbarch, bp_tgt);
7745 remote_remove_breakpoint (struct gdbarch *gdbarch,
7746 struct bp_target_info *bp_tgt)
7748 CORE_ADDR addr = bp_tgt->placed_address;
7749 struct remote_state *rs = get_remote_state ();
7751 if (remote_protocol_packets[PACKET_Z0].support != PACKET_DISABLE)
7759 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
7760 p += hexnumstr (p, addr);
7761 sprintf (p, ",%d", bp_tgt->placed_size);
7764 getpkt (&rs->buf, &rs->buf_size, 0);
7766 return (rs->buf[0] == 'E');
7769 return memory_remove_breakpoint (gdbarch, bp_tgt);
7773 watchpoint_to_Z_packet (int type)
7778 return Z_PACKET_WRITE_WP;
7781 return Z_PACKET_READ_WP;
7784 return Z_PACKET_ACCESS_WP;
7787 internal_error (__FILE__, __LINE__,
7788 _("hw_bp_to_z: bad watchpoint type %d"), type);
7793 remote_insert_watchpoint (CORE_ADDR addr, int len, int type,
7794 struct expression *cond)
7796 struct remote_state *rs = get_remote_state ();
7798 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
7800 if (remote_protocol_packets[PACKET_Z0 + packet].support == PACKET_DISABLE)
7803 sprintf (rs->buf, "Z%x,", packet);
7804 p = strchr (rs->buf, '\0');
7805 addr = remote_address_masked (addr);
7806 p += hexnumstr (p, (ULONGEST) addr);
7807 sprintf (p, ",%x", len);
7810 getpkt (&rs->buf, &rs->buf_size, 0);
7812 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
7816 case PACKET_UNKNOWN:
7821 internal_error (__FILE__, __LINE__,
7822 _("remote_insert_watchpoint: reached end of function"));
7827 remote_remove_watchpoint (CORE_ADDR addr, int len, int type,
7828 struct expression *cond)
7830 struct remote_state *rs = get_remote_state ();
7832 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
7834 if (remote_protocol_packets[PACKET_Z0 + packet].support == PACKET_DISABLE)
7837 sprintf (rs->buf, "z%x,", packet);
7838 p = strchr (rs->buf, '\0');
7839 addr = remote_address_masked (addr);
7840 p += hexnumstr (p, (ULONGEST) addr);
7841 sprintf (p, ",%x", len);
7843 getpkt (&rs->buf, &rs->buf_size, 0);
7845 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
7848 case PACKET_UNKNOWN:
7853 internal_error (__FILE__, __LINE__,
7854 _("remote_remove_watchpoint: reached end of function"));
7858 int remote_hw_watchpoint_limit = -1;
7859 int remote_hw_watchpoint_length_limit = -1;
7860 int remote_hw_breakpoint_limit = -1;
7863 remote_region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
7865 if (remote_hw_watchpoint_length_limit == 0)
7867 else if (remote_hw_watchpoint_length_limit < 0)
7869 else if (len <= remote_hw_watchpoint_length_limit)
7876 remote_check_watch_resources (int type, int cnt, int ot)
7878 if (type == bp_hardware_breakpoint)
7880 if (remote_hw_breakpoint_limit == 0)
7882 else if (remote_hw_breakpoint_limit < 0)
7884 else if (cnt <= remote_hw_breakpoint_limit)
7889 if (remote_hw_watchpoint_limit == 0)
7891 else if (remote_hw_watchpoint_limit < 0)
7895 else if (cnt <= remote_hw_watchpoint_limit)
7902 remote_stopped_by_watchpoint (void)
7904 return remote_stopped_by_watchpoint_p;
7908 remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
7912 if (remote_stopped_by_watchpoint ())
7914 *addr_p = remote_watch_data_address;
7923 remote_insert_hw_breakpoint (struct gdbarch *gdbarch,
7924 struct bp_target_info *bp_tgt)
7927 struct remote_state *rs;
7930 /* The length field should be set to the size of a breakpoint
7931 instruction, even though we aren't inserting one ourselves. */
7933 gdbarch_remote_breakpoint_from_pc
7934 (gdbarch, &bp_tgt->placed_address, &bp_tgt->placed_size);
7936 if (remote_protocol_packets[PACKET_Z1].support == PACKET_DISABLE)
7939 rs = get_remote_state ();
7946 addr = remote_address_masked (bp_tgt->placed_address);
7947 p += hexnumstr (p, (ULONGEST) addr);
7948 sprintf (p, ",%x", bp_tgt->placed_size);
7951 getpkt (&rs->buf, &rs->buf_size, 0);
7953 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
7956 case PACKET_UNKNOWN:
7961 internal_error (__FILE__, __LINE__,
7962 _("remote_insert_hw_breakpoint: reached end of function"));
7967 remote_remove_hw_breakpoint (struct gdbarch *gdbarch,
7968 struct bp_target_info *bp_tgt)
7971 struct remote_state *rs = get_remote_state ();
7974 if (remote_protocol_packets[PACKET_Z1].support == PACKET_DISABLE)
7981 addr = remote_address_masked (bp_tgt->placed_address);
7982 p += hexnumstr (p, (ULONGEST) addr);
7983 sprintf (p, ",%x", bp_tgt->placed_size);
7986 getpkt (&rs->buf, &rs->buf_size, 0);
7988 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
7991 case PACKET_UNKNOWN:
7996 internal_error (__FILE__, __LINE__,
7997 _("remote_remove_hw_breakpoint: reached end of function"));
8000 /* Table used by the crc32 function to calcuate the checksum. */
8002 static unsigned long crc32_table[256] =
8005 static unsigned long
8006 crc32 (const unsigned char *buf, int len, unsigned int crc)
8008 if (!crc32_table[1])
8010 /* Initialize the CRC table and the decoding table. */
8014 for (i = 0; i < 256; i++)
8016 for (c = i << 24, j = 8; j > 0; --j)
8017 c = c & 0x80000000 ? (c << 1) ^ 0x04c11db7 : (c << 1);
8024 crc = (crc << 8) ^ crc32_table[((crc >> 24) ^ *buf) & 255];
8030 /* Verify memory using the "qCRC:" request. */
8033 remote_verify_memory (struct target_ops *ops,
8034 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
8036 struct remote_state *rs = get_remote_state ();
8037 unsigned long host_crc, target_crc;
8040 /* FIXME: assumes lma can fit into long. */
8041 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
8042 (long) lma, (long) size);
8045 /* Be clever; compute the host_crc before waiting for target
8047 host_crc = crc32 (data, size, 0xffffffff);
8049 getpkt (&rs->buf, &rs->buf_size, 0);
8050 if (rs->buf[0] == 'E')
8053 if (rs->buf[0] != 'C')
8054 error (_("remote target does not support this operation"));
8056 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
8057 target_crc = target_crc * 16 + fromhex (*tmp);
8059 return (host_crc == target_crc);
8062 /* compare-sections command
8064 With no arguments, compares each loadable section in the exec bfd
8065 with the same memory range on the target, and reports mismatches.
8066 Useful for verifying the image on the target against the exec file. */
8069 compare_sections_command (char *args, int from_tty)
8072 struct cleanup *old_chain;
8074 const char *sectname;
8082 error (_("command cannot be used without an exec file"));
8084 for (s = exec_bfd->sections; s; s = s->next)
8086 if (!(s->flags & SEC_LOAD))
8087 continue; /* Skip non-loadable section. */
8089 size = bfd_get_section_size (s);
8091 continue; /* Skip zero-length section. */
8093 sectname = bfd_get_section_name (exec_bfd, s);
8094 if (args && strcmp (args, sectname) != 0)
8095 continue; /* Not the section selected by user. */
8097 matched = 1; /* Do this section. */
8100 sectdata = xmalloc (size);
8101 old_chain = make_cleanup (xfree, sectdata);
8102 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
8104 res = target_verify_memory (sectdata, lma, size);
8107 error (_("target memory fault, section %s, range %s -- %s"), sectname,
8108 paddress (target_gdbarch, lma),
8109 paddress (target_gdbarch, lma + size));
8111 printf_filtered ("Section %s, range %s -- %s: ", sectname,
8112 paddress (target_gdbarch, lma),
8113 paddress (target_gdbarch, lma + size));
8115 printf_filtered ("matched.\n");
8118 printf_filtered ("MIS-MATCHED!\n");
8122 do_cleanups (old_chain);
8125 warning (_("One or more sections of the remote executable does not match\n\
8126 the loaded file\n"));
8127 if (args && !matched)
8128 printf_filtered (_("No loaded section named '%s'.\n"), args);
8131 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
8132 into remote target. The number of bytes written to the remote
8133 target is returned, or -1 for error. */
8136 remote_write_qxfer (struct target_ops *ops, const char *object_name,
8137 const char *annex, const gdb_byte *writebuf,
8138 ULONGEST offset, LONGEST len,
8139 struct packet_config *packet)
8143 struct remote_state *rs = get_remote_state ();
8144 int max_size = get_memory_write_packet_size ();
8146 if (packet->support == PACKET_DISABLE)
8149 /* Insert header. */
8150 i = snprintf (rs->buf, max_size,
8151 "qXfer:%s:write:%s:%s:",
8152 object_name, annex ? annex : "",
8153 phex_nz (offset, sizeof offset));
8154 max_size -= (i + 1);
8156 /* Escape as much data as fits into rs->buf. */
8157 buf_len = remote_escape_output
8158 (writebuf, len, (rs->buf + i), &max_size, max_size);
8160 if (putpkt_binary (rs->buf, i + buf_len) < 0
8161 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
8162 || packet_ok (rs->buf, packet) != PACKET_OK)
8165 unpack_varlen_hex (rs->buf, &n);
8169 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
8170 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
8171 number of bytes read is returned, or 0 for EOF, or -1 for error.
8172 The number of bytes read may be less than LEN without indicating an
8173 EOF. PACKET is checked and updated to indicate whether the remote
8174 target supports this object. */
8177 remote_read_qxfer (struct target_ops *ops, const char *object_name,
8179 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
8180 struct packet_config *packet)
8182 static char *finished_object;
8183 static char *finished_annex;
8184 static ULONGEST finished_offset;
8186 struct remote_state *rs = get_remote_state ();
8187 LONGEST i, n, packet_len;
8189 if (packet->support == PACKET_DISABLE)
8192 /* Check whether we've cached an end-of-object packet that matches
8194 if (finished_object)
8196 if (strcmp (object_name, finished_object) == 0
8197 && strcmp (annex ? annex : "", finished_annex) == 0
8198 && offset == finished_offset)
8201 /* Otherwise, we're now reading something different. Discard
8203 xfree (finished_object);
8204 xfree (finished_annex);
8205 finished_object = NULL;
8206 finished_annex = NULL;
8209 /* Request only enough to fit in a single packet. The actual data
8210 may not, since we don't know how much of it will need to be escaped;
8211 the target is free to respond with slightly less data. We subtract
8212 five to account for the response type and the protocol frame. */
8213 n = min (get_remote_packet_size () - 5, len);
8214 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
8215 object_name, annex ? annex : "",
8216 phex_nz (offset, sizeof offset),
8217 phex_nz (n, sizeof n));
8218 i = putpkt (rs->buf);
8223 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
8224 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
8227 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
8228 error (_("Unknown remote qXfer reply: %s"), rs->buf);
8230 /* 'm' means there is (or at least might be) more data after this
8231 batch. That does not make sense unless there's at least one byte
8232 of data in this reply. */
8233 if (rs->buf[0] == 'm' && packet_len == 1)
8234 error (_("Remote qXfer reply contained no data."));
8236 /* Got some data. */
8237 i = remote_unescape_input (rs->buf + 1, packet_len - 1, readbuf, n);
8239 /* 'l' is an EOF marker, possibly including a final block of data,
8240 or possibly empty. If we have the final block of a non-empty
8241 object, record this fact to bypass a subsequent partial read. */
8242 if (rs->buf[0] == 'l' && offset + i > 0)
8244 finished_object = xstrdup (object_name);
8245 finished_annex = xstrdup (annex ? annex : "");
8246 finished_offset = offset + i;
8253 remote_xfer_partial (struct target_ops *ops, enum target_object object,
8254 const char *annex, gdb_byte *readbuf,
8255 const gdb_byte *writebuf, ULONGEST offset, LONGEST len)
8257 struct remote_state *rs;
8262 set_remote_traceframe ();
8263 set_general_thread (inferior_ptid);
8265 rs = get_remote_state ();
8267 /* Handle memory using the standard memory routines. */
8268 if (object == TARGET_OBJECT_MEMORY)
8274 /* If the remote target is connected but not running, we should
8275 pass this request down to a lower stratum (e.g. the executable
8277 if (!target_has_execution)
8280 if (writebuf != NULL)
8281 xfered = remote_write_bytes (offset, writebuf, len);
8283 xfered = remote_read_bytes (offset, readbuf, len);
8287 else if (xfered == 0 && errno == 0)
8293 /* Handle SPU memory using qxfer packets. */
8294 if (object == TARGET_OBJECT_SPU)
8297 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
8298 &remote_protocol_packets
8299 [PACKET_qXfer_spu_read]);
8301 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
8302 &remote_protocol_packets
8303 [PACKET_qXfer_spu_write]);
8306 /* Handle extra signal info using qxfer packets. */
8307 if (object == TARGET_OBJECT_SIGNAL_INFO)
8310 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
8311 &remote_protocol_packets
8312 [PACKET_qXfer_siginfo_read]);
8314 return remote_write_qxfer (ops, "siginfo", annex,
8315 writebuf, offset, len,
8316 &remote_protocol_packets
8317 [PACKET_qXfer_siginfo_write]);
8320 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
8323 return remote_read_qxfer (ops, "statictrace", annex,
8324 readbuf, offset, len,
8325 &remote_protocol_packets
8326 [PACKET_qXfer_statictrace_read]);
8331 /* Only handle flash writes. */
8332 if (writebuf != NULL)
8338 case TARGET_OBJECT_FLASH:
8339 xfered = remote_flash_write (ops, offset, len, writebuf);
8343 else if (xfered == 0 && errno == 0)
8353 /* Map pre-existing objects onto letters. DO NOT do this for new
8354 objects!!! Instead specify new query packets. */
8357 case TARGET_OBJECT_AVR:
8361 case TARGET_OBJECT_AUXV:
8362 gdb_assert (annex == NULL);
8363 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
8364 &remote_protocol_packets[PACKET_qXfer_auxv]);
8366 case TARGET_OBJECT_AVAILABLE_FEATURES:
8367 return remote_read_qxfer
8368 (ops, "features", annex, readbuf, offset, len,
8369 &remote_protocol_packets[PACKET_qXfer_features]);
8371 case TARGET_OBJECT_LIBRARIES:
8372 return remote_read_qxfer
8373 (ops, "libraries", annex, readbuf, offset, len,
8374 &remote_protocol_packets[PACKET_qXfer_libraries]);
8376 case TARGET_OBJECT_LIBRARIES_SVR4:
8377 return remote_read_qxfer
8378 (ops, "libraries-svr4", annex, readbuf, offset, len,
8379 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
8381 case TARGET_OBJECT_MEMORY_MAP:
8382 gdb_assert (annex == NULL);
8383 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
8384 &remote_protocol_packets[PACKET_qXfer_memory_map]);
8386 case TARGET_OBJECT_OSDATA:
8387 /* Should only get here if we're connected. */
8388 gdb_assert (remote_desc);
8389 return remote_read_qxfer
8390 (ops, "osdata", annex, readbuf, offset, len,
8391 &remote_protocol_packets[PACKET_qXfer_osdata]);
8393 case TARGET_OBJECT_THREADS:
8394 gdb_assert (annex == NULL);
8395 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
8396 &remote_protocol_packets[PACKET_qXfer_threads]);
8398 case TARGET_OBJECT_TRACEFRAME_INFO:
8399 gdb_assert (annex == NULL);
8400 return remote_read_qxfer
8401 (ops, "traceframe-info", annex, readbuf, offset, len,
8402 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
8404 case TARGET_OBJECT_FDPIC:
8405 return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
8406 &remote_protocol_packets[PACKET_qXfer_fdpic]);
8411 /* Note: a zero OFFSET and LEN can be used to query the minimum
8413 if (offset == 0 && len == 0)
8414 return (get_remote_packet_size ());
8415 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
8416 large enough let the caller deal with it. */
8417 if (len < get_remote_packet_size ())
8419 len = get_remote_packet_size ();
8421 /* Except for querying the minimum buffer size, target must be open. */
8423 error (_("remote query is only available after target open"));
8425 gdb_assert (annex != NULL);
8426 gdb_assert (readbuf != NULL);
8432 /* We used one buffer char for the remote protocol q command and
8433 another for the query type. As the remote protocol encapsulation
8434 uses 4 chars plus one extra in case we are debugging
8435 (remote_debug), we have PBUFZIZ - 7 left to pack the query
8438 while (annex[i] && (i < (get_remote_packet_size () - 8)))
8440 /* Bad caller may have sent forbidden characters. */
8441 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
8446 gdb_assert (annex[i] == '\0');
8448 i = putpkt (rs->buf);
8452 getpkt (&rs->buf, &rs->buf_size, 0);
8453 strcpy ((char *) readbuf, rs->buf);
8455 return strlen ((char *) readbuf);
8459 remote_search_memory (struct target_ops* ops,
8460 CORE_ADDR start_addr, ULONGEST search_space_len,
8461 const gdb_byte *pattern, ULONGEST pattern_len,
8462 CORE_ADDR *found_addrp)
8464 int addr_size = gdbarch_addr_bit (target_gdbarch) / 8;
8465 struct remote_state *rs = get_remote_state ();
8466 int max_size = get_memory_write_packet_size ();
8467 struct packet_config *packet =
8468 &remote_protocol_packets[PACKET_qSearch_memory];
8469 /* Number of packet bytes used to encode the pattern;
8470 this could be more than PATTERN_LEN due to escape characters. */
8471 int escaped_pattern_len;
8472 /* Amount of pattern that was encodable in the packet. */
8473 int used_pattern_len;
8476 ULONGEST found_addr;
8478 /* Don't go to the target if we don't have to.
8479 This is done before checking packet->support to avoid the possibility that
8480 a success for this edge case means the facility works in general. */
8481 if (pattern_len > search_space_len)
8483 if (pattern_len == 0)
8485 *found_addrp = start_addr;
8489 /* If we already know the packet isn't supported, fall back to the simple
8490 way of searching memory. */
8492 if (packet->support == PACKET_DISABLE)
8494 /* Target doesn't provided special support, fall back and use the
8495 standard support (copy memory and do the search here). */
8496 return simple_search_memory (ops, start_addr, search_space_len,
8497 pattern, pattern_len, found_addrp);
8500 /* Insert header. */
8501 i = snprintf (rs->buf, max_size,
8502 "qSearch:memory:%s;%s;",
8503 phex_nz (start_addr, addr_size),
8504 phex_nz (search_space_len, sizeof (search_space_len)));
8505 max_size -= (i + 1);
8507 /* Escape as much data as fits into rs->buf. */
8508 escaped_pattern_len =
8509 remote_escape_output (pattern, pattern_len, (rs->buf + i),
8510 &used_pattern_len, max_size);
8512 /* Bail if the pattern is too large. */
8513 if (used_pattern_len != pattern_len)
8514 error (_("Pattern is too large to transmit to remote target."));
8516 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
8517 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
8518 || packet_ok (rs->buf, packet) != PACKET_OK)
8520 /* The request may not have worked because the command is not
8521 supported. If so, fall back to the simple way. */
8522 if (packet->support == PACKET_DISABLE)
8524 return simple_search_memory (ops, start_addr, search_space_len,
8525 pattern, pattern_len, found_addrp);
8530 if (rs->buf[0] == '0')
8532 else if (rs->buf[0] == '1')
8535 if (rs->buf[1] != ',')
8536 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
8537 unpack_varlen_hex (rs->buf + 2, &found_addr);
8538 *found_addrp = found_addr;
8541 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
8547 remote_rcmd (char *command,
8548 struct ui_file *outbuf)
8550 struct remote_state *rs = get_remote_state ();
8554 error (_("remote rcmd is only available after target open"));
8556 /* Send a NULL command across as an empty command. */
8557 if (command == NULL)
8560 /* The query prefix. */
8561 strcpy (rs->buf, "qRcmd,");
8562 p = strchr (rs->buf, '\0');
8564 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
8565 > get_remote_packet_size ())
8566 error (_("\"monitor\" command ``%s'' is too long."), command);
8568 /* Encode the actual command. */
8569 bin2hex ((gdb_byte *) command, p, 0);
8571 if (putpkt (rs->buf) < 0)
8572 error (_("Communication problem with target."));
8574 /* get/display the response */
8579 /* XXX - see also remote_get_noisy_reply(). */
8581 getpkt (&rs->buf, &rs->buf_size, 0);
8584 error (_("Target does not support this command."));
8585 if (buf[0] == 'O' && buf[1] != 'K')
8587 remote_console_output (buf + 1); /* 'O' message from stub. */
8590 if (strcmp (buf, "OK") == 0)
8592 if (strlen (buf) == 3 && buf[0] == 'E'
8593 && isdigit (buf[1]) && isdigit (buf[2]))
8595 error (_("Protocol error with Rcmd"));
8597 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
8599 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
8601 fputc_unfiltered (c, outbuf);
8607 static VEC(mem_region_s) *
8608 remote_memory_map (struct target_ops *ops)
8610 VEC(mem_region_s) *result = NULL;
8611 char *text = target_read_stralloc (¤t_target,
8612 TARGET_OBJECT_MEMORY_MAP, NULL);
8616 struct cleanup *back_to = make_cleanup (xfree, text);
8618 result = parse_memory_map (text);
8619 do_cleanups (back_to);
8626 packet_command (char *args, int from_tty)
8628 struct remote_state *rs = get_remote_state ();
8631 error (_("command can only be used with remote target"));
8634 error (_("remote-packet command requires packet text as argument"));
8636 puts_filtered ("sending: ");
8637 print_packet (args);
8638 puts_filtered ("\n");
8641 getpkt (&rs->buf, &rs->buf_size, 0);
8642 puts_filtered ("received: ");
8643 print_packet (rs->buf);
8644 puts_filtered ("\n");
8648 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
8650 static void display_thread_info (struct gdb_ext_thread_info *info);
8652 static void threadset_test_cmd (char *cmd, int tty);
8654 static void threadalive_test (char *cmd, int tty);
8656 static void threadlist_test_cmd (char *cmd, int tty);
8658 int get_and_display_threadinfo (threadref *ref);
8660 static void threadinfo_test_cmd (char *cmd, int tty);
8662 static int thread_display_step (threadref *ref, void *context);
8664 static void threadlist_update_test_cmd (char *cmd, int tty);
8666 static void init_remote_threadtests (void);
8668 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
8671 threadset_test_cmd (char *cmd, int tty)
8673 int sample_thread = SAMPLE_THREAD;
8675 printf_filtered (_("Remote threadset test\n"));
8676 set_general_thread (sample_thread);
8681 threadalive_test (char *cmd, int tty)
8683 int sample_thread = SAMPLE_THREAD;
8684 int pid = ptid_get_pid (inferior_ptid);
8685 ptid_t ptid = ptid_build (pid, 0, sample_thread);
8687 if (remote_thread_alive (ptid))
8688 printf_filtered ("PASS: Thread alive test\n");
8690 printf_filtered ("FAIL: Thread alive test\n");
8693 void output_threadid (char *title, threadref *ref);
8696 output_threadid (char *title, threadref *ref)
8700 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
8702 printf_filtered ("%s %s\n", title, (&hexid[0]));
8706 threadlist_test_cmd (char *cmd, int tty)
8709 threadref nextthread;
8710 int done, result_count;
8711 threadref threadlist[3];
8713 printf_filtered ("Remote Threadlist test\n");
8714 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
8715 &result_count, &threadlist[0]))
8716 printf_filtered ("FAIL: threadlist test\n");
8719 threadref *scan = threadlist;
8720 threadref *limit = scan + result_count;
8722 while (scan < limit)
8723 output_threadid (" thread ", scan++);
8728 display_thread_info (struct gdb_ext_thread_info *info)
8730 output_threadid ("Threadid: ", &info->threadid);
8731 printf_filtered ("Name: %s\n ", info->shortname);
8732 printf_filtered ("State: %s\n", info->display);
8733 printf_filtered ("other: %s\n\n", info->more_display);
8737 get_and_display_threadinfo (threadref *ref)
8741 struct gdb_ext_thread_info threadinfo;
8743 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
8744 | TAG_MOREDISPLAY | TAG_DISPLAY;
8745 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
8746 display_thread_info (&threadinfo);
8751 threadinfo_test_cmd (char *cmd, int tty)
8753 int athread = SAMPLE_THREAD;
8757 int_to_threadref (&thread, athread);
8758 printf_filtered ("Remote Threadinfo test\n");
8759 if (!get_and_display_threadinfo (&thread))
8760 printf_filtered ("FAIL cannot get thread info\n");
8764 thread_display_step (threadref *ref, void *context)
8766 /* output_threadid(" threadstep ",ref); *//* simple test */
8767 return get_and_display_threadinfo (ref);
8771 threadlist_update_test_cmd (char *cmd, int tty)
8773 printf_filtered ("Remote Threadlist update test\n");
8774 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
8778 init_remote_threadtests (void)
8780 add_com ("tlist", class_obscure, threadlist_test_cmd,
8781 _("Fetch and print the remote list of "
8782 "thread identifiers, one pkt only"));
8783 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
8784 _("Fetch and display info about one thread"));
8785 add_com ("tset", class_obscure, threadset_test_cmd,
8786 _("Test setting to a different thread"));
8787 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
8788 _("Iterate through updating all remote thread info"));
8789 add_com ("talive", class_obscure, threadalive_test,
8790 _(" Remote thread alive test "));
8795 /* Convert a thread ID to a string. Returns the string in a static
8799 remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
8801 static char buf[64];
8802 struct remote_state *rs = get_remote_state ();
8804 if (ptid_is_pid (ptid))
8806 /* Printing an inferior target id. */
8808 /* When multi-process extensions are off, there's no way in the
8809 remote protocol to know the remote process id, if there's any
8810 at all. There's one exception --- when we're connected with
8811 target extended-remote, and we manually attached to a process
8812 with "attach PID". We don't record anywhere a flag that
8813 allows us to distinguish that case from the case of
8814 connecting with extended-remote and the stub already being
8815 attached to a process, and reporting yes to qAttached, hence
8816 no smart special casing here. */
8817 if (!remote_multi_process_p (rs))
8819 xsnprintf (buf, sizeof buf, "Remote target");
8823 return normal_pid_to_str (ptid);
8827 if (ptid_equal (magic_null_ptid, ptid))
8828 xsnprintf (buf, sizeof buf, "Thread <main>");
8829 else if (remote_multi_process_p (rs))
8830 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
8831 ptid_get_pid (ptid), ptid_get_tid (ptid));
8833 xsnprintf (buf, sizeof buf, "Thread %ld",
8834 ptid_get_tid (ptid));
8839 /* Get the address of the thread local variable in OBJFILE which is
8840 stored at OFFSET within the thread local storage for thread PTID. */
8843 remote_get_thread_local_address (struct target_ops *ops,
8844 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
8846 if (remote_protocol_packets[PACKET_qGetTLSAddr].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, "qGetTLSAddr:");
8855 p = write_ptid (p, endp, ptid);
8857 p += hexnumstr (p, offset);
8859 p += hexnumstr (p, lm);
8863 getpkt (&rs->buf, &rs->buf_size, 0);
8864 result = packet_ok (rs->buf,
8865 &remote_protocol_packets[PACKET_qGetTLSAddr]);
8866 if (result == PACKET_OK)
8870 unpack_varlen_hex (rs->buf, &result);
8873 else if (result == PACKET_UNKNOWN)
8874 throw_error (TLS_GENERIC_ERROR,
8875 _("Remote target doesn't support qGetTLSAddr packet"));
8877 throw_error (TLS_GENERIC_ERROR,
8878 _("Remote target failed to process qGetTLSAddr request"));
8881 throw_error (TLS_GENERIC_ERROR,
8882 _("TLS not supported or disabled on this target"));
8887 /* Provide thread local base, i.e. Thread Information Block address.
8888 Returns 1 if ptid is found and thread_local_base is non zero. */
8891 remote_get_tib_address (ptid_t ptid, CORE_ADDR *addr)
8893 if (remote_protocol_packets[PACKET_qGetTIBAddr].support != PACKET_DISABLE)
8895 struct remote_state *rs = get_remote_state ();
8897 char *endp = rs->buf + get_remote_packet_size ();
8898 enum packet_result result;
8900 strcpy (p, "qGetTIBAddr:");
8902 p = write_ptid (p, endp, ptid);
8906 getpkt (&rs->buf, &rs->buf_size, 0);
8907 result = packet_ok (rs->buf,
8908 &remote_protocol_packets[PACKET_qGetTIBAddr]);
8909 if (result == PACKET_OK)
8913 unpack_varlen_hex (rs->buf, &result);
8915 *addr = (CORE_ADDR) result;
8918 else if (result == PACKET_UNKNOWN)
8919 error (_("Remote target doesn't support qGetTIBAddr packet"));
8921 error (_("Remote target failed to process qGetTIBAddr request"));
8924 error (_("qGetTIBAddr not supported or disabled on this target"));
8929 /* Support for inferring a target description based on the current
8930 architecture and the size of a 'g' packet. While the 'g' packet
8931 can have any size (since optional registers can be left off the
8932 end), some sizes are easily recognizable given knowledge of the
8933 approximate architecture. */
8935 struct remote_g_packet_guess
8938 const struct target_desc *tdesc;
8940 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
8941 DEF_VEC_O(remote_g_packet_guess_s);
8943 struct remote_g_packet_data
8945 VEC(remote_g_packet_guess_s) *guesses;
8948 static struct gdbarch_data *remote_g_packet_data_handle;
8951 remote_g_packet_data_init (struct obstack *obstack)
8953 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
8957 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
8958 const struct target_desc *tdesc)
8960 struct remote_g_packet_data *data
8961 = gdbarch_data (gdbarch, remote_g_packet_data_handle);
8962 struct remote_g_packet_guess new_guess, *guess;
8965 gdb_assert (tdesc != NULL);
8968 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
8970 if (guess->bytes == bytes)
8971 internal_error (__FILE__, __LINE__,
8972 _("Duplicate g packet description added for size %d"),
8975 new_guess.bytes = bytes;
8976 new_guess.tdesc = tdesc;
8977 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
8980 /* Return 1 if remote_read_description would do anything on this target
8981 and architecture, 0 otherwise. */
8984 remote_read_description_p (struct target_ops *target)
8986 struct remote_g_packet_data *data
8987 = gdbarch_data (target_gdbarch, remote_g_packet_data_handle);
8989 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
8995 static const struct target_desc *
8996 remote_read_description (struct target_ops *target)
8998 struct remote_g_packet_data *data
8999 = gdbarch_data (target_gdbarch, remote_g_packet_data_handle);
9001 /* Do not try this during initial connection, when we do not know
9002 whether there is a running but stopped thread. */
9003 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
9006 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
9008 struct remote_g_packet_guess *guess;
9010 int bytes = send_g_packet ();
9013 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
9015 if (guess->bytes == bytes)
9016 return guess->tdesc;
9018 /* We discard the g packet. A minor optimization would be to
9019 hold on to it, and fill the register cache once we have selected
9020 an architecture, but it's too tricky to do safely. */
9026 /* Remote file transfer support. This is host-initiated I/O, not
9027 target-initiated; for target-initiated, see remote-fileio.c. */
9029 /* If *LEFT is at least the length of STRING, copy STRING to
9030 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9031 decrease *LEFT. Otherwise raise an error. */
9034 remote_buffer_add_string (char **buffer, int *left, char *string)
9036 int len = strlen (string);
9039 error (_("Packet too long for target."));
9041 memcpy (*buffer, string, len);
9045 /* NUL-terminate the buffer as a convenience, if there is
9051 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
9052 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9053 decrease *LEFT. Otherwise raise an error. */
9056 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
9059 if (2 * len > *left)
9060 error (_("Packet too long for target."));
9062 bin2hex (bytes, *buffer, len);
9066 /* NUL-terminate the buffer as a convenience, if there is
9072 /* If *LEFT is large enough, convert VALUE to hex and add it to
9073 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9074 decrease *LEFT. Otherwise raise an error. */
9077 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
9079 int len = hexnumlen (value);
9082 error (_("Packet too long for target."));
9084 hexnumstr (*buffer, value);
9088 /* NUL-terminate the buffer as a convenience, if there is
9094 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
9095 value, *REMOTE_ERRNO to the remote error number or zero if none
9096 was included, and *ATTACHMENT to point to the start of the annex
9097 if any. The length of the packet isn't needed here; there may
9098 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
9100 Return 0 if the packet could be parsed, -1 if it could not. If
9101 -1 is returned, the other variables may not be initialized. */
9104 remote_hostio_parse_result (char *buffer, int *retcode,
9105 int *remote_errno, char **attachment)
9112 if (buffer[0] != 'F')
9116 *retcode = strtol (&buffer[1], &p, 16);
9117 if (errno != 0 || p == &buffer[1])
9120 /* Check for ",errno". */
9124 *remote_errno = strtol (p + 1, &p2, 16);
9125 if (errno != 0 || p + 1 == p2)
9130 /* Check for ";attachment". If there is no attachment, the
9131 packet should end here. */
9134 *attachment = p + 1;
9137 else if (*p == '\0')
9143 /* Send a prepared I/O packet to the target and read its response.
9144 The prepared packet is in the global RS->BUF before this function
9145 is called, and the answer is there when we return.
9147 COMMAND_BYTES is the length of the request to send, which may include
9148 binary data. WHICH_PACKET is the packet configuration to check
9149 before attempting a packet. If an error occurs, *REMOTE_ERRNO
9150 is set to the error number and -1 is returned. Otherwise the value
9151 returned by the function is returned.
9153 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
9154 attachment is expected; an error will be reported if there's a
9155 mismatch. If one is found, *ATTACHMENT will be set to point into
9156 the packet buffer and *ATTACHMENT_LEN will be set to the
9157 attachment's length. */
9160 remote_hostio_send_command (int command_bytes, int which_packet,
9161 int *remote_errno, char **attachment,
9162 int *attachment_len)
9164 struct remote_state *rs = get_remote_state ();
9165 int ret, bytes_read;
9166 char *attachment_tmp;
9169 || remote_protocol_packets[which_packet].support == PACKET_DISABLE)
9171 *remote_errno = FILEIO_ENOSYS;
9175 putpkt_binary (rs->buf, command_bytes);
9176 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
9178 /* If it timed out, something is wrong. Don't try to parse the
9182 *remote_errno = FILEIO_EINVAL;
9186 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
9189 *remote_errno = FILEIO_EINVAL;
9191 case PACKET_UNKNOWN:
9192 *remote_errno = FILEIO_ENOSYS;
9198 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
9201 *remote_errno = FILEIO_EINVAL;
9205 /* Make sure we saw an attachment if and only if we expected one. */
9206 if ((attachment_tmp == NULL && attachment != NULL)
9207 || (attachment_tmp != NULL && attachment == NULL))
9209 *remote_errno = FILEIO_EINVAL;
9213 /* If an attachment was found, it must point into the packet buffer;
9214 work out how many bytes there were. */
9215 if (attachment_tmp != NULL)
9217 *attachment = attachment_tmp;
9218 *attachment_len = bytes_read - (*attachment - rs->buf);
9224 /* Open FILENAME on the remote target, using FLAGS and MODE. Return a
9225 remote file descriptor, or -1 if an error occurs (and set
9229 remote_hostio_open (const char *filename, int flags, int mode,
9232 struct remote_state *rs = get_remote_state ();
9234 int left = get_remote_packet_size () - 1;
9236 remote_buffer_add_string (&p, &left, "vFile:open:");
9238 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
9240 remote_buffer_add_string (&p, &left, ",");
9242 remote_buffer_add_int (&p, &left, flags);
9243 remote_buffer_add_string (&p, &left, ",");
9245 remote_buffer_add_int (&p, &left, mode);
9247 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
9248 remote_errno, NULL, NULL);
9251 /* Write up to LEN bytes from WRITE_BUF to FD on the remote target.
9252 Return the number of bytes written, or -1 if an error occurs (and
9253 set *REMOTE_ERRNO). */
9256 remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
9257 ULONGEST offset, int *remote_errno)
9259 struct remote_state *rs = get_remote_state ();
9261 int left = get_remote_packet_size ();
9264 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
9266 remote_buffer_add_int (&p, &left, fd);
9267 remote_buffer_add_string (&p, &left, ",");
9269 remote_buffer_add_int (&p, &left, offset);
9270 remote_buffer_add_string (&p, &left, ",");
9272 p += remote_escape_output (write_buf, len, p, &out_len,
9273 get_remote_packet_size () - (p - rs->buf));
9275 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
9276 remote_errno, NULL, NULL);
9279 /* Read up to LEN bytes FD on the remote target into READ_BUF
9280 Return the number of bytes read, or -1 if an error occurs (and
9281 set *REMOTE_ERRNO). */
9284 remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
9285 ULONGEST offset, int *remote_errno)
9287 struct remote_state *rs = get_remote_state ();
9290 int left = get_remote_packet_size ();
9291 int ret, attachment_len;
9294 remote_buffer_add_string (&p, &left, "vFile:pread:");
9296 remote_buffer_add_int (&p, &left, fd);
9297 remote_buffer_add_string (&p, &left, ",");
9299 remote_buffer_add_int (&p, &left, len);
9300 remote_buffer_add_string (&p, &left, ",");
9302 remote_buffer_add_int (&p, &left, offset);
9304 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
9305 remote_errno, &attachment,
9311 read_len = remote_unescape_input (attachment, attachment_len,
9313 if (read_len != ret)
9314 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
9319 /* Close FD on the remote target. Return 0, or -1 if an error occurs
9320 (and set *REMOTE_ERRNO). */
9323 remote_hostio_close (int fd, int *remote_errno)
9325 struct remote_state *rs = get_remote_state ();
9327 int left = get_remote_packet_size () - 1;
9329 remote_buffer_add_string (&p, &left, "vFile:close:");
9331 remote_buffer_add_int (&p, &left, fd);
9333 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
9334 remote_errno, NULL, NULL);
9337 /* Unlink FILENAME on the remote target. Return 0, or -1 if an error
9338 occurs (and set *REMOTE_ERRNO). */
9341 remote_hostio_unlink (const char *filename, int *remote_errno)
9343 struct remote_state *rs = get_remote_state ();
9345 int left = get_remote_packet_size () - 1;
9347 remote_buffer_add_string (&p, &left, "vFile:unlink:");
9349 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
9352 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
9353 remote_errno, NULL, NULL);
9357 remote_fileio_errno_to_host (int errnum)
9381 case FILEIO_ENOTDIR:
9401 case FILEIO_ENAMETOOLONG:
9402 return ENAMETOOLONG;
9408 remote_hostio_error (int errnum)
9410 int host_error = remote_fileio_errno_to_host (errnum);
9412 if (host_error == -1)
9413 error (_("Unknown remote I/O error %d"), errnum);
9415 error (_("Remote I/O error: %s"), safe_strerror (host_error));
9419 remote_hostio_close_cleanup (void *opaque)
9421 int fd = *(int *) opaque;
9424 remote_hostio_close (fd, &remote_errno);
9429 remote_bfd_iovec_open (struct bfd *abfd, void *open_closure)
9431 const char *filename = bfd_get_filename (abfd);
9432 int fd, remote_errno;
9435 gdb_assert (remote_filename_p (filename));
9437 fd = remote_hostio_open (filename + 7, FILEIO_O_RDONLY, 0, &remote_errno);
9440 errno = remote_fileio_errno_to_host (remote_errno);
9441 bfd_set_error (bfd_error_system_call);
9445 stream = xmalloc (sizeof (int));
9451 remote_bfd_iovec_close (struct bfd *abfd, void *stream)
9453 int fd = *(int *)stream;
9458 /* Ignore errors on close; these may happen if the remote
9459 connection was already torn down. */
9460 remote_hostio_close (fd, &remote_errno);
9466 remote_bfd_iovec_pread (struct bfd *abfd, void *stream, void *buf,
9467 file_ptr nbytes, file_ptr offset)
9469 int fd = *(int *)stream;
9471 file_ptr pos, bytes;
9474 while (nbytes > pos)
9476 bytes = remote_hostio_pread (fd, (char *)buf + pos, nbytes - pos,
9477 offset + pos, &remote_errno);
9479 /* Success, but no bytes, means end-of-file. */
9483 errno = remote_fileio_errno_to_host (remote_errno);
9484 bfd_set_error (bfd_error_system_call);
9495 remote_bfd_iovec_stat (struct bfd *abfd, void *stream, struct stat *sb)
9497 /* FIXME: We should probably implement remote_hostio_stat. */
9498 sb->st_size = INT_MAX;
9503 remote_filename_p (const char *filename)
9505 return strncmp (filename, "remote:", 7) == 0;
9509 remote_bfd_open (const char *remote_file, const char *target)
9511 return bfd_openr_iovec (remote_file, target,
9512 remote_bfd_iovec_open, NULL,
9513 remote_bfd_iovec_pread,
9514 remote_bfd_iovec_close,
9515 remote_bfd_iovec_stat);
9519 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
9521 struct cleanup *back_to, *close_cleanup;
9522 int retcode, fd, remote_errno, bytes, io_size;
9525 int bytes_in_buffer;
9530 error (_("command can only be used with remote target"));
9532 file = fopen (local_file, "rb");
9534 perror_with_name (local_file);
9535 back_to = make_cleanup_fclose (file);
9537 fd = remote_hostio_open (remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
9539 0700, &remote_errno);
9541 remote_hostio_error (remote_errno);
9543 /* Send up to this many bytes at once. They won't all fit in the
9544 remote packet limit, so we'll transfer slightly fewer. */
9545 io_size = get_remote_packet_size ();
9546 buffer = xmalloc (io_size);
9547 make_cleanup (xfree, buffer);
9549 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
9551 bytes_in_buffer = 0;
9554 while (bytes_in_buffer || !saw_eof)
9558 bytes = fread (buffer + bytes_in_buffer, 1,
9559 io_size - bytes_in_buffer,
9564 error (_("Error reading %s."), local_file);
9567 /* EOF. Unless there is something still in the
9568 buffer from the last iteration, we are done. */
9570 if (bytes_in_buffer == 0)
9578 bytes += bytes_in_buffer;
9579 bytes_in_buffer = 0;
9581 retcode = remote_hostio_pwrite (fd, buffer, bytes,
9582 offset, &remote_errno);
9585 remote_hostio_error (remote_errno);
9586 else if (retcode == 0)
9587 error (_("Remote write of %d bytes returned 0!"), bytes);
9588 else if (retcode < bytes)
9590 /* Short write. Save the rest of the read data for the next
9592 bytes_in_buffer = bytes - retcode;
9593 memmove (buffer, buffer + retcode, bytes_in_buffer);
9599 discard_cleanups (close_cleanup);
9600 if (remote_hostio_close (fd, &remote_errno))
9601 remote_hostio_error (remote_errno);
9604 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
9605 do_cleanups (back_to);
9609 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
9611 struct cleanup *back_to, *close_cleanup;
9612 int fd, remote_errno, bytes, io_size;
9618 error (_("command can only be used with remote target"));
9620 fd = remote_hostio_open (remote_file, FILEIO_O_RDONLY, 0, &remote_errno);
9622 remote_hostio_error (remote_errno);
9624 file = fopen (local_file, "wb");
9626 perror_with_name (local_file);
9627 back_to = make_cleanup_fclose (file);
9629 /* Send up to this many bytes at once. They won't all fit in the
9630 remote packet limit, so we'll transfer slightly fewer. */
9631 io_size = get_remote_packet_size ();
9632 buffer = xmalloc (io_size);
9633 make_cleanup (xfree, buffer);
9635 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
9640 bytes = remote_hostio_pread (fd, buffer, io_size, offset, &remote_errno);
9642 /* Success, but no bytes, means end-of-file. */
9645 remote_hostio_error (remote_errno);
9649 bytes = fwrite (buffer, 1, bytes, file);
9651 perror_with_name (local_file);
9654 discard_cleanups (close_cleanup);
9655 if (remote_hostio_close (fd, &remote_errno))
9656 remote_hostio_error (remote_errno);
9659 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
9660 do_cleanups (back_to);
9664 remote_file_delete (const char *remote_file, int from_tty)
9666 int retcode, remote_errno;
9669 error (_("command can only be used with remote target"));
9671 retcode = remote_hostio_unlink (remote_file, &remote_errno);
9673 remote_hostio_error (remote_errno);
9676 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
9680 remote_put_command (char *args, int from_tty)
9682 struct cleanup *back_to;
9686 error_no_arg (_("file to put"));
9688 argv = gdb_buildargv (args);
9689 back_to = make_cleanup_freeargv (argv);
9690 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
9691 error (_("Invalid parameters to remote put"));
9693 remote_file_put (argv[0], argv[1], from_tty);
9695 do_cleanups (back_to);
9699 remote_get_command (char *args, int from_tty)
9701 struct cleanup *back_to;
9705 error_no_arg (_("file to get"));
9707 argv = gdb_buildargv (args);
9708 back_to = make_cleanup_freeargv (argv);
9709 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
9710 error (_("Invalid parameters to remote get"));
9712 remote_file_get (argv[0], argv[1], from_tty);
9714 do_cleanups (back_to);
9718 remote_delete_command (char *args, int from_tty)
9720 struct cleanup *back_to;
9724 error_no_arg (_("file to delete"));
9726 argv = gdb_buildargv (args);
9727 back_to = make_cleanup_freeargv (argv);
9728 if (argv[0] == NULL || argv[1] != NULL)
9729 error (_("Invalid parameters to remote delete"));
9731 remote_file_delete (argv[0], from_tty);
9733 do_cleanups (back_to);
9737 remote_command (char *args, int from_tty)
9739 help_list (remote_cmdlist, "remote ", -1, gdb_stdout);
9743 remote_can_execute_reverse (void)
9745 if (remote_protocol_packets[PACKET_bs].support == PACKET_ENABLE
9746 || remote_protocol_packets[PACKET_bc].support == PACKET_ENABLE)
9753 remote_supports_non_stop (void)
9759 remote_supports_disable_randomization (void)
9761 /* Only supported in extended mode. */
9766 remote_supports_multi_process (void)
9768 struct remote_state *rs = get_remote_state ();
9770 return remote_multi_process_p (rs);
9774 remote_supports_cond_tracepoints (void)
9776 struct remote_state *rs = get_remote_state ();
9778 return rs->cond_tracepoints;
9782 remote_supports_fast_tracepoints (void)
9784 struct remote_state *rs = get_remote_state ();
9786 return rs->fast_tracepoints;
9790 remote_supports_static_tracepoints (void)
9792 struct remote_state *rs = get_remote_state ();
9794 return rs->static_tracepoints;
9798 remote_supports_install_in_trace (void)
9800 struct remote_state *rs = get_remote_state ();
9802 return rs->install_in_trace;
9806 remote_supports_enable_disable_tracepoint (void)
9808 struct remote_state *rs = get_remote_state ();
9810 return rs->enable_disable_tracepoints;
9814 remote_supports_string_tracing (void)
9816 struct remote_state *rs = get_remote_state ();
9818 return rs->string_tracing;
9822 remote_trace_init (void)
9825 remote_get_noisy_reply (&target_buf, &target_buf_size);
9826 if (strcmp (target_buf, "OK") != 0)
9827 error (_("Target does not support this command."));
9830 static void free_actions_list (char **actions_list);
9831 static void free_actions_list_cleanup_wrapper (void *);
9833 free_actions_list_cleanup_wrapper (void *al)
9835 free_actions_list (al);
9839 free_actions_list (char **actions_list)
9843 if (actions_list == 0)
9846 for (ndx = 0; actions_list[ndx]; ndx++)
9847 xfree (actions_list[ndx]);
9849 xfree (actions_list);
9852 /* Recursive routine to walk through command list including loops, and
9853 download packets for each command. */
9856 remote_download_command_source (int num, ULONGEST addr,
9857 struct command_line *cmds)
9859 struct remote_state *rs = get_remote_state ();
9860 struct command_line *cmd;
9862 for (cmd = cmds; cmd; cmd = cmd->next)
9864 QUIT; /* Allow user to bail out with ^C. */
9865 strcpy (rs->buf, "QTDPsrc:");
9866 encode_source_string (num, addr, "cmd", cmd->line,
9867 rs->buf + strlen (rs->buf),
9868 rs->buf_size - strlen (rs->buf));
9870 remote_get_noisy_reply (&target_buf, &target_buf_size);
9871 if (strcmp (target_buf, "OK"))
9872 warning (_("Target does not support source download."));
9874 if (cmd->control_type == while_control
9875 || cmd->control_type == while_stepping_control)
9877 remote_download_command_source (num, addr, *cmd->body_list);
9879 QUIT; /* Allow user to bail out with ^C. */
9880 strcpy (rs->buf, "QTDPsrc:");
9881 encode_source_string (num, addr, "cmd", "end",
9882 rs->buf + strlen (rs->buf),
9883 rs->buf_size - strlen (rs->buf));
9885 remote_get_noisy_reply (&target_buf, &target_buf_size);
9886 if (strcmp (target_buf, "OK"))
9887 warning (_("Target does not support source download."));
9893 remote_download_tracepoint (struct bp_location *loc)
9900 char **stepping_actions;
9902 struct cleanup *old_chain = NULL;
9903 struct agent_expr *aexpr;
9904 struct cleanup *aexpr_chain = NULL;
9906 struct breakpoint *b = loc->owner;
9907 struct tracepoint *t = (struct tracepoint *) b;
9909 encode_actions (loc->owner, loc, &tdp_actions, &stepping_actions);
9910 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
9912 (void) make_cleanup (free_actions_list_cleanup_wrapper,
9915 tpaddr = loc->address;
9916 sprintf_vma (addrbuf, tpaddr);
9917 sprintf (buf, "QTDP:%x:%s:%c:%lx:%x", b->number,
9918 addrbuf, /* address */
9919 (b->enable_state == bp_enabled ? 'E' : 'D'),
9920 t->step_count, t->pass_count);
9921 /* Fast tracepoints are mostly handled by the target, but we can
9922 tell the target how big of an instruction block should be moved
9924 if (b->type == bp_fast_tracepoint)
9926 /* Only test for support at download time; we may not know
9927 target capabilities at definition time. */
9928 if (remote_supports_fast_tracepoints ())
9932 if (gdbarch_fast_tracepoint_valid_at (target_gdbarch,
9933 tpaddr, &isize, NULL))
9934 sprintf (buf + strlen (buf), ":F%x", isize);
9936 /* If it passed validation at definition but fails now,
9937 something is very wrong. */
9938 internal_error (__FILE__, __LINE__,
9939 _("Fast tracepoint not "
9940 "valid during download"));
9943 /* Fast tracepoints are functionally identical to regular
9944 tracepoints, so don't take lack of support as a reason to
9945 give up on the trace run. */
9946 warning (_("Target does not support fast tracepoints, "
9947 "downloading %d as regular tracepoint"), b->number);
9949 else if (b->type == bp_static_tracepoint)
9951 /* Only test for support at download time; we may not know
9952 target capabilities at definition time. */
9953 if (remote_supports_static_tracepoints ())
9955 struct static_tracepoint_marker marker;
9957 if (target_static_tracepoint_marker_at (tpaddr, &marker))
9960 error (_("Static tracepoint not valid during download"));
9963 /* Fast tracepoints are functionally identical to regular
9964 tracepoints, so don't take lack of support as a reason
9965 to give up on the trace run. */
9966 error (_("Target does not support static tracepoints"));
9968 /* If the tracepoint has a conditional, make it into an agent
9969 expression and append to the definition. */
9972 /* Only test support at download time, we may not know target
9973 capabilities at definition time. */
9974 if (remote_supports_cond_tracepoints ())
9976 aexpr = gen_eval_for_expr (tpaddr, loc->cond);
9977 aexpr_chain = make_cleanup_free_agent_expr (aexpr);
9978 sprintf (buf + strlen (buf), ":X%x,", aexpr->len);
9979 pkt = buf + strlen (buf);
9980 for (ndx = 0; ndx < aexpr->len; ++ndx)
9981 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
9983 do_cleanups (aexpr_chain);
9986 warning (_("Target does not support conditional tracepoints, "
9987 "ignoring tp %d cond"), b->number);
9990 if (b->commands || *default_collect)
9993 remote_get_noisy_reply (&target_buf, &target_buf_size);
9994 if (strcmp (target_buf, "OK"))
9995 error (_("Target does not support tracepoints."));
9997 /* do_single_steps (t); */
10000 for (ndx = 0; tdp_actions[ndx]; ndx++)
10002 QUIT; /* Allow user to bail out with ^C. */
10003 sprintf (buf, "QTDP:-%x:%s:%s%c",
10004 b->number, addrbuf, /* address */
10006 ((tdp_actions[ndx + 1] || stepping_actions)
10009 remote_get_noisy_reply (&target_buf,
10011 if (strcmp (target_buf, "OK"))
10012 error (_("Error on target while setting tracepoints."));
10015 if (stepping_actions)
10017 for (ndx = 0; stepping_actions[ndx]; ndx++)
10019 QUIT; /* Allow user to bail out with ^C. */
10020 sprintf (buf, "QTDP:-%x:%s:%s%s%s",
10021 b->number, addrbuf, /* address */
10022 ((ndx == 0) ? "S" : ""),
10023 stepping_actions[ndx],
10024 (stepping_actions[ndx + 1] ? "-" : ""));
10026 remote_get_noisy_reply (&target_buf,
10028 if (strcmp (target_buf, "OK"))
10029 error (_("Error on target while setting tracepoints."));
10033 if (remote_protocol_packets[PACKET_TracepointSource].support
10036 if (b->addr_string)
10038 strcpy (buf, "QTDPsrc:");
10039 encode_source_string (b->number, loc->address,
10040 "at", b->addr_string, buf + strlen (buf),
10041 2048 - strlen (buf));
10044 remote_get_noisy_reply (&target_buf, &target_buf_size);
10045 if (strcmp (target_buf, "OK"))
10046 warning (_("Target does not support source download."));
10048 if (b->cond_string)
10050 strcpy (buf, "QTDPsrc:");
10051 encode_source_string (b->number, loc->address,
10052 "cond", b->cond_string, buf + strlen (buf),
10053 2048 - strlen (buf));
10055 remote_get_noisy_reply (&target_buf, &target_buf_size);
10056 if (strcmp (target_buf, "OK"))
10057 warning (_("Target does not support source download."));
10059 remote_download_command_source (b->number, loc->address,
10060 breakpoint_commands (b));
10063 do_cleanups (old_chain);
10067 remote_can_download_tracepoint (void)
10069 struct remote_state *rs = get_remote_state ();
10070 struct trace_status *ts;
10073 /* Don't try to install tracepoints until we've relocated our
10074 symbols, and fetched and merged the target's tracepoint list with
10076 if (rs->starting_up)
10079 ts = current_trace_status ();
10080 status = remote_get_trace_status (ts);
10082 if (status == -1 || !ts->running_known || !ts->running)
10085 /* If we are in a tracing experiment, but remote stub doesn't support
10086 installing tracepoint in trace, we have to return. */
10087 if (!remote_supports_install_in_trace ())
10095 remote_download_trace_state_variable (struct trace_state_variable *tsv)
10097 struct remote_state *rs = get_remote_state ();
10100 sprintf (rs->buf, "QTDV:%x:%s:%x:",
10101 tsv->number, phex ((ULONGEST) tsv->initial_value, 8), tsv->builtin);
10102 p = rs->buf + strlen (rs->buf);
10103 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
10104 error (_("Trace state variable name too long for tsv definition packet"));
10105 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, 0);
10108 remote_get_noisy_reply (&target_buf, &target_buf_size);
10109 if (*target_buf == '\0')
10110 error (_("Target does not support this command."));
10111 if (strcmp (target_buf, "OK") != 0)
10112 error (_("Error on target while downloading trace state variable."));
10116 remote_enable_tracepoint (struct bp_location *location)
10118 struct remote_state *rs = get_remote_state ();
10121 sprintf_vma (addr_buf, location->address);
10122 sprintf (rs->buf, "QTEnable:%x:%s", location->owner->number, addr_buf);
10124 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
10125 if (*rs->buf == '\0')
10126 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
10127 if (strcmp (rs->buf, "OK") != 0)
10128 error (_("Error on target while enabling tracepoint."));
10132 remote_disable_tracepoint (struct bp_location *location)
10134 struct remote_state *rs = get_remote_state ();
10137 sprintf_vma (addr_buf, location->address);
10138 sprintf (rs->buf, "QTDisable:%x:%s", location->owner->number, addr_buf);
10140 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
10141 if (*rs->buf == '\0')
10142 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
10143 if (strcmp (rs->buf, "OK") != 0)
10144 error (_("Error on target while disabling tracepoint."));
10148 remote_trace_set_readonly_regions (void)
10151 bfd_size_type size;
10157 return; /* No information to give. */
10159 strcpy (target_buf, "QTro");
10160 for (s = exec_bfd->sections; s; s = s->next)
10162 char tmp1[40], tmp2[40];
10165 if ((s->flags & SEC_LOAD) == 0 ||
10166 /* (s->flags & SEC_CODE) == 0 || */
10167 (s->flags & SEC_READONLY) == 0)
10171 vma = bfd_get_section_vma (,s);
10172 size = bfd_get_section_size (s);
10173 sprintf_vma (tmp1, vma);
10174 sprintf_vma (tmp2, vma + size);
10175 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
10176 if (offset + sec_length + 1 > target_buf_size)
10178 if (remote_protocol_packets[PACKET_qXfer_traceframe_info].support
10181 Too many sections for read-only sections definition packet."));
10184 sprintf (target_buf + offset, ":%s,%s", tmp1, tmp2);
10185 offset += sec_length;
10189 putpkt (target_buf);
10190 getpkt (&target_buf, &target_buf_size, 0);
10195 remote_trace_start (void)
10197 putpkt ("QTStart");
10198 remote_get_noisy_reply (&target_buf, &target_buf_size);
10199 if (*target_buf == '\0')
10200 error (_("Target does not support this command."));
10201 if (strcmp (target_buf, "OK") != 0)
10202 error (_("Bogus reply from target: %s"), target_buf);
10206 remote_get_trace_status (struct trace_status *ts)
10208 /* Initialize it just to avoid a GCC false warning. */
10210 /* FIXME we need to get register block size some other way. */
10211 extern int trace_regblock_size;
10212 volatile struct gdb_exception ex;
10214 trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
10216 putpkt ("qTStatus");
10218 TRY_CATCH (ex, RETURN_MASK_ERROR)
10220 p = remote_get_noisy_reply (&target_buf, &target_buf_size);
10224 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
10228 /* If the remote target doesn't do tracing, flag it. */
10232 /* We're working with a live target. */
10235 /* Set some defaults. */
10236 ts->running_known = 0;
10237 ts->stop_reason = trace_stop_reason_unknown;
10238 ts->traceframe_count = -1;
10239 ts->buffer_free = 0;
10242 error (_("Bogus trace status reply from target: %s"), target_buf);
10244 parse_trace_status (p, ts);
10246 return ts->running;
10250 remote_get_tracepoint_status (struct breakpoint *bp,
10251 struct uploaded_tp *utp)
10253 struct remote_state *rs = get_remote_state ();
10255 struct bp_location *loc;
10256 struct tracepoint *tp = (struct tracepoint *) bp;
10260 tp->base.hit_count = 0;
10261 tp->traceframe_usage = 0;
10262 for (loc = tp->base.loc; loc; loc = loc->next)
10264 /* If the tracepoint was never downloaded, don't go asking for
10266 if (tp->number_on_target == 0)
10268 sprintf (rs->buf, "qTP:%x:%s", tp->number_on_target,
10269 phex_nz (loc->address, 0));
10271 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10272 if (reply && *reply)
10275 parse_tracepoint_status (reply + 1, bp, utp);
10281 utp->hit_count = 0;
10282 utp->traceframe_usage = 0;
10283 sprintf (rs->buf, "qTP:%x:%s", utp->number, phex_nz (utp->addr, 0));
10285 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10286 if (reply && *reply)
10289 parse_tracepoint_status (reply + 1, bp, utp);
10295 remote_trace_stop (void)
10298 remote_get_noisy_reply (&target_buf, &target_buf_size);
10299 if (*target_buf == '\0')
10300 error (_("Target does not support this command."));
10301 if (strcmp (target_buf, "OK") != 0)
10302 error (_("Bogus reply from target: %s"), target_buf);
10306 remote_trace_find (enum trace_find_type type, int num,
10307 ULONGEST addr1, ULONGEST addr2,
10310 struct remote_state *rs = get_remote_state ();
10312 int target_frameno = -1, target_tracept = -1;
10314 /* Lookups other than by absolute frame number depend on the current
10315 trace selected, so make sure it is correct on the remote end
10317 if (type != tfind_number)
10318 set_remote_traceframe ();
10321 strcpy (p, "QTFrame:");
10322 p = strchr (p, '\0');
10326 sprintf (p, "%x", num);
10329 sprintf (p, "pc:%s", phex_nz (addr1, 0));
10332 sprintf (p, "tdp:%x", num);
10335 sprintf (p, "range:%s:%s", phex_nz (addr1, 0), phex_nz (addr2, 0));
10337 case tfind_outside:
10338 sprintf (p, "outside:%s:%s", phex_nz (addr1, 0), phex_nz (addr2, 0));
10341 error (_("Unknown trace find type %d"), type);
10345 reply = remote_get_noisy_reply (&(rs->buf), &sizeof_pkt);
10346 if (*reply == '\0')
10347 error (_("Target does not support this command."));
10349 while (reply && *reply)
10354 target_frameno = (int) strtol (p, &reply, 16);
10356 error (_("Unable to parse trace frame number"));
10357 /* Don't update our remote traceframe number cache on failure
10358 to select a remote traceframe. */
10359 if (target_frameno == -1)
10364 target_tracept = (int) strtol (p, &reply, 16);
10366 error (_("Unable to parse tracepoint number"));
10368 case 'O': /* "OK"? */
10369 if (reply[1] == 'K' && reply[2] == '\0')
10372 error (_("Bogus reply from target: %s"), reply);
10375 error (_("Bogus reply from target: %s"), reply);
10378 *tpp = target_tracept;
10380 remote_traceframe_number = target_frameno;
10381 return target_frameno;
10385 remote_get_trace_state_variable_value (int tsvnum, LONGEST *val)
10387 struct remote_state *rs = get_remote_state ();
10391 set_remote_traceframe ();
10393 sprintf (rs->buf, "qTV:%x", tsvnum);
10395 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10396 if (reply && *reply)
10400 unpack_varlen_hex (reply + 1, &uval);
10401 *val = (LONGEST) uval;
10409 remote_save_trace_data (const char *filename)
10411 struct remote_state *rs = get_remote_state ();
10415 strcpy (p, "QTSave:");
10417 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
10418 error (_("Remote file name too long for trace save packet"));
10419 p += 2 * bin2hex ((gdb_byte *) filename, p, 0);
10422 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10423 if (*reply == '\0')
10424 error (_("Target does not support this command."));
10425 if (strcmp (reply, "OK") != 0)
10426 error (_("Bogus reply from target: %s"), reply);
10430 /* This is basically a memory transfer, but needs to be its own packet
10431 because we don't know how the target actually organizes its trace
10432 memory, plus we want to be able to ask for as much as possible, but
10433 not be unhappy if we don't get as much as we ask for. */
10436 remote_get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
10438 struct remote_state *rs = get_remote_state ();
10444 strcpy (p, "qTBuffer:");
10446 p += hexnumstr (p, offset);
10448 p += hexnumstr (p, len);
10452 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10453 if (reply && *reply)
10455 /* 'l' by itself means we're at the end of the buffer and
10456 there is nothing more to get. */
10460 /* Convert the reply into binary. Limit the number of bytes to
10461 convert according to our passed-in buffer size, rather than
10462 what was returned in the packet; if the target is
10463 unexpectedly generous and gives us a bigger reply than we
10464 asked for, we don't want to crash. */
10465 rslt = hex2bin (target_buf, buf, len);
10469 /* Something went wrong, flag as an error. */
10474 remote_set_disconnected_tracing (int val)
10476 struct remote_state *rs = get_remote_state ();
10478 if (rs->disconnected_tracing)
10482 sprintf (rs->buf, "QTDisconnected:%x", val);
10484 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10485 if (*reply == '\0')
10486 error (_("Target does not support this command."));
10487 if (strcmp (reply, "OK") != 0)
10488 error (_("Bogus reply from target: %s"), reply);
10491 warning (_("Target does not support disconnected tracing."));
10495 remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
10497 struct thread_info *info = find_thread_ptid (ptid);
10499 if (info && info->private)
10500 return info->private->core;
10505 remote_set_circular_trace_buffer (int val)
10507 struct remote_state *rs = get_remote_state ();
10510 sprintf (rs->buf, "QTBuffer:circular:%x", val);
10512 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10513 if (*reply == '\0')
10514 error (_("Target does not support this command."));
10515 if (strcmp (reply, "OK") != 0)
10516 error (_("Bogus reply from target: %s"), reply);
10519 static struct traceframe_info *
10520 remote_traceframe_info (void)
10524 text = target_read_stralloc (¤t_target,
10525 TARGET_OBJECT_TRACEFRAME_INFO, NULL);
10528 struct traceframe_info *info;
10529 struct cleanup *back_to = make_cleanup (xfree, text);
10531 info = parse_traceframe_info (text);
10532 do_cleanups (back_to);
10539 /* Handle the qTMinFTPILen packet. Returns the minimum length of
10540 instruction on which a fast tracepoint may be placed. Returns -1
10541 if the packet is not supported, and 0 if the minimum instruction
10542 length is unknown. */
10545 remote_get_min_fast_tracepoint_insn_len (void)
10547 struct remote_state *rs = get_remote_state ();
10550 sprintf (rs->buf, "qTMinFTPILen");
10552 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10553 if (*reply == '\0')
10557 ULONGEST min_insn_len;
10559 unpack_varlen_hex (reply, &min_insn_len);
10561 return (int) min_insn_len;
10566 remote_set_trace_notes (char *user, char *notes, char *stop_notes)
10568 struct remote_state *rs = get_remote_state ();
10570 char *buf = rs->buf;
10571 char *endbuf = rs->buf + get_remote_packet_size ();
10574 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
10577 buf += xsnprintf (buf, endbuf - buf, "user:");
10578 nbytes = bin2hex (user, buf, 0);
10584 buf += xsnprintf (buf, endbuf - buf, "notes:");
10585 nbytes = bin2hex (notes, buf, 0);
10591 buf += xsnprintf (buf, endbuf - buf, "tstop:");
10592 nbytes = bin2hex (stop_notes, buf, 0);
10596 /* Ensure the buffer is terminated. */
10600 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10601 if (*reply == '\0')
10604 if (strcmp (reply, "OK") != 0)
10605 error (_("Bogus reply from target: %s"), reply);
10611 init_remote_ops (void)
10613 remote_ops.to_shortname = "remote";
10614 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
10615 remote_ops.to_doc =
10616 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
10617 Specify the serial device it is connected to\n\
10618 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
10619 remote_ops.to_open = remote_open;
10620 remote_ops.to_close = remote_close;
10621 remote_ops.to_detach = remote_detach;
10622 remote_ops.to_disconnect = remote_disconnect;
10623 remote_ops.to_resume = remote_resume;
10624 remote_ops.to_wait = remote_wait;
10625 remote_ops.to_fetch_registers = remote_fetch_registers;
10626 remote_ops.to_store_registers = remote_store_registers;
10627 remote_ops.to_prepare_to_store = remote_prepare_to_store;
10628 remote_ops.deprecated_xfer_memory = remote_xfer_memory;
10629 remote_ops.to_files_info = remote_files_info;
10630 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
10631 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
10632 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
10633 remote_ops.to_stopped_data_address = remote_stopped_data_address;
10634 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
10635 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
10636 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
10637 remote_ops.to_region_ok_for_hw_watchpoint
10638 = remote_region_ok_for_hw_watchpoint;
10639 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
10640 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
10641 remote_ops.to_kill = remote_kill;
10642 remote_ops.to_load = generic_load;
10643 remote_ops.to_mourn_inferior = remote_mourn;
10644 remote_ops.to_pass_signals = remote_pass_signals;
10645 remote_ops.to_thread_alive = remote_thread_alive;
10646 remote_ops.to_find_new_threads = remote_threads_info;
10647 remote_ops.to_pid_to_str = remote_pid_to_str;
10648 remote_ops.to_extra_thread_info = remote_threads_extra_info;
10649 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
10650 remote_ops.to_stop = remote_stop;
10651 remote_ops.to_xfer_partial = remote_xfer_partial;
10652 remote_ops.to_rcmd = remote_rcmd;
10653 remote_ops.to_log_command = serial_log_command;
10654 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
10655 remote_ops.to_stratum = process_stratum;
10656 remote_ops.to_has_all_memory = default_child_has_all_memory;
10657 remote_ops.to_has_memory = default_child_has_memory;
10658 remote_ops.to_has_stack = default_child_has_stack;
10659 remote_ops.to_has_registers = default_child_has_registers;
10660 remote_ops.to_has_execution = default_child_has_execution;
10661 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
10662 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
10663 remote_ops.to_magic = OPS_MAGIC;
10664 remote_ops.to_memory_map = remote_memory_map;
10665 remote_ops.to_flash_erase = remote_flash_erase;
10666 remote_ops.to_flash_done = remote_flash_done;
10667 remote_ops.to_read_description = remote_read_description;
10668 remote_ops.to_search_memory = remote_search_memory;
10669 remote_ops.to_can_async_p = remote_can_async_p;
10670 remote_ops.to_is_async_p = remote_is_async_p;
10671 remote_ops.to_async = remote_async;
10672 remote_ops.to_terminal_inferior = remote_terminal_inferior;
10673 remote_ops.to_terminal_ours = remote_terminal_ours;
10674 remote_ops.to_supports_non_stop = remote_supports_non_stop;
10675 remote_ops.to_supports_multi_process = remote_supports_multi_process;
10676 remote_ops.to_supports_disable_randomization
10677 = remote_supports_disable_randomization;
10678 remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
10679 remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
10680 remote_ops.to_trace_init = remote_trace_init;
10681 remote_ops.to_download_tracepoint = remote_download_tracepoint;
10682 remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
10683 remote_ops.to_download_trace_state_variable
10684 = remote_download_trace_state_variable;
10685 remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
10686 remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
10687 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
10688 remote_ops.to_trace_start = remote_trace_start;
10689 remote_ops.to_get_trace_status = remote_get_trace_status;
10690 remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
10691 remote_ops.to_trace_stop = remote_trace_stop;
10692 remote_ops.to_trace_find = remote_trace_find;
10693 remote_ops.to_get_trace_state_variable_value
10694 = remote_get_trace_state_variable_value;
10695 remote_ops.to_save_trace_data = remote_save_trace_data;
10696 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
10697 remote_ops.to_upload_trace_state_variables
10698 = remote_upload_trace_state_variables;
10699 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
10700 remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
10701 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
10702 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
10703 remote_ops.to_set_trace_notes = remote_set_trace_notes;
10704 remote_ops.to_core_of_thread = remote_core_of_thread;
10705 remote_ops.to_verify_memory = remote_verify_memory;
10706 remote_ops.to_get_tib_address = remote_get_tib_address;
10707 remote_ops.to_set_permissions = remote_set_permissions;
10708 remote_ops.to_static_tracepoint_marker_at
10709 = remote_static_tracepoint_marker_at;
10710 remote_ops.to_static_tracepoint_markers_by_strid
10711 = remote_static_tracepoint_markers_by_strid;
10712 remote_ops.to_traceframe_info = remote_traceframe_info;
10715 /* Set up the extended remote vector by making a copy of the standard
10716 remote vector and adding to it. */
10719 init_extended_remote_ops (void)
10721 extended_remote_ops = remote_ops;
10723 extended_remote_ops.to_shortname = "extended-remote";
10724 extended_remote_ops.to_longname =
10725 "Extended remote serial target in gdb-specific protocol";
10726 extended_remote_ops.to_doc =
10727 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
10728 Specify the serial device it is connected to (e.g. /dev/ttya).";
10729 extended_remote_ops.to_open = extended_remote_open;
10730 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
10731 extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
10732 extended_remote_ops.to_detach = extended_remote_detach;
10733 extended_remote_ops.to_attach = extended_remote_attach;
10734 extended_remote_ops.to_kill = extended_remote_kill;
10735 extended_remote_ops.to_supports_disable_randomization
10736 = extended_remote_supports_disable_randomization;
10740 remote_can_async_p (void)
10742 if (!target_async_permitted)
10743 /* We only enable async when the user specifically asks for it. */
10746 /* We're async whenever the serial device is. */
10747 return serial_can_async_p (remote_desc);
10751 remote_is_async_p (void)
10753 if (!target_async_permitted)
10754 /* We only enable async when the user specifically asks for it. */
10757 /* We're async whenever the serial device is. */
10758 return serial_is_async_p (remote_desc);
10761 /* Pass the SERIAL event on and up to the client. One day this code
10762 will be able to delay notifying the client of an event until the
10763 point where an entire packet has been received. */
10765 static void (*async_client_callback) (enum inferior_event_type event_type,
10767 static void *async_client_context;
10768 static serial_event_ftype remote_async_serial_handler;
10771 remote_async_serial_handler (struct serial *scb, void *context)
10773 /* Don't propogate error information up to the client. Instead let
10774 the client find out about the error by querying the target. */
10775 async_client_callback (INF_REG_EVENT, async_client_context);
10779 remote_async_inferior_event_handler (gdb_client_data data)
10781 inferior_event_handler (INF_REG_EVENT, NULL);
10785 remote_async_get_pending_events_handler (gdb_client_data data)
10787 remote_get_pending_stop_replies ();
10791 remote_async (void (*callback) (enum inferior_event_type event_type,
10792 void *context), void *context)
10794 if (callback != NULL)
10796 serial_async (remote_desc, remote_async_serial_handler, NULL);
10797 async_client_callback = callback;
10798 async_client_context = context;
10801 serial_async (remote_desc, NULL, NULL);
10805 set_remote_cmd (char *args, int from_tty)
10807 help_list (remote_set_cmdlist, "set remote ", -1, gdb_stdout);
10811 show_remote_cmd (char *args, int from_tty)
10813 /* We can't just use cmd_show_list here, because we want to skip
10814 the redundant "show remote Z-packet" and the legacy aliases. */
10815 struct cleanup *showlist_chain;
10816 struct cmd_list_element *list = remote_show_cmdlist;
10817 struct ui_out *uiout = current_uiout;
10819 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
10820 for (; list != NULL; list = list->next)
10821 if (strcmp (list->name, "Z-packet") == 0)
10823 else if (list->type == not_set_cmd)
10824 /* Alias commands are exactly like the original, except they
10825 don't have the normal type. */
10829 struct cleanup *option_chain
10830 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
10832 ui_out_field_string (uiout, "name", list->name);
10833 ui_out_text (uiout, ": ");
10834 if (list->type == show_cmd)
10835 do_setshow_command ((char *) NULL, from_tty, list);
10837 cmd_func (list, NULL, from_tty);
10838 /* Close the tuple. */
10839 do_cleanups (option_chain);
10842 /* Close the tuple. */
10843 do_cleanups (showlist_chain);
10847 /* Function to be called whenever a new objfile (shlib) is detected. */
10849 remote_new_objfile (struct objfile *objfile)
10851 if (remote_desc != 0) /* Have a remote connection. */
10852 remote_check_symbols (objfile);
10855 /* Pull all the tracepoints defined on the target and create local
10856 data structures representing them. We don't want to create real
10857 tracepoints yet, we don't want to mess up the user's existing
10861 remote_upload_tracepoints (struct uploaded_tp **utpp)
10863 struct remote_state *rs = get_remote_state ();
10866 /* Ask for a first packet of tracepoint definition. */
10868 getpkt (&rs->buf, &rs->buf_size, 0);
10870 while (*p && *p != 'l')
10872 parse_tracepoint_definition (p, utpp);
10873 /* Ask for another packet of tracepoint definition. */
10875 getpkt (&rs->buf, &rs->buf_size, 0);
10882 remote_upload_trace_state_variables (struct uploaded_tsv **utsvp)
10884 struct remote_state *rs = get_remote_state ();
10887 /* Ask for a first packet of variable definition. */
10889 getpkt (&rs->buf, &rs->buf_size, 0);
10891 while (*p && *p != 'l')
10893 parse_tsv_definition (p, utsvp);
10894 /* Ask for another packet of variable definition. */
10896 getpkt (&rs->buf, &rs->buf_size, 0);
10903 _initialize_remote (void)
10905 struct remote_state *rs;
10906 struct cmd_list_element *cmd;
10909 /* architecture specific data */
10910 remote_gdbarch_data_handle =
10911 gdbarch_data_register_post_init (init_remote_state);
10912 remote_g_packet_data_handle =
10913 gdbarch_data_register_pre_init (remote_g_packet_data_init);
10915 /* Initialize the per-target state. At the moment there is only one
10916 of these, not one per target. Only one target is active at a
10917 time. The default buffer size is unimportant; it will be expanded
10918 whenever a larger buffer is needed. */
10919 rs = get_remote_state_raw ();
10920 rs->buf_size = 400;
10921 rs->buf = xmalloc (rs->buf_size);
10923 init_remote_ops ();
10924 add_target (&remote_ops);
10926 init_extended_remote_ops ();
10927 add_target (&extended_remote_ops);
10929 /* Hook into new objfile notification. */
10930 observer_attach_new_objfile (remote_new_objfile);
10932 /* Set up signal handlers. */
10933 sigint_remote_token =
10934 create_async_signal_handler (async_remote_interrupt, NULL);
10935 sigint_remote_twice_token =
10936 create_async_signal_handler (async_remote_interrupt_twice, NULL);
10939 init_remote_threadtests ();
10942 /* set/show remote ... */
10944 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
10945 Remote protocol specific variables\n\
10946 Configure various remote-protocol specific variables such as\n\
10947 the packets being used"),
10948 &remote_set_cmdlist, "set remote ",
10949 0 /* allow-unknown */, &setlist);
10950 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
10951 Remote protocol specific variables\n\
10952 Configure various remote-protocol specific variables such as\n\
10953 the packets being used"),
10954 &remote_show_cmdlist, "show remote ",
10955 0 /* allow-unknown */, &showlist);
10957 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
10958 Compare section data on target to the exec file.\n\
10959 Argument is a single section name (default: all loaded sections)."),
10962 add_cmd ("packet", class_maintenance, packet_command, _("\
10963 Send an arbitrary packet to a remote target.\n\
10964 maintenance packet TEXT\n\
10965 If GDB is talking to an inferior via the GDB serial protocol, then\n\
10966 this command sends the string TEXT to the inferior, and displays the\n\
10967 response packet. GDB supplies the initial `$' character, and the\n\
10968 terminating `#' character and checksum."),
10971 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
10972 Set whether to send break if interrupted."), _("\
10973 Show whether to send break if interrupted."), _("\
10974 If set, a break, instead of a cntrl-c, is sent to the remote target."),
10975 set_remotebreak, show_remotebreak,
10976 &setlist, &showlist);
10977 cmd_name = "remotebreak";
10978 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
10979 deprecate_cmd (cmd, "set remote interrupt-sequence");
10980 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
10981 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
10982 deprecate_cmd (cmd, "show remote interrupt-sequence");
10984 add_setshow_enum_cmd ("interrupt-sequence", class_support,
10985 interrupt_sequence_modes, &interrupt_sequence_mode,
10987 Set interrupt sequence to remote target."), _("\
10988 Show interrupt sequence to remote target."), _("\
10989 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
10990 NULL, show_interrupt_sequence,
10991 &remote_set_cmdlist,
10992 &remote_show_cmdlist);
10994 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
10995 &interrupt_on_connect, _("\
10996 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
10997 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
10998 If set, interrupt sequence is sent to remote target."),
11000 &remote_set_cmdlist, &remote_show_cmdlist);
11002 /* Install commands for configuring memory read/write packets. */
11004 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
11005 Set the maximum number of bytes per memory write packet (deprecated)."),
11007 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
11008 Show the maximum number of bytes per memory write packet (deprecated)."),
11010 add_cmd ("memory-write-packet-size", no_class,
11011 set_memory_write_packet_size, _("\
11012 Set the maximum number of bytes per memory-write packet.\n\
11013 Specify the number of bytes in a packet or 0 (zero) for the\n\
11014 default packet size. The actual limit is further reduced\n\
11015 dependent on the target. Specify ``fixed'' to disable the\n\
11016 further restriction and ``limit'' to enable that restriction."),
11017 &remote_set_cmdlist);
11018 add_cmd ("memory-read-packet-size", no_class,
11019 set_memory_read_packet_size, _("\
11020 Set the maximum number of bytes per memory-read packet.\n\
11021 Specify the number of bytes in a packet or 0 (zero) for the\n\
11022 default packet size. The actual limit is further reduced\n\
11023 dependent on the target. Specify ``fixed'' to disable the\n\
11024 further restriction and ``limit'' to enable that restriction."),
11025 &remote_set_cmdlist);
11026 add_cmd ("memory-write-packet-size", no_class,
11027 show_memory_write_packet_size,
11028 _("Show the maximum number of bytes per memory-write packet."),
11029 &remote_show_cmdlist);
11030 add_cmd ("memory-read-packet-size", no_class,
11031 show_memory_read_packet_size,
11032 _("Show the maximum number of bytes per memory-read packet."),
11033 &remote_show_cmdlist);
11035 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
11036 &remote_hw_watchpoint_limit, _("\
11037 Set the maximum number of target hardware watchpoints."), _("\
11038 Show the maximum number of target hardware watchpoints."), _("\
11039 Specify a negative limit for unlimited."),
11040 NULL, NULL, /* FIXME: i18n: The maximum
11041 number of target hardware
11042 watchpoints is %s. */
11043 &remote_set_cmdlist, &remote_show_cmdlist);
11044 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
11045 &remote_hw_watchpoint_length_limit, _("\
11046 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
11047 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
11048 Specify a negative limit for unlimited."),
11049 NULL, NULL, /* FIXME: i18n: The maximum
11050 length (in bytes) of a target
11051 hardware watchpoint is %s. */
11052 &remote_set_cmdlist, &remote_show_cmdlist);
11053 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
11054 &remote_hw_breakpoint_limit, _("\
11055 Set the maximum number of target hardware breakpoints."), _("\
11056 Show the maximum number of target hardware breakpoints."), _("\
11057 Specify a negative limit for unlimited."),
11058 NULL, NULL, /* FIXME: i18n: The maximum
11059 number of target hardware
11060 breakpoints is %s. */
11061 &remote_set_cmdlist, &remote_show_cmdlist);
11063 add_setshow_integer_cmd ("remoteaddresssize", class_obscure,
11064 &remote_address_size, _("\
11065 Set the maximum size of the address (in bits) in a memory packet."), _("\
11066 Show the maximum size of the address (in bits) in a memory packet."), NULL,
11068 NULL, /* FIXME: i18n: */
11069 &setlist, &showlist);
11071 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
11072 "X", "binary-download", 1);
11074 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
11075 "vCont", "verbose-resume", 0);
11077 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
11078 "QPassSignals", "pass-signals", 0);
11080 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
11081 "qSymbol", "symbol-lookup", 0);
11083 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
11084 "P", "set-register", 1);
11086 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
11087 "p", "fetch-register", 1);
11089 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
11090 "Z0", "software-breakpoint", 0);
11092 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
11093 "Z1", "hardware-breakpoint", 0);
11095 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
11096 "Z2", "write-watchpoint", 0);
11098 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
11099 "Z3", "read-watchpoint", 0);
11101 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
11102 "Z4", "access-watchpoint", 0);
11104 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
11105 "qXfer:auxv:read", "read-aux-vector", 0);
11107 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
11108 "qXfer:features:read", "target-features", 0);
11110 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
11111 "qXfer:libraries:read", "library-info", 0);
11113 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
11114 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
11116 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
11117 "qXfer:memory-map:read", "memory-map", 0);
11119 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
11120 "qXfer:spu:read", "read-spu-object", 0);
11122 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
11123 "qXfer:spu:write", "write-spu-object", 0);
11125 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
11126 "qXfer:osdata:read", "osdata", 0);
11128 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
11129 "qXfer:threads:read", "threads", 0);
11131 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
11132 "qXfer:siginfo:read", "read-siginfo-object", 0);
11134 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
11135 "qXfer:siginfo:write", "write-siginfo-object", 0);
11137 add_packet_config_cmd
11138 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
11139 "qXfer:trace-frame-info:read", "traceframe-info", 0);
11141 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
11142 "qGetTLSAddr", "get-thread-local-storage-address",
11145 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
11146 "qGetTIBAddr", "get-thread-information-block-address",
11149 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
11150 "bc", "reverse-continue", 0);
11152 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
11153 "bs", "reverse-step", 0);
11155 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
11156 "qSupported", "supported-packets", 0);
11158 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
11159 "qSearch:memory", "search-memory", 0);
11161 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
11162 "vFile:open", "hostio-open", 0);
11164 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
11165 "vFile:pread", "hostio-pread", 0);
11167 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
11168 "vFile:pwrite", "hostio-pwrite", 0);
11170 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
11171 "vFile:close", "hostio-close", 0);
11173 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
11174 "vFile:unlink", "hostio-unlink", 0);
11176 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
11177 "vAttach", "attach", 0);
11179 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
11182 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
11183 "QStartNoAckMode", "noack", 0);
11185 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
11186 "vKill", "kill", 0);
11188 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
11189 "qAttached", "query-attached", 0);
11191 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
11192 "ConditionalTracepoints",
11193 "conditional-tracepoints", 0);
11194 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
11195 "FastTracepoints", "fast-tracepoints", 0);
11197 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
11198 "TracepointSource", "TracepointSource", 0);
11200 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
11201 "QAllow", "allow", 0);
11203 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
11204 "StaticTracepoints", "static-tracepoints", 0);
11206 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
11207 "InstallInTrace", "install-in-trace", 0);
11209 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
11210 "qXfer:statictrace:read", "read-sdata-object", 0);
11212 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
11213 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
11215 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
11216 "QDisableRandomization", "disable-randomization", 0);
11218 /* Keep the old ``set remote Z-packet ...'' working. Each individual
11219 Z sub-packet has its own set and show commands, but users may
11220 have sets to this variable in their .gdbinit files (or in their
11222 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
11223 &remote_Z_packet_detect, _("\
11224 Set use of remote protocol `Z' packets"), _("\
11225 Show use of remote protocol `Z' packets "), _("\
11226 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
11228 set_remote_protocol_Z_packet_cmd,
11229 show_remote_protocol_Z_packet_cmd,
11230 /* FIXME: i18n: Use of remote protocol
11231 `Z' packets is %s. */
11232 &remote_set_cmdlist, &remote_show_cmdlist);
11234 add_prefix_cmd ("remote", class_files, remote_command, _("\
11235 Manipulate files on the remote system\n\
11236 Transfer files to and from the remote target system."),
11237 &remote_cmdlist, "remote ",
11238 0 /* allow-unknown */, &cmdlist);
11240 add_cmd ("put", class_files, remote_put_command,
11241 _("Copy a local file to the remote system."),
11244 add_cmd ("get", class_files, remote_get_command,
11245 _("Copy a remote file to the local system."),
11248 add_cmd ("delete", class_files, remote_delete_command,
11249 _("Delete a remote file."),
11252 remote_exec_file = xstrdup ("");
11253 add_setshow_string_noescape_cmd ("exec-file", class_files,
11254 &remote_exec_file, _("\
11255 Set the remote pathname for \"run\""), _("\
11256 Show the remote pathname for \"run\""), NULL, NULL, NULL,
11257 &remote_set_cmdlist, &remote_show_cmdlist);
11259 /* Eventually initialize fileio. See fileio.c */
11260 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
11262 /* Take advantage of the fact that the LWP field is not used, to tag
11263 special ptids with it set to != 0. */
11264 magic_null_ptid = ptid_build (42000, 1, -1);
11265 not_sent_ptid = ptid_build (42000, 1, -2);
11266 any_thread_ptid = ptid_build (42000, 1, 0);
11268 target_buf_size = 2048;
11269 target_buf = xmalloc (target_buf_size);