1 /* Remote target communications for serial-line targets in custom GDB protocol
3 Copyright (C) 1988-2015 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. */
30 /*#include "terminal.h" */
33 #include "gdb-stabs.h"
34 #include "gdbthread.h"
36 #include "remote-notif.h"
41 #include "cli/cli-decode.h"
42 #include "cli/cli-setshow.h"
43 #include "target-descriptions.h"
45 #include "filestuff.h"
50 #include "event-loop.h"
51 #include "event-top.h"
57 #include "gdbcore.h" /* for exec_bfd */
59 #include "remote-fileio.h"
60 #include "gdb/fileio.h"
62 #include "xml-support.h"
64 #include "memory-map.h"
66 #include "tracepoint.h"
72 /* Temp hacks for tracepoint encoding migration. */
73 static char *target_buf;
74 static long target_buf_size;
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 async_cleanup_sigint_signal_handler (void *dummy);
90 static int getpkt_sane (char **buf, long *sizeof_buf, int forever);
91 static int getpkt_or_notif_sane (char **buf, long *sizeof_buf,
92 int forever, int *is_notif);
94 static void async_handle_remote_sigint (int);
95 static void async_handle_remote_sigint_twice (int);
97 static void remote_files_info (struct target_ops *ignore);
99 static void remote_prepare_to_store (struct target_ops *self,
100 struct regcache *regcache);
102 static void remote_open_1 (const char *, int, struct target_ops *,
105 static void remote_close (struct target_ops *self);
107 static void remote_mourn (struct target_ops *ops);
109 static void extended_remote_restart (void);
111 static void extended_remote_mourn (struct target_ops *);
113 static void remote_mourn_1 (struct target_ops *);
115 static void remote_send (char **buf, long *sizeof_buf_p);
117 static int readchar (int timeout);
119 static void remote_serial_write (const char *str, int len);
121 static void remote_kill (struct target_ops *ops);
123 static int remote_can_async_p (struct target_ops *);
125 static int remote_is_async_p (struct target_ops *);
127 static void remote_async (struct target_ops *ops,
128 void (*callback) (enum inferior_event_type event_type,
132 static void sync_remote_interrupt_twice (int signo);
134 static void interrupt_query (void);
136 static void set_general_thread (struct ptid ptid);
137 static void set_continue_thread (struct ptid ptid);
139 static void get_offsets (void);
141 static void skip_frame (void);
143 static long read_frame (char **buf_p, long *sizeof_buf);
145 static int hexnumlen (ULONGEST num);
147 static void init_remote_ops (void);
149 static void init_extended_remote_ops (void);
151 static void remote_stop (struct target_ops *self, ptid_t);
153 static int stubhex (int ch);
155 static int hexnumstr (char *, ULONGEST);
157 static int hexnumnstr (char *, ULONGEST, int);
159 static CORE_ADDR remote_address_masked (CORE_ADDR);
161 static void print_packet (const char *);
163 static void compare_sections_command (char *, int);
165 static void packet_command (char *, int);
167 static int stub_unpack_int (char *buff, int fieldlength);
169 static ptid_t remote_current_thread (ptid_t oldptid);
171 static int putpkt_binary (const char *buf, int cnt);
173 static void check_binary_download (CORE_ADDR addr);
175 struct packet_config;
177 static void show_packet_config_cmd (struct packet_config *config);
179 static void show_remote_protocol_packet_cmd (struct ui_file *file,
181 struct cmd_list_element *c,
184 static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
185 static ptid_t read_ptid (char *buf, char **obuf);
187 static void remote_set_permissions (struct target_ops *self);
190 static int remote_get_trace_status (struct target_ops *self,
191 struct trace_status *ts);
193 static int remote_upload_tracepoints (struct target_ops *self,
194 struct uploaded_tp **utpp);
196 static int remote_upload_trace_state_variables (struct target_ops *self,
197 struct uploaded_tsv **utsvp);
199 static void remote_query_supported (void);
201 static void remote_check_symbols (void);
203 void _initialize_remote (void);
206 static void stop_reply_xfree (struct stop_reply *);
207 static void remote_parse_stop_reply (char *, struct stop_reply *);
208 static void push_stop_reply (struct stop_reply *);
209 static void discard_pending_stop_replies_in_queue (struct remote_state *);
210 static int peek_stop_reply (ptid_t ptid);
212 static void remote_async_inferior_event_handler (gdb_client_data);
214 static void remote_terminal_ours (struct target_ops *self);
216 static int remote_read_description_p (struct target_ops *target);
218 static void remote_console_output (char *msg);
220 static int remote_supports_cond_breakpoints (struct target_ops *self);
222 static int remote_can_run_breakpoint_commands (struct target_ops *self);
224 static void remote_btrace_reset (void);
228 static struct cmd_list_element *remote_cmdlist;
230 /* For "set remote" and "show remote". */
232 static struct cmd_list_element *remote_set_cmdlist;
233 static struct cmd_list_element *remote_show_cmdlist;
235 /* Stub vCont actions support.
237 Each field is a boolean flag indicating whether the stub reports
238 support for the corresponding action. */
240 struct vCont_action_support
249 /* Controls whether GDB is willing to use range stepping. */
251 static int use_range_stepping = 1;
253 #define OPAQUETHREADBYTES 8
255 /* a 64 bit opaque identifier */
256 typedef unsigned char threadref[OPAQUETHREADBYTES];
258 /* About this many threadisds fit in a packet. */
260 #define MAXTHREADLISTRESULTS 32
262 /* Description of the remote protocol state for the currently
263 connected target. This is per-target state, and independent of the
264 selected architecture. */
268 /* A buffer to use for incoming packets, and its current size. The
269 buffer is grown dynamically for larger incoming packets.
270 Outgoing packets may also be constructed in this buffer.
271 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
272 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
277 /* True if we're going through initial connection setup (finding out
278 about the remote side's threads, relocating symbols, etc.). */
281 /* If we negotiated packet size explicitly (and thus can bypass
282 heuristics for the largest packet size that will not overflow
283 a buffer in the stub), this will be set to that packet size.
284 Otherwise zero, meaning to use the guessed size. */
285 long explicit_packet_size;
287 /* remote_wait is normally called when the target is running and
288 waits for a stop reply packet. But sometimes we need to call it
289 when the target is already stopped. We can send a "?" packet
290 and have remote_wait read the response. Or, if we already have
291 the response, we can stash it in BUF and tell remote_wait to
292 skip calling getpkt. This flag is set when BUF contains a
293 stop reply packet and the target is not waiting. */
294 int cached_wait_status;
296 /* True, if in no ack mode. That is, neither GDB nor the stub will
297 expect acks from each other. The connection is assumed to be
301 /* True if we're connected in extended remote mode. */
304 /* True if we resumed the target and we're waiting for the target to
305 stop. In the mean time, we can't start another command/query.
306 The remote server wouldn't be ready to process it, so we'd
307 timeout waiting for a reply that would never come and eventually
308 we'd close the connection. This can happen in asynchronous mode
309 because we allow GDB commands while the target is running. */
310 int waiting_for_stop_reply;
312 /* The status of the stub support for the various vCont actions. */
313 struct vCont_action_support supports_vCont;
315 /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
316 responded to that. */
319 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
320 remote_open knows that we don't have a file open when the program
322 struct serial *remote_desc;
324 /* These are the threads which we last sent to the remote system. The
325 TID member will be -1 for all or -2 for not sent yet. */
326 ptid_t general_thread;
327 ptid_t continue_thread;
329 /* This is the traceframe which we last selected on the remote system.
330 It will be -1 if no traceframe is selected. */
331 int remote_traceframe_number;
333 char *last_pass_packet;
335 /* The last QProgramSignals packet sent to the target. We bypass
336 sending a new program signals list down to the target if the new
337 packet is exactly the same as the last we sent. IOW, we only let
338 the target know about program signals list changes. */
339 char *last_program_signals_packet;
341 enum gdb_signal last_sent_signal;
345 char *finished_object;
346 char *finished_annex;
347 ULONGEST finished_offset;
349 /* Should we try the 'ThreadInfo' query packet?
351 This variable (NOT available to the user: auto-detect only!)
352 determines whether GDB will use the new, simpler "ThreadInfo"
353 query or the older, more complex syntax for thread queries.
354 This is an auto-detect variable (set to true at each connect,
355 and set to false when the target fails to recognize it). */
356 int use_threadinfo_query;
357 int use_threadextra_query;
359 void (*async_client_callback) (enum inferior_event_type event_type,
361 void *async_client_context;
363 /* This is set to the data address of the access causing the target
364 to stop for a watchpoint. */
365 CORE_ADDR remote_watch_data_address;
367 /* Whether the target stopped for a breakpoint/watchpoint. */
368 enum target_stop_reason stop_reason;
370 threadref echo_nextthread;
371 threadref nextthread;
372 threadref resultthreadlist[MAXTHREADLISTRESULTS];
374 /* The state of remote notification. */
375 struct remote_notif_state *notif_state;
377 /* The branch trace configuration. */
378 struct btrace_config btrace_config;
381 /* Private data that we'll store in (struct thread_info)->private. */
382 struct private_thread_info
389 free_private_thread_info (struct private_thread_info *info)
395 /* This data could be associated with a target, but we do not always
396 have access to the current target when we need it, so for now it is
397 static. This will be fine for as long as only one target is in use
399 static struct remote_state *remote_state;
401 static struct remote_state *
402 get_remote_state_raw (void)
407 /* Allocate a new struct remote_state with xmalloc, initialize it, and
410 static struct remote_state *
411 new_remote_state (void)
413 struct remote_state *result = XCNEW (struct remote_state);
415 /* The default buffer size is unimportant; it will be expanded
416 whenever a larger buffer is needed. */
417 result->buf_size = 400;
418 result->buf = xmalloc (result->buf_size);
419 result->remote_traceframe_number = -1;
420 result->last_sent_signal = GDB_SIGNAL_0;
425 /* Description of the remote protocol for a given architecture. */
429 long offset; /* Offset into G packet. */
430 long regnum; /* GDB's internal register number. */
431 LONGEST pnum; /* Remote protocol register number. */
432 int in_g_packet; /* Always part of G packet. */
433 /* long size in bytes; == register_size (target_gdbarch (), regnum);
435 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
439 struct remote_arch_state
441 /* Description of the remote protocol registers. */
442 long sizeof_g_packet;
444 /* Description of the remote protocol registers indexed by REGNUM
445 (making an array gdbarch_num_regs in size). */
446 struct packet_reg *regs;
448 /* This is the size (in chars) of the first response to the ``g''
449 packet. It is used as a heuristic when determining the maximum
450 size of memory-read and memory-write packets. A target will
451 typically only reserve a buffer large enough to hold the ``g''
452 packet. The size does not include packet overhead (headers and
454 long actual_register_packet_size;
456 /* This is the maximum size (in chars) of a non read/write packet.
457 It is also used as a cap on the size of read/write packets. */
458 long remote_packet_size;
461 /* Utility: generate error from an incoming stub packet. */
463 trace_error (char *buf)
466 return; /* not an error msg */
469 case '1': /* malformed packet error */
470 if (*++buf == '0') /* general case: */
471 error (_("remote.c: error in outgoing packet."));
473 error (_("remote.c: error in outgoing packet at field #%ld."),
474 strtol (buf, NULL, 16));
476 error (_("Target returns error code '%s'."), buf);
480 /* Utility: wait for reply from stub, while accepting "O" packets. */
482 remote_get_noisy_reply (char **buf_p,
485 do /* Loop on reply from remote stub. */
489 QUIT; /* Allow user to bail out with ^C. */
490 getpkt (buf_p, sizeof_buf, 0);
494 else if (startswith (buf, "qRelocInsn:"))
497 CORE_ADDR from, to, org_to;
499 int adjusted_size = 0;
502 p = buf + strlen ("qRelocInsn:");
503 pp = unpack_varlen_hex (p, &ul);
505 error (_("invalid qRelocInsn packet: %s"), buf);
509 unpack_varlen_hex (p, &ul);
516 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
519 CATCH (ex, RETURN_MASK_ALL)
521 if (ex.error == MEMORY_ERROR)
523 /* Propagate memory errors silently back to the
524 target. The stub may have limited the range of
525 addresses we can write to, for example. */
529 /* Something unexpectedly bad happened. Be verbose
530 so we can tell what, and propagate the error back
531 to the stub, so it doesn't get stuck waiting for
533 exception_fprintf (gdb_stderr, ex,
534 _("warning: relocating instruction: "));
542 adjusted_size = to - org_to;
544 xsnprintf (buf, *sizeof_buf, "qRelocInsn:%x", adjusted_size);
548 else if (buf[0] == 'O' && buf[1] != 'K')
549 remote_console_output (buf + 1); /* 'O' message from stub */
551 return buf; /* Here's the actual reply. */
556 /* Handle for retreving the remote protocol data from gdbarch. */
557 static struct gdbarch_data *remote_gdbarch_data_handle;
559 static struct remote_arch_state *
560 get_remote_arch_state (void)
562 return gdbarch_data (target_gdbarch (), remote_gdbarch_data_handle);
565 /* Fetch the global remote target state. */
567 static struct remote_state *
568 get_remote_state (void)
570 /* Make sure that the remote architecture state has been
571 initialized, because doing so might reallocate rs->buf. Any
572 function which calls getpkt also needs to be mindful of changes
573 to rs->buf, but this call limits the number of places which run
575 get_remote_arch_state ();
577 return get_remote_state_raw ();
581 compare_pnums (const void *lhs_, const void *rhs_)
583 const struct packet_reg * const *lhs = lhs_;
584 const struct packet_reg * const *rhs = rhs_;
586 if ((*lhs)->pnum < (*rhs)->pnum)
588 else if ((*lhs)->pnum == (*rhs)->pnum)
595 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
597 int regnum, num_remote_regs, offset;
598 struct packet_reg **remote_regs;
600 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
602 struct packet_reg *r = ®s[regnum];
604 if (register_size (gdbarch, regnum) == 0)
605 /* Do not try to fetch zero-sized (placeholder) registers. */
608 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
613 /* Define the g/G packet format as the contents of each register
614 with a remote protocol number, in order of ascending protocol
617 remote_regs = alloca (gdbarch_num_regs (gdbarch)
618 * sizeof (struct packet_reg *));
619 for (num_remote_regs = 0, regnum = 0;
620 regnum < gdbarch_num_regs (gdbarch);
622 if (regs[regnum].pnum != -1)
623 remote_regs[num_remote_regs++] = ®s[regnum];
625 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
628 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
630 remote_regs[regnum]->in_g_packet = 1;
631 remote_regs[regnum]->offset = offset;
632 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
638 /* Given the architecture described by GDBARCH, return the remote
639 protocol register's number and the register's offset in the g/G
640 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
641 If the target does not have a mapping for REGNUM, return false,
642 otherwise, return true. */
645 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
646 int *pnum, int *poffset)
649 struct packet_reg *regs;
650 struct cleanup *old_chain;
652 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
654 regs = xcalloc (gdbarch_num_regs (gdbarch), sizeof (struct packet_reg));
655 old_chain = make_cleanup (xfree, regs);
657 sizeof_g_packet = map_regcache_remote_table (gdbarch, regs);
659 *pnum = regs[regnum].pnum;
660 *poffset = regs[regnum].offset;
662 do_cleanups (old_chain);
668 init_remote_state (struct gdbarch *gdbarch)
670 struct remote_state *rs = get_remote_state_raw ();
671 struct remote_arch_state *rsa;
673 rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
675 /* Use the architecture to build a regnum<->pnum table, which will be
676 1:1 unless a feature set specifies otherwise. */
677 rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
678 gdbarch_num_regs (gdbarch),
681 /* Record the maximum possible size of the g packet - it may turn out
683 rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
685 /* Default maximum number of characters in a packet body. Many
686 remote stubs have a hardwired buffer size of 400 bytes
687 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
688 as the maximum packet-size to ensure that the packet and an extra
689 NUL character can always fit in the buffer. This stops GDB
690 trashing stubs that try to squeeze an extra NUL into what is
691 already a full buffer (As of 1999-12-04 that was most stubs). */
692 rsa->remote_packet_size = 400 - 1;
694 /* This one is filled in when a ``g'' packet is received. */
695 rsa->actual_register_packet_size = 0;
697 /* Should rsa->sizeof_g_packet needs more space than the
698 default, adjust the size accordingly. Remember that each byte is
699 encoded as two characters. 32 is the overhead for the packet
700 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
701 (``$NN:G...#NN'') is a better guess, the below has been padded a
703 if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
704 rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
706 /* Make sure that the packet buffer is plenty big enough for
707 this architecture. */
708 if (rs->buf_size < rsa->remote_packet_size)
710 rs->buf_size = 2 * rsa->remote_packet_size;
711 rs->buf = xrealloc (rs->buf, rs->buf_size);
717 /* Return the current allowed size of a remote packet. This is
718 inferred from the current architecture, and should be used to
719 limit the length of outgoing packets. */
721 get_remote_packet_size (void)
723 struct remote_state *rs = get_remote_state ();
724 struct remote_arch_state *rsa = get_remote_arch_state ();
726 if (rs->explicit_packet_size)
727 return rs->explicit_packet_size;
729 return rsa->remote_packet_size;
732 static struct packet_reg *
733 packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
735 if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch ()))
739 struct packet_reg *r = &rsa->regs[regnum];
741 gdb_assert (r->regnum == regnum);
746 static struct packet_reg *
747 packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
751 for (i = 0; i < gdbarch_num_regs (target_gdbarch ()); i++)
753 struct packet_reg *r = &rsa->regs[i];
761 static struct target_ops remote_ops;
763 static struct target_ops extended_remote_ops;
765 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
766 ``forever'' still use the normal timeout mechanism. This is
767 currently used by the ASYNC code to guarentee that target reads
768 during the initial connect always time-out. Once getpkt has been
769 modified to return a timeout indication and, in turn
770 remote_wait()/wait_for_inferior() have gained a timeout parameter
772 static int wait_forever_enabled_p = 1;
774 /* Allow the user to specify what sequence to send to the remote
775 when he requests a program interruption: Although ^C is usually
776 what remote systems expect (this is the default, here), it is
777 sometimes preferable to send a break. On other systems such
778 as the Linux kernel, a break followed by g, which is Magic SysRq g
779 is required in order to interrupt the execution. */
780 const char interrupt_sequence_control_c[] = "Ctrl-C";
781 const char interrupt_sequence_break[] = "BREAK";
782 const char interrupt_sequence_break_g[] = "BREAK-g";
783 static const char *const interrupt_sequence_modes[] =
785 interrupt_sequence_control_c,
786 interrupt_sequence_break,
787 interrupt_sequence_break_g,
790 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
793 show_interrupt_sequence (struct ui_file *file, int from_tty,
794 struct cmd_list_element *c,
797 if (interrupt_sequence_mode == interrupt_sequence_control_c)
798 fprintf_filtered (file,
799 _("Send the ASCII ETX character (Ctrl-c) "
800 "to the remote target to interrupt the "
801 "execution of the program.\n"));
802 else if (interrupt_sequence_mode == interrupt_sequence_break)
803 fprintf_filtered (file,
804 _("send a break signal to the remote target "
805 "to interrupt the execution of the program.\n"));
806 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
807 fprintf_filtered (file,
808 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
809 "the remote target to interrupt the execution "
810 "of Linux kernel.\n"));
812 internal_error (__FILE__, __LINE__,
813 _("Invalid value for interrupt_sequence_mode: %s."),
814 interrupt_sequence_mode);
817 /* This boolean variable specifies whether interrupt_sequence is sent
818 to the remote target when gdb connects to it.
819 This is mostly needed when you debug the Linux kernel: The Linux kernel
820 expects BREAK g which is Magic SysRq g for connecting gdb. */
821 static int interrupt_on_connect = 0;
823 /* This variable is used to implement the "set/show remotebreak" commands.
824 Since these commands are now deprecated in favor of "set/show remote
825 interrupt-sequence", it no longer has any effect on the code. */
826 static int remote_break;
829 set_remotebreak (char *args, int from_tty, struct cmd_list_element *c)
832 interrupt_sequence_mode = interrupt_sequence_break;
834 interrupt_sequence_mode = interrupt_sequence_control_c;
838 show_remotebreak (struct ui_file *file, int from_tty,
839 struct cmd_list_element *c,
844 /* This variable sets the number of bits in an address that are to be
845 sent in a memory ("M" or "m") packet. Normally, after stripping
846 leading zeros, the entire address would be sent. This variable
847 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
848 initial implementation of remote.c restricted the address sent in
849 memory packets to ``host::sizeof long'' bytes - (typically 32
850 bits). Consequently, for 64 bit targets, the upper 32 bits of an
851 address was never sent. Since fixing this bug may cause a break in
852 some remote targets this variable is principly provided to
853 facilitate backward compatibility. */
855 static unsigned int remote_address_size;
857 /* Temporary to track who currently owns the terminal. See
858 remote_terminal_* for more details. */
860 static int remote_async_terminal_ours_p;
862 /* The executable file to use for "run" on the remote side. */
864 static char *remote_exec_file = "";
867 /* User configurable variables for the number of characters in a
868 memory read/write packet. MIN (rsa->remote_packet_size,
869 rsa->sizeof_g_packet) is the default. Some targets need smaller
870 values (fifo overruns, et.al.) and some users need larger values
871 (speed up transfers). The variables ``preferred_*'' (the user
872 request), ``current_*'' (what was actually set) and ``forced_*''
873 (Positive - a soft limit, negative - a hard limit). */
875 struct memory_packet_config
882 /* Compute the current size of a read/write packet. Since this makes
883 use of ``actual_register_packet_size'' the computation is dynamic. */
886 get_memory_packet_size (struct memory_packet_config *config)
888 struct remote_state *rs = get_remote_state ();
889 struct remote_arch_state *rsa = get_remote_arch_state ();
891 /* NOTE: The somewhat arbitrary 16k comes from the knowledge (folk
892 law?) that some hosts don't cope very well with large alloca()
893 calls. Eventually the alloca() code will be replaced by calls to
894 xmalloc() and make_cleanups() allowing this restriction to either
895 be lifted or removed. */
896 #ifndef MAX_REMOTE_PACKET_SIZE
897 #define MAX_REMOTE_PACKET_SIZE 16384
899 /* NOTE: 20 ensures we can write at least one byte. */
900 #ifndef MIN_REMOTE_PACKET_SIZE
901 #define MIN_REMOTE_PACKET_SIZE 20
906 if (config->size <= 0)
907 what_they_get = MAX_REMOTE_PACKET_SIZE;
909 what_they_get = config->size;
913 what_they_get = get_remote_packet_size ();
914 /* Limit the packet to the size specified by the user. */
916 && what_they_get > config->size)
917 what_they_get = config->size;
919 /* Limit it to the size of the targets ``g'' response unless we have
920 permission from the stub to use a larger packet size. */
921 if (rs->explicit_packet_size == 0
922 && rsa->actual_register_packet_size > 0
923 && what_they_get > rsa->actual_register_packet_size)
924 what_they_get = rsa->actual_register_packet_size;
926 if (what_they_get > MAX_REMOTE_PACKET_SIZE)
927 what_they_get = MAX_REMOTE_PACKET_SIZE;
928 if (what_they_get < MIN_REMOTE_PACKET_SIZE)
929 what_they_get = MIN_REMOTE_PACKET_SIZE;
931 /* Make sure there is room in the global buffer for this packet
932 (including its trailing NUL byte). */
933 if (rs->buf_size < what_they_get + 1)
935 rs->buf_size = 2 * what_they_get;
936 rs->buf = xrealloc (rs->buf, 2 * what_they_get);
939 return what_they_get;
942 /* Update the size of a read/write packet. If they user wants
943 something really big then do a sanity check. */
946 set_memory_packet_size (char *args, struct memory_packet_config *config)
948 int fixed_p = config->fixed_p;
949 long size = config->size;
952 error (_("Argument required (integer, `fixed' or `limited')."));
953 else if (strcmp (args, "hard") == 0
954 || strcmp (args, "fixed") == 0)
956 else if (strcmp (args, "soft") == 0
957 || strcmp (args, "limit") == 0)
963 size = strtoul (args, &end, 0);
965 error (_("Invalid %s (bad syntax)."), config->name);
967 /* Instead of explicitly capping the size of a packet to
968 MAX_REMOTE_PACKET_SIZE or dissallowing it, the user is
969 instead allowed to set the size to something arbitrarily
971 if (size > MAX_REMOTE_PACKET_SIZE)
972 error (_("Invalid %s (too large)."), config->name);
976 if (fixed_p && !config->fixed_p)
978 if (! query (_("The target may not be able to correctly handle a %s\n"
979 "of %ld bytes. Change the packet size? "),
981 error (_("Packet size not changed."));
983 /* Update the config. */
984 config->fixed_p = fixed_p;
989 show_memory_packet_size (struct memory_packet_config *config)
991 printf_filtered (_("The %s is %ld. "), config->name, config->size);
993 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
994 get_memory_packet_size (config));
996 printf_filtered (_("Packets are limited to %ld bytes.\n"),
997 get_memory_packet_size (config));
1000 static struct memory_packet_config memory_write_packet_config =
1002 "memory-write-packet-size",
1006 set_memory_write_packet_size (char *args, int from_tty)
1008 set_memory_packet_size (args, &memory_write_packet_config);
1012 show_memory_write_packet_size (char *args, int from_tty)
1014 show_memory_packet_size (&memory_write_packet_config);
1018 get_memory_write_packet_size (void)
1020 return get_memory_packet_size (&memory_write_packet_config);
1023 static struct memory_packet_config memory_read_packet_config =
1025 "memory-read-packet-size",
1029 set_memory_read_packet_size (char *args, int from_tty)
1031 set_memory_packet_size (args, &memory_read_packet_config);
1035 show_memory_read_packet_size (char *args, int from_tty)
1037 show_memory_packet_size (&memory_read_packet_config);
1041 get_memory_read_packet_size (void)
1043 long size = get_memory_packet_size (&memory_read_packet_config);
1045 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1046 extra buffer size argument before the memory read size can be
1047 increased beyond this. */
1048 if (size > get_remote_packet_size ())
1049 size = get_remote_packet_size ();
1054 /* Generic configuration support for packets the stub optionally
1055 supports. Allows the user to specify the use of the packet as well
1056 as allowing GDB to auto-detect support in the remote stub. */
1060 PACKET_SUPPORT_UNKNOWN = 0,
1065 struct packet_config
1070 /* If auto, GDB auto-detects support for this packet or feature,
1071 either through qSupported, or by trying the packet and looking
1072 at the response. If true, GDB assumes the target supports this
1073 packet. If false, the packet is disabled. Configs that don't
1074 have an associated command always have this set to auto. */
1075 enum auto_boolean detect;
1077 /* Does the target support this packet? */
1078 enum packet_support support;
1081 /* Analyze a packet's return value and update the packet config
1091 static enum packet_support packet_config_support (struct packet_config *config);
1092 static enum packet_support packet_support (int packet);
1095 show_packet_config_cmd (struct packet_config *config)
1097 char *support = "internal-error";
1099 switch (packet_config_support (config))
1102 support = "enabled";
1104 case PACKET_DISABLE:
1105 support = "disabled";
1107 case PACKET_SUPPORT_UNKNOWN:
1108 support = "unknown";
1111 switch (config->detect)
1113 case AUTO_BOOLEAN_AUTO:
1114 printf_filtered (_("Support for the `%s' packet "
1115 "is auto-detected, currently %s.\n"),
1116 config->name, support);
1118 case AUTO_BOOLEAN_TRUE:
1119 case AUTO_BOOLEAN_FALSE:
1120 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1121 config->name, support);
1127 add_packet_config_cmd (struct packet_config *config, const char *name,
1128 const char *title, int legacy)
1134 config->name = name;
1135 config->title = title;
1136 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1138 show_doc = xstrprintf ("Show current use of remote "
1139 "protocol `%s' (%s) packet",
1141 /* set/show TITLE-packet {auto,on,off} */
1142 cmd_name = xstrprintf ("%s-packet", title);
1143 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
1144 &config->detect, set_doc,
1145 show_doc, NULL, /* help_doc */
1147 show_remote_protocol_packet_cmd,
1148 &remote_set_cmdlist, &remote_show_cmdlist);
1149 /* The command code copies the documentation strings. */
1152 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
1157 legacy_name = xstrprintf ("%s-packet", name);
1158 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1159 &remote_set_cmdlist);
1160 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1161 &remote_show_cmdlist);
1165 static enum packet_result
1166 packet_check_result (const char *buf)
1170 /* The stub recognized the packet request. Check that the
1171 operation succeeded. */
1173 && isxdigit (buf[1]) && isxdigit (buf[2])
1175 /* "Enn" - definitly an error. */
1176 return PACKET_ERROR;
1178 /* Always treat "E." as an error. This will be used for
1179 more verbose error messages, such as E.memtypes. */
1180 if (buf[0] == 'E' && buf[1] == '.')
1181 return PACKET_ERROR;
1183 /* The packet may or may not be OK. Just assume it is. */
1187 /* The stub does not support the packet. */
1188 return PACKET_UNKNOWN;
1191 static enum packet_result
1192 packet_ok (const char *buf, struct packet_config *config)
1194 enum packet_result result;
1196 if (config->detect != AUTO_BOOLEAN_TRUE
1197 && config->support == PACKET_DISABLE)
1198 internal_error (__FILE__, __LINE__,
1199 _("packet_ok: attempt to use a disabled packet"));
1201 result = packet_check_result (buf);
1206 /* The stub recognized the packet request. */
1207 if (config->support == PACKET_SUPPORT_UNKNOWN)
1210 fprintf_unfiltered (gdb_stdlog,
1211 "Packet %s (%s) is supported\n",
1212 config->name, config->title);
1213 config->support = PACKET_ENABLE;
1216 case PACKET_UNKNOWN:
1217 /* The stub does not support the packet. */
1218 if (config->detect == AUTO_BOOLEAN_AUTO
1219 && config->support == PACKET_ENABLE)
1221 /* If the stub previously indicated that the packet was
1222 supported then there is a protocol error. */
1223 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1224 config->name, config->title);
1226 else if (config->detect == AUTO_BOOLEAN_TRUE)
1228 /* The user set it wrong. */
1229 error (_("Enabled packet %s (%s) not recognized by stub"),
1230 config->name, config->title);
1234 fprintf_unfiltered (gdb_stdlog,
1235 "Packet %s (%s) is NOT supported\n",
1236 config->name, config->title);
1237 config->support = PACKET_DISABLE;
1257 PACKET_vFile_pwrite,
1259 PACKET_vFile_unlink,
1260 PACKET_vFile_readlink,
1263 PACKET_qXfer_features,
1264 PACKET_qXfer_libraries,
1265 PACKET_qXfer_libraries_svr4,
1266 PACKET_qXfer_memory_map,
1267 PACKET_qXfer_spu_read,
1268 PACKET_qXfer_spu_write,
1269 PACKET_qXfer_osdata,
1270 PACKET_qXfer_threads,
1271 PACKET_qXfer_statictrace_read,
1272 PACKET_qXfer_traceframe_info,
1278 PACKET_QPassSignals,
1279 PACKET_QProgramSignals,
1281 PACKET_qSearch_memory,
1284 PACKET_QStartNoAckMode,
1286 PACKET_qXfer_siginfo_read,
1287 PACKET_qXfer_siginfo_write,
1290 /* Support for conditional tracepoints. */
1291 PACKET_ConditionalTracepoints,
1293 /* Support for target-side breakpoint conditions. */
1294 PACKET_ConditionalBreakpoints,
1296 /* Support for target-side breakpoint commands. */
1297 PACKET_BreakpointCommands,
1299 /* Support for fast tracepoints. */
1300 PACKET_FastTracepoints,
1302 /* Support for static tracepoints. */
1303 PACKET_StaticTracepoints,
1305 /* Support for installing tracepoints while a trace experiment is
1307 PACKET_InstallInTrace,
1311 PACKET_TracepointSource,
1314 PACKET_QDisableRandomization,
1316 PACKET_QTBuffer_size,
1319 PACKET_qXfer_btrace,
1321 /* Support for the QNonStop packet. */
1324 /* Support for multi-process extensions. */
1325 PACKET_multiprocess_feature,
1327 /* Support for enabling and disabling tracepoints while a trace
1328 experiment is running. */
1329 PACKET_EnableDisableTracepoints_feature,
1331 /* Support for collecting strings using the tracenz bytecode. */
1332 PACKET_tracenz_feature,
1334 /* Support for continuing to run a trace experiment while GDB is
1336 PACKET_DisconnectedTracing_feature,
1338 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
1339 PACKET_augmented_libraries_svr4_read_feature,
1341 /* Support for the qXfer:btrace-conf:read packet. */
1342 PACKET_qXfer_btrace_conf,
1344 /* Support for the Qbtrace-conf:bts:size packet. */
1345 PACKET_Qbtrace_conf_bts_size,
1347 /* Support for swbreak+ feature. */
1348 PACKET_swbreak_feature,
1350 /* Support for hwbreak+ feature. */
1351 PACKET_hwbreak_feature,
1356 static struct packet_config remote_protocol_packets[PACKET_MAX];
1358 /* Returns the packet's corresponding "set remote foo-packet" command
1359 state. See struct packet_config for more details. */
1361 static enum auto_boolean
1362 packet_set_cmd_state (int packet)
1364 return remote_protocol_packets[packet].detect;
1367 /* Returns whether a given packet or feature is supported. This takes
1368 into account the state of the corresponding "set remote foo-packet"
1369 command, which may be used to bypass auto-detection. */
1371 static enum packet_support
1372 packet_config_support (struct packet_config *config)
1374 switch (config->detect)
1376 case AUTO_BOOLEAN_TRUE:
1377 return PACKET_ENABLE;
1378 case AUTO_BOOLEAN_FALSE:
1379 return PACKET_DISABLE;
1380 case AUTO_BOOLEAN_AUTO:
1381 return config->support;
1383 gdb_assert_not_reached (_("bad switch"));
1387 /* Same as packet_config_support, but takes the packet's enum value as
1390 static enum packet_support
1391 packet_support (int packet)
1393 struct packet_config *config = &remote_protocol_packets[packet];
1395 return packet_config_support (config);
1399 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1400 struct cmd_list_element *c,
1403 struct packet_config *packet;
1405 for (packet = remote_protocol_packets;
1406 packet < &remote_protocol_packets[PACKET_MAX];
1409 if (&packet->detect == c->var)
1411 show_packet_config_cmd (packet);
1415 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
1419 /* Should we try one of the 'Z' requests? */
1423 Z_PACKET_SOFTWARE_BP,
1424 Z_PACKET_HARDWARE_BP,
1431 /* For compatibility with older distributions. Provide a ``set remote
1432 Z-packet ...'' command that updates all the Z packet types. */
1434 static enum auto_boolean remote_Z_packet_detect;
1437 set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1438 struct cmd_list_element *c)
1442 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1443 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
1447 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1448 struct cmd_list_element *c,
1453 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1455 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
1459 /* Returns true if the multi-process extensions are in effect. */
1462 remote_multi_process_p (struct remote_state *rs)
1464 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
1467 /* Tokens for use by the asynchronous signal handlers for SIGINT. */
1468 static struct async_signal_handler *async_sigint_remote_twice_token;
1469 static struct async_signal_handler *async_sigint_remote_token;
1472 /* Asynchronous signal handle registered as event loop source for
1473 when we have pending events ready to be passed to the core. */
1475 static struct async_event_handler *remote_async_inferior_event_token;
1479 static ptid_t magic_null_ptid;
1480 static ptid_t not_sent_ptid;
1481 static ptid_t any_thread_ptid;
1483 /* Find out if the stub attached to PID (and hence GDB should offer to
1484 detach instead of killing it when bailing out). */
1487 remote_query_attached (int pid)
1489 struct remote_state *rs = get_remote_state ();
1490 size_t size = get_remote_packet_size ();
1492 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
1495 if (remote_multi_process_p (rs))
1496 xsnprintf (rs->buf, size, "qAttached:%x", pid);
1498 xsnprintf (rs->buf, size, "qAttached");
1501 getpkt (&rs->buf, &rs->buf_size, 0);
1503 switch (packet_ok (rs->buf,
1504 &remote_protocol_packets[PACKET_qAttached]))
1507 if (strcmp (rs->buf, "1") == 0)
1511 warning (_("Remote failure reply: %s"), rs->buf);
1513 case PACKET_UNKNOWN:
1520 /* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
1521 has been invented by GDB, instead of reported by the target. Since
1522 we can be connected to a remote system before before knowing about
1523 any inferior, mark the target with execution when we find the first
1524 inferior. If ATTACHED is 1, then we had just attached to this
1525 inferior. If it is 0, then we just created this inferior. If it
1526 is -1, then try querying the remote stub to find out if it had
1527 attached to the inferior or not. */
1529 static struct inferior *
1530 remote_add_inferior (int fake_pid_p, int pid, int attached)
1532 struct inferior *inf;
1534 /* Check whether this process we're learning about is to be
1535 considered attached, or if is to be considered to have been
1536 spawned by the stub. */
1538 attached = remote_query_attached (pid);
1540 if (gdbarch_has_global_solist (target_gdbarch ()))
1542 /* If the target shares code across all inferiors, then every
1543 attach adds a new inferior. */
1544 inf = add_inferior (pid);
1546 /* ... and every inferior is bound to the same program space.
1547 However, each inferior may still have its own address
1549 inf->aspace = maybe_new_address_space ();
1550 inf->pspace = current_program_space;
1554 /* In the traditional debugging scenario, there's a 1-1 match
1555 between program/address spaces. We simply bind the inferior
1556 to the program space's address space. */
1557 inf = current_inferior ();
1558 inferior_appeared (inf, pid);
1561 inf->attach_flag = attached;
1562 inf->fake_pid_p = fake_pid_p;
1567 /* Add thread PTID to GDB's thread list. Tag it as executing/running
1568 according to RUNNING. */
1571 remote_add_thread (ptid_t ptid, int running)
1573 struct remote_state *rs = get_remote_state ();
1575 /* GDB historically didn't pull threads in the initial connection
1576 setup. If the remote target doesn't even have a concept of
1577 threads (e.g., a bare-metal target), even if internally we
1578 consider that a single-threaded target, mentioning a new thread
1579 might be confusing to the user. Be silent then, preserving the
1580 age old behavior. */
1581 if (rs->starting_up)
1582 add_thread_silent (ptid);
1586 set_executing (ptid, running);
1587 set_running (ptid, running);
1590 /* Come here when we learn about a thread id from the remote target.
1591 It may be the first time we hear about such thread, so take the
1592 opportunity to add it to GDB's thread list. In case this is the
1593 first time we're noticing its corresponding inferior, add it to
1594 GDB's inferior list as well. */
1597 remote_notice_new_inferior (ptid_t currthread, int running)
1599 /* If this is a new thread, add it to GDB's thread list.
1600 If we leave it up to WFI to do this, bad things will happen. */
1602 if (in_thread_list (currthread) && is_exited (currthread))
1604 /* We're seeing an event on a thread id we knew had exited.
1605 This has to be a new thread reusing the old id. Add it. */
1606 remote_add_thread (currthread, running);
1610 if (!in_thread_list (currthread))
1612 struct inferior *inf = NULL;
1613 int pid = ptid_get_pid (currthread);
1615 if (ptid_is_pid (inferior_ptid)
1616 && pid == ptid_get_pid (inferior_ptid))
1618 /* inferior_ptid has no thread member yet. This can happen
1619 with the vAttach -> remote_wait,"TAAthread:" path if the
1620 stub doesn't support qC. This is the first stop reported
1621 after an attach, so this is the main thread. Update the
1622 ptid in the thread list. */
1623 if (in_thread_list (pid_to_ptid (pid)))
1624 thread_change_ptid (inferior_ptid, currthread);
1627 remote_add_thread (currthread, running);
1628 inferior_ptid = currthread;
1633 if (ptid_equal (magic_null_ptid, inferior_ptid))
1635 /* inferior_ptid is not set yet. This can happen with the
1636 vRun -> remote_wait,"TAAthread:" path if the stub
1637 doesn't support qC. This is the first stop reported
1638 after an attach, so this is the main thread. Update the
1639 ptid in the thread list. */
1640 thread_change_ptid (inferior_ptid, currthread);
1644 /* When connecting to a target remote, or to a target
1645 extended-remote which already was debugging an inferior, we
1646 may not know about it yet. Add it before adding its child
1647 thread, so notifications are emitted in a sensible order. */
1648 if (!in_inferior_list (ptid_get_pid (currthread)))
1650 struct remote_state *rs = get_remote_state ();
1651 int fake_pid_p = !remote_multi_process_p (rs);
1653 inf = remote_add_inferior (fake_pid_p,
1654 ptid_get_pid (currthread), -1);
1657 /* This is really a new thread. Add it. */
1658 remote_add_thread (currthread, running);
1660 /* If we found a new inferior, let the common code do whatever
1661 it needs to with it (e.g., read shared libraries, insert
1662 breakpoints), unless we're just setting up an all-stop
1666 struct remote_state *rs = get_remote_state ();
1668 if (non_stop || !rs->starting_up)
1669 notice_new_inferior (currthread, running, 0);
1674 /* Return the private thread data, creating it if necessary. */
1676 static struct private_thread_info *
1677 demand_private_info (ptid_t ptid)
1679 struct thread_info *info = find_thread_ptid (ptid);
1685 info->priv = xmalloc (sizeof (*(info->priv)));
1686 info->private_dtor = free_private_thread_info;
1687 info->priv->core = -1;
1688 info->priv->extra = 0;
1694 /* Call this function as a result of
1695 1) A halt indication (T packet) containing a thread id
1696 2) A direct query of currthread
1697 3) Successful execution of set thread */
1700 record_currthread (struct remote_state *rs, ptid_t currthread)
1702 rs->general_thread = currthread;
1705 /* If 'QPassSignals' is supported, tell the remote stub what signals
1706 it can simply pass through to the inferior without reporting. */
1709 remote_pass_signals (struct target_ops *self,
1710 int numsigs, unsigned char *pass_signals)
1712 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
1714 char *pass_packet, *p;
1716 struct remote_state *rs = get_remote_state ();
1718 gdb_assert (numsigs < 256);
1719 for (i = 0; i < numsigs; i++)
1721 if (pass_signals[i])
1724 pass_packet = xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
1725 strcpy (pass_packet, "QPassSignals:");
1726 p = pass_packet + strlen (pass_packet);
1727 for (i = 0; i < numsigs; i++)
1729 if (pass_signals[i])
1732 *p++ = tohex (i >> 4);
1733 *p++ = tohex (i & 15);
1742 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
1744 putpkt (pass_packet);
1745 getpkt (&rs->buf, &rs->buf_size, 0);
1746 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
1747 if (rs->last_pass_packet)
1748 xfree (rs->last_pass_packet);
1749 rs->last_pass_packet = pass_packet;
1752 xfree (pass_packet);
1756 /* If 'QProgramSignals' is supported, tell the remote stub what
1757 signals it should pass through to the inferior when detaching. */
1760 remote_program_signals (struct target_ops *self,
1761 int numsigs, unsigned char *signals)
1763 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
1767 struct remote_state *rs = get_remote_state ();
1769 gdb_assert (numsigs < 256);
1770 for (i = 0; i < numsigs; i++)
1775 packet = xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
1776 strcpy (packet, "QProgramSignals:");
1777 p = packet + strlen (packet);
1778 for (i = 0; i < numsigs; i++)
1780 if (signal_pass_state (i))
1783 *p++ = tohex (i >> 4);
1784 *p++ = tohex (i & 15);
1793 if (!rs->last_program_signals_packet
1794 || strcmp (rs->last_program_signals_packet, packet) != 0)
1797 getpkt (&rs->buf, &rs->buf_size, 0);
1798 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
1799 xfree (rs->last_program_signals_packet);
1800 rs->last_program_signals_packet = packet;
1807 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
1808 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
1809 thread. If GEN is set, set the general thread, if not, then set
1810 the step/continue thread. */
1812 set_thread (struct ptid ptid, int gen)
1814 struct remote_state *rs = get_remote_state ();
1815 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
1816 char *buf = rs->buf;
1817 char *endbuf = rs->buf + get_remote_packet_size ();
1819 if (ptid_equal (state, ptid))
1823 *buf++ = gen ? 'g' : 'c';
1824 if (ptid_equal (ptid, magic_null_ptid))
1825 xsnprintf (buf, endbuf - buf, "0");
1826 else if (ptid_equal (ptid, any_thread_ptid))
1827 xsnprintf (buf, endbuf - buf, "0");
1828 else if (ptid_equal (ptid, minus_one_ptid))
1829 xsnprintf (buf, endbuf - buf, "-1");
1831 write_ptid (buf, endbuf, ptid);
1833 getpkt (&rs->buf, &rs->buf_size, 0);
1835 rs->general_thread = ptid;
1837 rs->continue_thread = ptid;
1841 set_general_thread (struct ptid ptid)
1843 set_thread (ptid, 1);
1847 set_continue_thread (struct ptid ptid)
1849 set_thread (ptid, 0);
1852 /* Change the remote current process. Which thread within the process
1853 ends up selected isn't important, as long as it is the same process
1854 as what INFERIOR_PTID points to.
1856 This comes from that fact that there is no explicit notion of
1857 "selected process" in the protocol. The selected process for
1858 general operations is the process the selected general thread
1862 set_general_process (void)
1864 struct remote_state *rs = get_remote_state ();
1866 /* If the remote can't handle multiple processes, don't bother. */
1867 if (!rs->extended || !remote_multi_process_p (rs))
1870 /* We only need to change the remote current thread if it's pointing
1871 at some other process. */
1872 if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
1873 set_general_thread (inferior_ptid);
1877 /* Return nonzero if this is the main thread that we made up ourselves
1878 to model non-threaded targets as single-threaded. */
1881 remote_thread_always_alive (struct target_ops *ops, ptid_t ptid)
1883 struct remote_state *rs = get_remote_state ();
1886 if (ptid_equal (ptid, magic_null_ptid))
1887 /* The main thread is always alive. */
1890 if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
1891 /* The main thread is always alive. This can happen after a
1892 vAttach, if the remote side doesn't support
1899 /* Return nonzero if the thread PTID is still alive on the remote
1903 remote_thread_alive (struct target_ops *ops, ptid_t ptid)
1905 struct remote_state *rs = get_remote_state ();
1908 /* Check if this is a thread that we made up ourselves to model
1909 non-threaded targets as single-threaded. */
1910 if (remote_thread_always_alive (ops, ptid))
1914 endp = rs->buf + get_remote_packet_size ();
1917 write_ptid (p, endp, ptid);
1920 getpkt (&rs->buf, &rs->buf_size, 0);
1921 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
1924 /* About these extended threadlist and threadinfo packets. They are
1925 variable length packets but, the fields within them are often fixed
1926 length. They are redundent enough to send over UDP as is the
1927 remote protocol in general. There is a matching unit test module
1930 /* WARNING: This threadref data structure comes from the remote O.S.,
1931 libstub protocol encoding, and remote.c. It is not particularly
1934 /* Right now, the internal structure is int. We want it to be bigger.
1935 Plan to fix this. */
1937 typedef int gdb_threadref; /* Internal GDB thread reference. */
1939 /* gdb_ext_thread_info is an internal GDB data structure which is
1940 equivalent to the reply of the remote threadinfo packet. */
1942 struct gdb_ext_thread_info
1944 threadref threadid; /* External form of thread reference. */
1945 int active; /* Has state interesting to GDB?
1947 char display[256]; /* Brief state display, name,
1948 blocked/suspended. */
1949 char shortname[32]; /* To be used to name threads. */
1950 char more_display[256]; /* Long info, statistics, queue depth,
1954 /* The volume of remote transfers can be limited by submitting
1955 a mask containing bits specifying the desired information.
1956 Use a union of these values as the 'selection' parameter to
1957 get_thread_info. FIXME: Make these TAG names more thread specific. */
1959 #define TAG_THREADID 1
1960 #define TAG_EXISTS 2
1961 #define TAG_DISPLAY 4
1962 #define TAG_THREADNAME 8
1963 #define TAG_MOREDISPLAY 16
1965 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
1967 static char *unpack_nibble (char *buf, int *val);
1969 static char *unpack_byte (char *buf, int *value);
1971 static char *pack_int (char *buf, int value);
1973 static char *unpack_int (char *buf, int *value);
1975 static char *unpack_string (char *src, char *dest, int length);
1977 static char *pack_threadid (char *pkt, threadref *id);
1979 static char *unpack_threadid (char *inbuf, threadref *id);
1981 void int_to_threadref (threadref *id, int value);
1983 static int threadref_to_int (threadref *ref);
1985 static void copy_threadref (threadref *dest, threadref *src);
1987 static int threadmatch (threadref *dest, threadref *src);
1989 static char *pack_threadinfo_request (char *pkt, int mode,
1992 static int remote_unpack_thread_info_response (char *pkt,
1993 threadref *expectedref,
1994 struct gdb_ext_thread_info
1998 static int remote_get_threadinfo (threadref *threadid,
1999 int fieldset, /*TAG mask */
2000 struct gdb_ext_thread_info *info);
2002 static char *pack_threadlist_request (char *pkt, int startflag,
2004 threadref *nextthread);
2006 static int parse_threadlist_response (char *pkt,
2008 threadref *original_echo,
2009 threadref *resultlist,
2012 static int remote_get_threadlist (int startflag,
2013 threadref *nextthread,
2017 threadref *threadlist);
2019 typedef int (*rmt_thread_action) (threadref *ref, void *context);
2021 static int remote_threadlist_iterator (rmt_thread_action stepfunction,
2022 void *context, int looplimit);
2024 static int remote_newthread_step (threadref *ref, void *context);
2027 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
2028 buffer we're allowed to write to. Returns
2029 BUF+CHARACTERS_WRITTEN. */
2032 write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2035 struct remote_state *rs = get_remote_state ();
2037 if (remote_multi_process_p (rs))
2039 pid = ptid_get_pid (ptid);
2041 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2043 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2045 tid = ptid_get_lwp (ptid);
2047 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2049 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2054 /* Extract a PTID from BUF. If non-null, OBUF is set to the to one
2055 passed the last parsed char. Returns null_ptid on error. */
2058 read_ptid (char *buf, char **obuf)
2062 ULONGEST pid = 0, tid = 0;
2066 /* Multi-process ptid. */
2067 pp = unpack_varlen_hex (p + 1, &pid);
2069 error (_("invalid remote ptid: %s"), p);
2072 pp = unpack_varlen_hex (p + 1, &tid);
2075 return ptid_build (pid, tid, 0);
2078 /* No multi-process. Just a tid. */
2079 pp = unpack_varlen_hex (p, &tid);
2081 /* Since the stub is not sending a process id, then default to
2082 what's in inferior_ptid, unless it's null at this point. If so,
2083 then since there's no way to know the pid of the reported
2084 threads, use the magic number. */
2085 if (ptid_equal (inferior_ptid, null_ptid))
2086 pid = ptid_get_pid (magic_null_ptid);
2088 pid = ptid_get_pid (inferior_ptid);
2092 return ptid_build (pid, tid, 0);
2098 if (ch >= 'a' && ch <= 'f')
2099 return ch - 'a' + 10;
2100 if (ch >= '0' && ch <= '9')
2102 if (ch >= 'A' && ch <= 'F')
2103 return ch - 'A' + 10;
2108 stub_unpack_int (char *buff, int fieldlength)
2115 nibble = stubhex (*buff++);
2119 retval = retval << 4;
2125 unpack_nibble (char *buf, int *val)
2127 *val = fromhex (*buf++);
2132 unpack_byte (char *buf, int *value)
2134 *value = stub_unpack_int (buf, 2);
2139 pack_int (char *buf, int value)
2141 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2142 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2143 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2144 buf = pack_hex_byte (buf, (value & 0xff));
2149 unpack_int (char *buf, int *value)
2151 *value = stub_unpack_int (buf, 8);
2155 #if 0 /* Currently unused, uncomment when needed. */
2156 static char *pack_string (char *pkt, char *string);
2159 pack_string (char *pkt, char *string)
2164 len = strlen (string);
2166 len = 200; /* Bigger than most GDB packets, junk??? */
2167 pkt = pack_hex_byte (pkt, len);
2171 if ((ch == '\0') || (ch == '#'))
2172 ch = '*'; /* Protect encapsulation. */
2177 #endif /* 0 (unused) */
2180 unpack_string (char *src, char *dest, int length)
2189 pack_threadid (char *pkt, threadref *id)
2192 unsigned char *altid;
2194 altid = (unsigned char *) id;
2195 limit = pkt + BUF_THREAD_ID_SIZE;
2197 pkt = pack_hex_byte (pkt, *altid++);
2203 unpack_threadid (char *inbuf, threadref *id)
2206 char *limit = inbuf + BUF_THREAD_ID_SIZE;
2209 altref = (char *) id;
2211 while (inbuf < limit)
2213 x = stubhex (*inbuf++);
2214 y = stubhex (*inbuf++);
2215 *altref++ = (x << 4) | y;
2220 /* Externally, threadrefs are 64 bits but internally, they are still
2221 ints. This is due to a mismatch of specifications. We would like
2222 to use 64bit thread references internally. This is an adapter
2226 int_to_threadref (threadref *id, int value)
2228 unsigned char *scan;
2230 scan = (unsigned char *) id;
2236 *scan++ = (value >> 24) & 0xff;
2237 *scan++ = (value >> 16) & 0xff;
2238 *scan++ = (value >> 8) & 0xff;
2239 *scan++ = (value & 0xff);
2243 threadref_to_int (threadref *ref)
2246 unsigned char *scan;
2252 value = (value << 8) | ((*scan++) & 0xff);
2257 copy_threadref (threadref *dest, threadref *src)
2260 unsigned char *csrc, *cdest;
2262 csrc = (unsigned char *) src;
2263 cdest = (unsigned char *) dest;
2270 threadmatch (threadref *dest, threadref *src)
2272 /* Things are broken right now, so just assume we got a match. */
2274 unsigned char *srcp, *destp;
2276 srcp = (char *) src;
2277 destp = (char *) dest;
2281 result &= (*srcp++ == *destp++) ? 1 : 0;
2288 threadid:1, # always request threadid
2295 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
2298 pack_threadinfo_request (char *pkt, int mode, threadref *id)
2300 *pkt++ = 'q'; /* Info Query */
2301 *pkt++ = 'P'; /* process or thread info */
2302 pkt = pack_int (pkt, mode); /* mode */
2303 pkt = pack_threadid (pkt, id); /* threadid */
2304 *pkt = '\0'; /* terminate */
2308 /* These values tag the fields in a thread info response packet. */
2309 /* Tagging the fields allows us to request specific fields and to
2310 add more fields as time goes by. */
2312 #define TAG_THREADID 1 /* Echo the thread identifier. */
2313 #define TAG_EXISTS 2 /* Is this process defined enough to
2314 fetch registers and its stack? */
2315 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
2316 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
2317 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
2321 remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2322 struct gdb_ext_thread_info *info)
2324 struct remote_state *rs = get_remote_state ();
2328 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
2331 /* info->threadid = 0; FIXME: implement zero_threadref. */
2333 info->display[0] = '\0';
2334 info->shortname[0] = '\0';
2335 info->more_display[0] = '\0';
2337 /* Assume the characters indicating the packet type have been
2339 pkt = unpack_int (pkt, &mask); /* arg mask */
2340 pkt = unpack_threadid (pkt, &ref);
2343 warning (_("Incomplete response to threadinfo request."));
2344 if (!threadmatch (&ref, expectedref))
2345 { /* This is an answer to a different request. */
2346 warning (_("ERROR RMT Thread info mismatch."));
2349 copy_threadref (&info->threadid, &ref);
2351 /* Loop on tagged fields , try to bail if somthing goes wrong. */
2353 /* Packets are terminated with nulls. */
2354 while ((pkt < limit) && mask && *pkt)
2356 pkt = unpack_int (pkt, &tag); /* tag */
2357 pkt = unpack_byte (pkt, &length); /* length */
2358 if (!(tag & mask)) /* Tags out of synch with mask. */
2360 warning (_("ERROR RMT: threadinfo tag mismatch."));
2364 if (tag == TAG_THREADID)
2368 warning (_("ERROR RMT: length of threadid is not 16."));
2372 pkt = unpack_threadid (pkt, &ref);
2373 mask = mask & ~TAG_THREADID;
2376 if (tag == TAG_EXISTS)
2378 info->active = stub_unpack_int (pkt, length);
2380 mask = mask & ~(TAG_EXISTS);
2383 warning (_("ERROR RMT: 'exists' length too long."));
2389 if (tag == TAG_THREADNAME)
2391 pkt = unpack_string (pkt, &info->shortname[0], length);
2392 mask = mask & ~TAG_THREADNAME;
2395 if (tag == TAG_DISPLAY)
2397 pkt = unpack_string (pkt, &info->display[0], length);
2398 mask = mask & ~TAG_DISPLAY;
2401 if (tag == TAG_MOREDISPLAY)
2403 pkt = unpack_string (pkt, &info->more_display[0], length);
2404 mask = mask & ~TAG_MOREDISPLAY;
2407 warning (_("ERROR RMT: unknown thread info tag."));
2408 break; /* Not a tag we know about. */
2414 remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
2415 struct gdb_ext_thread_info *info)
2417 struct remote_state *rs = get_remote_state ();
2420 pack_threadinfo_request (rs->buf, fieldset, threadid);
2422 getpkt (&rs->buf, &rs->buf_size, 0);
2424 if (rs->buf[0] == '\0')
2427 result = remote_unpack_thread_info_response (rs->buf + 2,
2432 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
2435 pack_threadlist_request (char *pkt, int startflag, int threadcount,
2436 threadref *nextthread)
2438 *pkt++ = 'q'; /* info query packet */
2439 *pkt++ = 'L'; /* Process LIST or threadLIST request */
2440 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
2441 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
2442 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
2447 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2450 parse_threadlist_response (char *pkt, int result_limit,
2451 threadref *original_echo, threadref *resultlist,
2454 struct remote_state *rs = get_remote_state ();
2456 int count, resultcount, done;
2459 /* Assume the 'q' and 'M chars have been stripped. */
2460 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
2461 /* done parse past here */
2462 pkt = unpack_byte (pkt, &count); /* count field */
2463 pkt = unpack_nibble (pkt, &done);
2464 /* The first threadid is the argument threadid. */
2465 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
2466 while ((count-- > 0) && (pkt < limit))
2468 pkt = unpack_threadid (pkt, resultlist++);
2469 if (resultcount++ >= result_limit)
2477 /* Fetch the next batch of threads from the remote. Returns -1 if the
2478 qL packet is not supported, 0 on error and 1 on success. */
2481 remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2482 int *done, int *result_count, threadref *threadlist)
2484 struct remote_state *rs = get_remote_state ();
2487 /* Trancate result limit to be smaller than the packet size. */
2488 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2489 >= get_remote_packet_size ())
2490 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
2492 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2494 getpkt (&rs->buf, &rs->buf_size, 0);
2495 if (*rs->buf == '\0')
2497 /* Packet not supported. */
2502 parse_threadlist_response (rs->buf + 2, result_limit,
2503 &rs->echo_nextthread, threadlist, done);
2505 if (!threadmatch (&rs->echo_nextthread, nextthread))
2507 /* FIXME: This is a good reason to drop the packet. */
2508 /* Possably, there is a duplicate response. */
2510 retransmit immediatly - race conditions
2511 retransmit after timeout - yes
2513 wait for packet, then exit
2515 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
2516 return 0; /* I choose simply exiting. */
2518 if (*result_count <= 0)
2522 warning (_("RMT ERROR : failed to get remote thread list."));
2525 return result; /* break; */
2527 if (*result_count > result_limit)
2530 warning (_("RMT ERROR: threadlist response longer than requested."));
2536 /* Fetch the list of remote threads, with the qL packet, and call
2537 STEPFUNCTION for each thread found. Stops iterating and returns 1
2538 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
2539 STEPFUNCTION returns false. If the packet is not supported,
2543 remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2546 struct remote_state *rs = get_remote_state ();
2547 int done, i, result_count;
2555 if (loopcount++ > looplimit)
2558 warning (_("Remote fetch threadlist -infinite loop-."));
2561 result = remote_get_threadlist (startflag, &rs->nextthread,
2562 MAXTHREADLISTRESULTS,
2563 &done, &result_count,
2564 rs->resultthreadlist);
2567 /* Clear for later iterations. */
2569 /* Setup to resume next batch of thread references, set nextthread. */
2570 if (result_count >= 1)
2571 copy_threadref (&rs->nextthread,
2572 &rs->resultthreadlist[result_count - 1]);
2574 while (result_count--)
2576 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
2586 /* A thread found on the remote target. */
2588 typedef struct thread_item
2590 /* The thread's PTID. */
2593 /* The thread's extra info. May be NULL. */
2596 /* The core the thread was running on. -1 if not known. */
2599 DEF_VEC_O(thread_item_t);
2601 /* Context passed around to the various methods listing remote
2602 threads. As new threads are found, they're added to the ITEMS
2605 struct threads_listing_context
2607 /* The threads found on the remote target. */
2608 VEC (thread_item_t) *items;
2611 /* Discard the contents of the constructed thread listing context. */
2614 clear_threads_listing_context (void *p)
2616 struct threads_listing_context *context = p;
2618 struct thread_item *item;
2620 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2621 xfree (item->extra);
2623 VEC_free (thread_item_t, context->items);
2627 remote_newthread_step (threadref *ref, void *data)
2629 struct threads_listing_context *context = data;
2630 struct thread_item item;
2631 int pid = ptid_get_pid (inferior_ptid);
2633 item.ptid = ptid_build (pid, threadref_to_int (ref), 0);
2637 VEC_safe_push (thread_item_t, context->items, &item);
2639 return 1; /* continue iterator */
2642 #define CRAZY_MAX_THREADS 1000
2645 remote_current_thread (ptid_t oldpid)
2647 struct remote_state *rs = get_remote_state ();
2650 getpkt (&rs->buf, &rs->buf_size, 0);
2651 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
2652 return read_ptid (&rs->buf[2], NULL);
2657 /* List remote threads using the deprecated qL packet. */
2660 remote_get_threads_with_ql (struct target_ops *ops,
2661 struct threads_listing_context *context)
2663 if (remote_threadlist_iterator (remote_newthread_step, context,
2664 CRAZY_MAX_THREADS) >= 0)
2670 #if defined(HAVE_LIBEXPAT)
2673 start_thread (struct gdb_xml_parser *parser,
2674 const struct gdb_xml_element *element,
2675 void *user_data, VEC(gdb_xml_value_s) *attributes)
2677 struct threads_listing_context *data = user_data;
2679 struct thread_item item;
2681 struct gdb_xml_value *attr;
2683 id = xml_find_attribute (attributes, "id")->value;
2684 item.ptid = read_ptid (id, NULL);
2686 attr = xml_find_attribute (attributes, "core");
2688 item.core = *(ULONGEST *) attr->value;
2694 VEC_safe_push (thread_item_t, data->items, &item);
2698 end_thread (struct gdb_xml_parser *parser,
2699 const struct gdb_xml_element *element,
2700 void *user_data, const char *body_text)
2702 struct threads_listing_context *data = user_data;
2704 if (body_text && *body_text)
2705 VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
2708 const struct gdb_xml_attribute thread_attributes[] = {
2709 { "id", GDB_XML_AF_NONE, NULL, NULL },
2710 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
2711 { NULL, GDB_XML_AF_NONE, NULL, NULL }
2714 const struct gdb_xml_element thread_children[] = {
2715 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2718 const struct gdb_xml_element threads_children[] = {
2719 { "thread", thread_attributes, thread_children,
2720 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
2721 start_thread, end_thread },
2722 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2725 const struct gdb_xml_element threads_elements[] = {
2726 { "threads", NULL, threads_children,
2727 GDB_XML_EF_NONE, NULL, NULL },
2728 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2733 /* List remote threads using qXfer:threads:read. */
2736 remote_get_threads_with_qxfer (struct target_ops *ops,
2737 struct threads_listing_context *context)
2739 #if defined(HAVE_LIBEXPAT)
2740 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
2742 char *xml = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
2743 struct cleanup *back_to = make_cleanup (xfree, xml);
2745 if (xml != NULL && *xml != '\0')
2747 gdb_xml_parse_quick (_("threads"), "threads.dtd",
2748 threads_elements, xml, context);
2751 do_cleanups (back_to);
2759 /* List remote threads using qfThreadInfo/qsThreadInfo. */
2762 remote_get_threads_with_qthreadinfo (struct target_ops *ops,
2763 struct threads_listing_context *context)
2765 struct remote_state *rs = get_remote_state ();
2767 if (rs->use_threadinfo_query)
2771 putpkt ("qfThreadInfo");
2772 getpkt (&rs->buf, &rs->buf_size, 0);
2774 if (bufp[0] != '\0') /* q packet recognized */
2776 while (*bufp++ == 'm') /* reply contains one or more TID */
2780 struct thread_item item;
2782 item.ptid = read_ptid (bufp, &bufp);
2786 VEC_safe_push (thread_item_t, context->items, &item);
2788 while (*bufp++ == ','); /* comma-separated list */
2789 putpkt ("qsThreadInfo");
2790 getpkt (&rs->buf, &rs->buf_size, 0);
2797 /* Packet not recognized. */
2798 rs->use_threadinfo_query = 0;
2805 /* Implement the to_update_thread_list function for the remote
2809 remote_update_thread_list (struct target_ops *ops)
2811 struct remote_state *rs = get_remote_state ();
2812 struct threads_listing_context context;
2813 struct cleanup *old_chain;
2816 context.items = NULL;
2817 old_chain = make_cleanup (clear_threads_listing_context, &context);
2819 /* We have a few different mechanisms to fetch the thread list. Try
2820 them all, starting with the most preferred one first, falling
2821 back to older methods. */
2822 if (remote_get_threads_with_qxfer (ops, &context)
2823 || remote_get_threads_with_qthreadinfo (ops, &context)
2824 || remote_get_threads_with_ql (ops, &context))
2827 struct thread_item *item;
2828 struct thread_info *tp, *tmp;
2832 if (VEC_empty (thread_item_t, context.items)
2833 && remote_thread_always_alive (ops, inferior_ptid))
2835 /* Some targets don't really support threads, but still
2836 reply an (empty) thread list in response to the thread
2837 listing packets, instead of replying "packet not
2838 supported". Exit early so we don't delete the main
2840 do_cleanups (old_chain);
2844 /* CONTEXT now holds the current thread list on the remote
2845 target end. Delete GDB-side threads no longer found on the
2847 ALL_NON_EXITED_THREADS_SAFE (tp, tmp)
2850 VEC_iterate (thread_item_t, context.items, i, item);
2853 if (ptid_equal (item->ptid, tp->ptid))
2857 if (i == VEC_length (thread_item_t, context.items))
2860 delete_thread (tp->ptid);
2864 /* And now add threads we don't know about yet to our list. */
2866 VEC_iterate (thread_item_t, context.items, i, item);
2869 if (!ptid_equal (item->ptid, null_ptid))
2871 struct private_thread_info *info;
2872 /* In non-stop mode, we assume new found threads are
2873 running until proven otherwise with a stop reply. In
2874 all-stop, we can only get here if all threads are
2876 int running = non_stop ? 1 : 0;
2878 remote_notice_new_inferior (item->ptid, running);
2880 info = demand_private_info (item->ptid);
2881 info->core = item->core;
2882 info->extra = item->extra;
2890 /* If no thread listing method is supported, then query whether
2891 each known thread is alive, one by one, with the T packet.
2892 If the target doesn't support threads at all, then this is a
2893 no-op. See remote_thread_alive. */
2897 do_cleanups (old_chain);
2901 * Collect a descriptive string about the given thread.
2902 * The target may say anything it wants to about the thread
2903 * (typically info about its blocked / runnable state, name, etc.).
2904 * This string will appear in the info threads display.
2906 * Optional: targets are not required to implement this function.
2910 remote_threads_extra_info (struct target_ops *self, struct thread_info *tp)
2912 struct remote_state *rs = get_remote_state ();
2916 struct gdb_ext_thread_info threadinfo;
2917 static char display_buf[100]; /* arbitrary... */
2918 int n = 0; /* position in display_buf */
2920 if (rs->remote_desc == 0) /* paranoia */
2921 internal_error (__FILE__, __LINE__,
2922 _("remote_threads_extra_info"));
2924 if (ptid_equal (tp->ptid, magic_null_ptid)
2925 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
2926 /* This is the main thread which was added by GDB. The remote
2927 server doesn't know about it. */
2930 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
2932 struct thread_info *info = find_thread_ptid (tp->ptid);
2934 if (info && info->priv)
2935 return info->priv->extra;
2940 if (rs->use_threadextra_query)
2943 char *endb = rs->buf + get_remote_packet_size ();
2945 xsnprintf (b, endb - b, "qThreadExtraInfo,");
2947 write_ptid (b, endb, tp->ptid);
2950 getpkt (&rs->buf, &rs->buf_size, 0);
2951 if (rs->buf[0] != 0)
2953 n = min (strlen (rs->buf) / 2, sizeof (display_buf));
2954 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
2955 display_buf [result] = '\0';
2960 /* If the above query fails, fall back to the old method. */
2961 rs->use_threadextra_query = 0;
2962 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
2963 | TAG_MOREDISPLAY | TAG_DISPLAY;
2964 int_to_threadref (&id, ptid_get_lwp (tp->ptid));
2965 if (remote_get_threadinfo (&id, set, &threadinfo))
2966 if (threadinfo.active)
2968 if (*threadinfo.shortname)
2969 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
2970 " Name: %s,", threadinfo.shortname);
2971 if (*threadinfo.display)
2972 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
2973 " State: %s,", threadinfo.display);
2974 if (*threadinfo.more_display)
2975 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
2976 " Priority: %s", threadinfo.more_display);
2980 /* For purely cosmetic reasons, clear up trailing commas. */
2981 if (',' == display_buf[n-1])
2982 display_buf[n-1] = ' ';
2991 remote_static_tracepoint_marker_at (struct target_ops *self, CORE_ADDR addr,
2992 struct static_tracepoint_marker *marker)
2994 struct remote_state *rs = get_remote_state ();
2997 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
2999 p += hexnumstr (p, addr);
3001 getpkt (&rs->buf, &rs->buf_size, 0);
3005 error (_("Remote failure reply: %s"), p);
3009 parse_static_tracepoint_marker_definition (p, &p, marker);
3016 static VEC(static_tracepoint_marker_p) *
3017 remote_static_tracepoint_markers_by_strid (struct target_ops *self,
3020 struct remote_state *rs = get_remote_state ();
3021 VEC(static_tracepoint_marker_p) *markers = NULL;
3022 struct static_tracepoint_marker *marker = NULL;
3023 struct cleanup *old_chain;
3026 /* Ask for a first packet of static tracepoint marker
3029 getpkt (&rs->buf, &rs->buf_size, 0);
3032 error (_("Remote failure reply: %s"), p);
3034 old_chain = make_cleanup (free_current_marker, &marker);
3039 marker = XCNEW (struct static_tracepoint_marker);
3043 parse_static_tracepoint_marker_definition (p, &p, marker);
3045 if (strid == NULL || strcmp (strid, marker->str_id) == 0)
3047 VEC_safe_push (static_tracepoint_marker_p,
3053 release_static_tracepoint_marker (marker);
3054 memset (marker, 0, sizeof (*marker));
3057 while (*p++ == ','); /* comma-separated list */
3058 /* Ask for another packet of static tracepoint definition. */
3060 getpkt (&rs->buf, &rs->buf_size, 0);
3064 do_cleanups (old_chain);
3069 /* Implement the to_get_ada_task_ptid function for the remote targets. */
3072 remote_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
3074 return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
3078 /* Restart the remote side; this is an extended protocol operation. */
3081 extended_remote_restart (void)
3083 struct remote_state *rs = get_remote_state ();
3085 /* Send the restart command; for reasons I don't understand the
3086 remote side really expects a number after the "R". */
3087 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
3090 remote_fileio_reset ();
3093 /* Clean up connection to a remote debugger. */
3096 remote_close (struct target_ops *self)
3098 struct remote_state *rs = get_remote_state ();
3100 if (rs->remote_desc == NULL)
3101 return; /* already closed */
3103 /* Make sure we leave stdin registered in the event loop, and we
3104 don't leave the async SIGINT signal handler installed. */
3105 remote_terminal_ours (self);
3107 serial_close (rs->remote_desc);
3108 rs->remote_desc = NULL;
3110 /* We don't have a connection to the remote stub anymore. Get rid
3111 of all the inferiors and their threads we were controlling.
3112 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3113 will be unable to find the thread corresponding to (pid, 0, 0). */
3114 inferior_ptid = null_ptid;
3115 discard_all_inferiors ();
3117 /* We are closing the remote target, so we should discard
3118 everything of this target. */
3119 discard_pending_stop_replies_in_queue (rs);
3121 if (remote_async_inferior_event_token)
3122 delete_async_event_handler (&remote_async_inferior_event_token);
3124 remote_notif_state_xfree (rs->notif_state);
3126 trace_reset_local_state ();
3129 /* Query the remote side for the text, data and bss offsets. */
3134 struct remote_state *rs = get_remote_state ();
3137 int lose, num_segments = 0, do_sections, do_segments;
3138 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
3139 struct section_offsets *offs;
3140 struct symfile_segment_data *data;
3142 if (symfile_objfile == NULL)
3145 putpkt ("qOffsets");
3146 getpkt (&rs->buf, &rs->buf_size, 0);
3149 if (buf[0] == '\000')
3150 return; /* Return silently. Stub doesn't support
3154 warning (_("Remote failure reply: %s"), buf);
3158 /* Pick up each field in turn. This used to be done with scanf, but
3159 scanf will make trouble if CORE_ADDR size doesn't match
3160 conversion directives correctly. The following code will work
3161 with any size of CORE_ADDR. */
3162 text_addr = data_addr = bss_addr = 0;
3166 if (startswith (ptr, "Text="))
3169 /* Don't use strtol, could lose on big values. */
3170 while (*ptr && *ptr != ';')
3171 text_addr = (text_addr << 4) + fromhex (*ptr++);
3173 if (startswith (ptr, ";Data="))
3176 while (*ptr && *ptr != ';')
3177 data_addr = (data_addr << 4) + fromhex (*ptr++);
3182 if (!lose && startswith (ptr, ";Bss="))
3185 while (*ptr && *ptr != ';')
3186 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
3188 if (bss_addr != data_addr)
3189 warning (_("Target reported unsupported offsets: %s"), buf);
3194 else if (startswith (ptr, "TextSeg="))
3197 /* Don't use strtol, could lose on big values. */
3198 while (*ptr && *ptr != ';')
3199 text_addr = (text_addr << 4) + fromhex (*ptr++);
3202 if (startswith (ptr, ";DataSeg="))
3205 while (*ptr && *ptr != ';')
3206 data_addr = (data_addr << 4) + fromhex (*ptr++);
3214 error (_("Malformed response to offset query, %s"), buf);
3215 else if (*ptr != '\0')
3216 warning (_("Target reported unsupported offsets: %s"), buf);
3218 offs = ((struct section_offsets *)
3219 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
3220 memcpy (offs, symfile_objfile->section_offsets,
3221 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
3223 data = get_symfile_segment_data (symfile_objfile->obfd);
3224 do_segments = (data != NULL);
3225 do_sections = num_segments == 0;
3227 if (num_segments > 0)
3229 segments[0] = text_addr;
3230 segments[1] = data_addr;
3232 /* If we have two segments, we can still try to relocate everything
3233 by assuming that the .text and .data offsets apply to the whole
3234 text and data segments. Convert the offsets given in the packet
3235 to base addresses for symfile_map_offsets_to_segments. */
3236 else if (data && data->num_segments == 2)
3238 segments[0] = data->segment_bases[0] + text_addr;
3239 segments[1] = data->segment_bases[1] + data_addr;
3242 /* If the object file has only one segment, assume that it is text
3243 rather than data; main programs with no writable data are rare,
3244 but programs with no code are useless. Of course the code might
3245 have ended up in the data segment... to detect that we would need
3246 the permissions here. */
3247 else if (data && data->num_segments == 1)
3249 segments[0] = data->segment_bases[0] + text_addr;
3252 /* There's no way to relocate by segment. */
3258 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3259 offs, num_segments, segments);
3261 if (ret == 0 && !do_sections)
3262 error (_("Can not handle qOffsets TextSeg "
3263 "response with this symbol file"));
3270 free_symfile_segment_data (data);
3274 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3276 /* This is a temporary kludge to force data and bss to use the
3277 same offsets because that's what nlmconv does now. The real
3278 solution requires changes to the stub and remote.c that I
3279 don't have time to do right now. */
3281 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3282 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3285 objfile_relocate (symfile_objfile, offs);
3288 /* Callback for iterate_over_threads. Set the STOP_REQUESTED flags in
3289 threads we know are stopped already. This is used during the
3290 initial remote connection in non-stop mode --- threads that are
3291 reported as already being stopped are left stopped. */
3294 set_stop_requested_callback (struct thread_info *thread, void *data)
3296 /* If we have a stop reply for this thread, it must be stopped. */
3297 if (peek_stop_reply (thread->ptid))
3298 set_stop_requested (thread->ptid, 1);
3303 /* Send interrupt_sequence to remote target. */
3305 send_interrupt_sequence (void)
3307 struct remote_state *rs = get_remote_state ();
3309 if (interrupt_sequence_mode == interrupt_sequence_control_c)
3310 remote_serial_write ("\x03", 1);
3311 else if (interrupt_sequence_mode == interrupt_sequence_break)
3312 serial_send_break (rs->remote_desc);
3313 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3315 serial_send_break (rs->remote_desc);
3316 remote_serial_write ("g", 1);
3319 internal_error (__FILE__, __LINE__,
3320 _("Invalid value for interrupt_sequence_mode: %s."),
3321 interrupt_sequence_mode);
3325 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
3326 and extract the PTID. Returns NULL_PTID if not found. */
3329 stop_reply_extract_thread (char *stop_reply)
3331 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3335 /* Txx r:val ; r:val (...) */
3338 /* Look for "register" named "thread". */
3343 p1 = strchr (p, ':');
3347 if (strncmp (p, "thread", p1 - p) == 0)
3348 return read_ptid (++p1, &p);
3350 p1 = strchr (p, ';');
3362 /* Determine the remote side's current thread. If we have a stop
3363 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
3364 "thread" register we can extract the current thread from. If not,
3365 ask the remote which is the current thread with qC. The former
3366 method avoids a roundtrip. */
3369 get_current_thread (char *wait_status)
3373 /* Note we don't use remote_parse_stop_reply as that makes use of
3374 the target architecture, which we haven't yet fully determined at
3376 if (wait_status != NULL)
3377 ptid = stop_reply_extract_thread (wait_status);
3378 if (ptid_equal (ptid, null_ptid))
3379 ptid = remote_current_thread (inferior_ptid);
3384 /* Query the remote target for which is the current thread/process,
3385 add it to our tables, and update INFERIOR_PTID. The caller is
3386 responsible for setting the state such that the remote end is ready
3387 to return the current thread.
3389 This function is called after handling the '?' or 'vRun' packets,
3390 whose response is a stop reply from which we can also try
3391 extracting the thread. If the target doesn't support the explicit
3392 qC query, we infer the current thread from that stop reply, passed
3393 in in WAIT_STATUS, which may be NULL. */
3396 add_current_inferior_and_thread (char *wait_status)
3398 struct remote_state *rs = get_remote_state ();
3400 ptid_t ptid = null_ptid;
3402 inferior_ptid = null_ptid;
3404 /* Now, if we have thread information, update inferior_ptid. */
3405 ptid = get_current_thread (wait_status);
3407 if (!ptid_equal (ptid, null_ptid))
3409 if (!remote_multi_process_p (rs))
3412 inferior_ptid = ptid;
3416 /* Without this, some commands which require an active target
3417 (such as kill) won't work. This variable serves (at least)
3418 double duty as both the pid of the target process (if it has
3419 such), and as a flag indicating that a target is active. */
3420 inferior_ptid = magic_null_ptid;
3424 remote_add_inferior (fake_pid_p, ptid_get_pid (inferior_ptid), -1);
3426 /* Add the main thread. */
3427 add_thread_silent (inferior_ptid);
3431 remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
3433 struct remote_state *rs = get_remote_state ();
3434 struct packet_config *noack_config;
3435 char *wait_status = NULL;
3437 immediate_quit++; /* Allow user to interrupt it. */
3440 if (interrupt_on_connect)
3441 send_interrupt_sequence ();
3443 /* Ack any packet which the remote side has already sent. */
3444 serial_write (rs->remote_desc, "+", 1);
3446 /* Signal other parts that we're going through the initial setup,
3447 and so things may not be stable yet. */
3448 rs->starting_up = 1;
3450 /* The first packet we send to the target is the optional "supported
3451 packets" request. If the target can answer this, it will tell us
3452 which later probes to skip. */
3453 remote_query_supported ();
3455 /* If the stub wants to get a QAllow, compose one and send it. */
3456 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
3457 remote_set_permissions (target);
3459 /* Next, we possibly activate noack mode.
3461 If the QStartNoAckMode packet configuration is set to AUTO,
3462 enable noack mode if the stub reported a wish for it with
3465 If set to TRUE, then enable noack mode even if the stub didn't
3466 report it in qSupported. If the stub doesn't reply OK, the
3467 session ends with an error.
3469 If FALSE, then don't activate noack mode, regardless of what the
3470 stub claimed should be the default with qSupported. */
3472 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
3473 if (packet_config_support (noack_config) != PACKET_DISABLE)
3475 putpkt ("QStartNoAckMode");
3476 getpkt (&rs->buf, &rs->buf_size, 0);
3477 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
3483 /* Tell the remote that we are using the extended protocol. */
3485 getpkt (&rs->buf, &rs->buf_size, 0);
3488 /* Let the target know which signals it is allowed to pass down to
3490 update_signals_program_target ();
3492 /* Next, if the target can specify a description, read it. We do
3493 this before anything involving memory or registers. */
3494 target_find_description ();
3496 /* Next, now that we know something about the target, update the
3497 address spaces in the program spaces. */
3498 update_address_spaces ();
3500 /* On OSs where the list of libraries is global to all
3501 processes, we fetch them early. */
3502 if (gdbarch_has_global_solist (target_gdbarch ()))
3503 solib_add (NULL, from_tty, target, auto_solib_add);
3507 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
3508 error (_("Non-stop mode requested, but remote "
3509 "does not support non-stop"));
3511 putpkt ("QNonStop:1");
3512 getpkt (&rs->buf, &rs->buf_size, 0);
3514 if (strcmp (rs->buf, "OK") != 0)
3515 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
3517 /* Find about threads and processes the stub is already
3518 controlling. We default to adding them in the running state.
3519 The '?' query below will then tell us about which threads are
3521 remote_update_thread_list (target);
3523 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
3525 /* Don't assume that the stub can operate in all-stop mode.
3526 Request it explicitly. */
3527 putpkt ("QNonStop:0");
3528 getpkt (&rs->buf, &rs->buf_size, 0);
3530 if (strcmp (rs->buf, "OK") != 0)
3531 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
3534 /* Upload TSVs regardless of whether the target is running or not. The
3535 remote stub, such as GDBserver, may have some predefined or builtin
3536 TSVs, even if the target is not running. */
3537 if (remote_get_trace_status (target, current_trace_status ()) != -1)
3539 struct uploaded_tsv *uploaded_tsvs = NULL;
3541 remote_upload_trace_state_variables (target, &uploaded_tsvs);
3542 merge_uploaded_trace_state_variables (&uploaded_tsvs);
3545 /* Check whether the target is running now. */
3547 getpkt (&rs->buf, &rs->buf_size, 0);
3553 struct inferior *inf;
3555 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
3558 error (_("The target is not running (try extended-remote?)"));
3560 /* We're connected, but not running. Drop out before we
3561 call start_remote. */
3562 rs->starting_up = 0;
3567 /* Save the reply for later. */
3568 wait_status = alloca (strlen (rs->buf) + 1);
3569 strcpy (wait_status, rs->buf);
3572 /* Fetch thread list. */
3573 target_update_thread_list ();
3575 /* Let the stub know that we want it to return the thread. */
3576 set_continue_thread (minus_one_ptid);
3578 if (thread_count () == 0)
3580 /* Target has no concept of threads at all. GDB treats
3581 non-threaded target as single-threaded; add a main
3583 add_current_inferior_and_thread (wait_status);
3587 /* We have thread information; select the thread the target
3588 says should be current. If we're reconnecting to a
3589 multi-threaded program, this will ideally be the thread
3590 that last reported an event before GDB disconnected. */
3591 inferior_ptid = get_current_thread (wait_status);
3592 if (ptid_equal (inferior_ptid, null_ptid))
3594 /* Odd... The target was able to list threads, but not
3595 tell us which thread was current (no "thread"
3596 register in T stop reply?). Just pick the first
3597 thread in the thread list then. */
3598 inferior_ptid = thread_list->ptid;
3602 /* init_wait_for_inferior should be called before get_offsets in order
3603 to manage `inserted' flag in bp loc in a correct state.
3604 breakpoint_init_inferior, called from init_wait_for_inferior, set
3605 `inserted' flag to 0, while before breakpoint_re_set, called from
3606 start_remote, set `inserted' flag to 1. In the initialization of
3607 inferior, breakpoint_init_inferior should be called first, and then
3608 breakpoint_re_set can be called. If this order is broken, state of
3609 `inserted' flag is wrong, and cause some problems on breakpoint
3611 init_wait_for_inferior ();
3613 get_offsets (); /* Get text, data & bss offsets. */
3615 /* If we could not find a description using qXfer, and we know
3616 how to do it some other way, try again. This is not
3617 supported for non-stop; it could be, but it is tricky if
3618 there are no stopped threads when we connect. */
3619 if (remote_read_description_p (target)
3620 && gdbarch_target_desc (target_gdbarch ()) == NULL)
3622 target_clear_description ();
3623 target_find_description ();
3626 /* Use the previously fetched status. */
3627 gdb_assert (wait_status != NULL);
3628 strcpy (rs->buf, wait_status);
3629 rs->cached_wait_status = 1;
3632 start_remote (from_tty); /* Initialize gdb process mechanisms. */
3636 /* Clear WFI global state. Do this before finding about new
3637 threads and inferiors, and setting the current inferior.
3638 Otherwise we would clear the proceed status of the current
3639 inferior when we want its stop_soon state to be preserved
3640 (see notice_new_inferior). */
3641 init_wait_for_inferior ();
3643 /* In non-stop, we will either get an "OK", meaning that there
3644 are no stopped threads at this time; or, a regular stop
3645 reply. In the latter case, there may be more than one thread
3646 stopped --- we pull them all out using the vStopped
3648 if (strcmp (rs->buf, "OK") != 0)
3650 struct notif_client *notif = ¬if_client_stop;
3652 /* remote_notif_get_pending_replies acks this one, and gets
3654 rs->notif_state->pending_event[notif_client_stop.id]
3655 = remote_notif_parse (notif, rs->buf);
3656 remote_notif_get_pending_events (notif);
3658 /* Make sure that threads that were stopped remain
3660 iterate_over_threads (set_stop_requested_callback, NULL);
3663 if (target_can_async_p ())
3664 target_async (inferior_event_handler, 0);
3666 if (thread_count () == 0)
3669 error (_("The target is not running (try extended-remote?)"));
3671 /* We're connected, but not running. Drop out before we
3672 call start_remote. */
3673 rs->starting_up = 0;
3677 /* Let the stub know that we want it to return the thread. */
3679 /* Force the stub to choose a thread. */
3680 set_general_thread (null_ptid);
3683 inferior_ptid = remote_current_thread (minus_one_ptid);
3684 if (ptid_equal (inferior_ptid, minus_one_ptid))
3685 error (_("remote didn't report the current thread in non-stop mode"));
3687 get_offsets (); /* Get text, data & bss offsets. */
3689 /* In non-stop mode, any cached wait status will be stored in
3690 the stop reply queue. */
3691 gdb_assert (wait_status == NULL);
3693 /* Report all signals during attach/startup. */
3694 remote_pass_signals (target, 0, NULL);
3697 /* If we connected to a live target, do some additional setup. */
3698 if (target_has_execution)
3700 if (symfile_objfile) /* No use without a symbol-file. */
3701 remote_check_symbols ();
3704 /* Possibly the target has been engaged in a trace run started
3705 previously; find out where things are at. */
3706 if (remote_get_trace_status (target, current_trace_status ()) != -1)
3708 struct uploaded_tp *uploaded_tps = NULL;
3710 if (current_trace_status ()->running)
3711 printf_filtered (_("Trace is already running on the target.\n"));
3713 remote_upload_tracepoints (target, &uploaded_tps);
3715 merge_uploaded_tracepoints (&uploaded_tps);
3718 /* The thread and inferior lists are now synchronized with the
3719 target, our symbols have been relocated, and we're merged the
3720 target's tracepoints with ours. We're done with basic start
3722 rs->starting_up = 0;
3724 /* Maybe breakpoints are global and need to be inserted now. */
3725 if (breakpoints_should_be_inserted_now ())
3726 insert_breakpoints ();
3729 /* Open a connection to a remote debugger.
3730 NAME is the filename used for communication. */
3733 remote_open (const char *name, int from_tty)
3735 remote_open_1 (name, from_tty, &remote_ops, 0);
3738 /* Open a connection to a remote debugger using the extended
3739 remote gdb protocol. NAME is the filename used for communication. */
3742 extended_remote_open (const char *name, int from_tty)
3744 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
3747 /* Reset all packets back to "unknown support". Called when opening a
3748 new connection to a remote target. */
3751 reset_all_packet_configs_support (void)
3755 for (i = 0; i < PACKET_MAX; i++)
3756 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
3759 /* Initialize all packet configs. */
3762 init_all_packet_configs (void)
3766 for (i = 0; i < PACKET_MAX; i++)
3768 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
3769 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
3773 /* Symbol look-up. */
3776 remote_check_symbols (void)
3778 struct remote_state *rs = get_remote_state ();
3779 char *msg, *reply, *tmp;
3780 struct bound_minimal_symbol sym;
3783 /* The remote side has no concept of inferiors that aren't running
3784 yet, it only knows about running processes. If we're connected
3785 but our current inferior is not running, we should not invite the
3786 remote target to request symbol lookups related to its
3787 (unrelated) current process. */
3788 if (!target_has_execution)
3791 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
3794 /* Make sure the remote is pointing at the right process. Note
3795 there's no way to select "no process". */
3796 set_general_process ();
3798 /* Allocate a message buffer. We can't reuse the input buffer in RS,
3799 because we need both at the same time. */
3800 msg = alloca (get_remote_packet_size ());
3802 /* Invite target to request symbol lookups. */
3804 putpkt ("qSymbol::");
3805 getpkt (&rs->buf, &rs->buf_size, 0);
3806 packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSymbol]);
3809 while (startswith (reply, "qSymbol:"))
3811 struct bound_minimal_symbol sym;
3814 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
3816 sym = lookup_minimal_symbol (msg, NULL, NULL);
3817 if (sym.minsym == NULL)
3818 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
3821 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
3822 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
3824 /* If this is a function address, return the start of code
3825 instead of any data function descriptor. */
3826 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
3830 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
3831 phex_nz (sym_addr, addr_size), &reply[8]);
3835 getpkt (&rs->buf, &rs->buf_size, 0);
3840 static struct serial *
3841 remote_serial_open (const char *name)
3843 static int udp_warning = 0;
3845 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
3846 of in ser-tcp.c, because it is the remote protocol assuming that the
3847 serial connection is reliable and not the serial connection promising
3849 if (!udp_warning && startswith (name, "udp:"))
3851 warning (_("The remote protocol may be unreliable over UDP.\n"
3852 "Some events may be lost, rendering further debugging "
3857 return serial_open (name);
3860 /* Inform the target of our permission settings. The permission flags
3861 work without this, but if the target knows the settings, it can do
3862 a couple things. First, it can add its own check, to catch cases
3863 that somehow manage to get by the permissions checks in target
3864 methods. Second, if the target is wired to disallow particular
3865 settings (for instance, a system in the field that is not set up to
3866 be able to stop at a breakpoint), it can object to any unavailable
3870 remote_set_permissions (struct target_ops *self)
3872 struct remote_state *rs = get_remote_state ();
3874 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
3875 "WriteReg:%x;WriteMem:%x;"
3876 "InsertBreak:%x;InsertTrace:%x;"
3877 "InsertFastTrace:%x;Stop:%x",
3878 may_write_registers, may_write_memory,
3879 may_insert_breakpoints, may_insert_tracepoints,
3880 may_insert_fast_tracepoints, may_stop);
3882 getpkt (&rs->buf, &rs->buf_size, 0);
3884 /* If the target didn't like the packet, warn the user. Do not try
3885 to undo the user's settings, that would just be maddening. */
3886 if (strcmp (rs->buf, "OK") != 0)
3887 warning (_("Remote refused setting permissions with: %s"), rs->buf);
3890 /* This type describes each known response to the qSupported
3892 struct protocol_feature
3894 /* The name of this protocol feature. */
3897 /* The default for this protocol feature. */
3898 enum packet_support default_support;
3900 /* The function to call when this feature is reported, or after
3901 qSupported processing if the feature is not supported.
3902 The first argument points to this structure. The second
3903 argument indicates whether the packet requested support be
3904 enabled, disabled, or probed (or the default, if this function
3905 is being called at the end of processing and this feature was
3906 not reported). The third argument may be NULL; if not NULL, it
3907 is a NUL-terminated string taken from the packet following
3908 this feature's name and an equals sign. */
3909 void (*func) (const struct protocol_feature *, enum packet_support,
3912 /* The corresponding packet for this feature. Only used if
3913 FUNC is remote_supported_packet. */
3918 remote_supported_packet (const struct protocol_feature *feature,
3919 enum packet_support support,
3920 const char *argument)
3924 warning (_("Remote qSupported response supplied an unexpected value for"
3925 " \"%s\"."), feature->name);
3929 remote_protocol_packets[feature->packet].support = support;
3933 remote_packet_size (const struct protocol_feature *feature,
3934 enum packet_support support, const char *value)
3936 struct remote_state *rs = get_remote_state ();
3941 if (support != PACKET_ENABLE)
3944 if (value == NULL || *value == '\0')
3946 warning (_("Remote target reported \"%s\" without a size."),
3952 packet_size = strtol (value, &value_end, 16);
3953 if (errno != 0 || *value_end != '\0' || packet_size < 0)
3955 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
3956 feature->name, value);
3960 if (packet_size > MAX_REMOTE_PACKET_SIZE)
3962 warning (_("limiting remote suggested packet size (%d bytes) to %d"),
3963 packet_size, MAX_REMOTE_PACKET_SIZE);
3964 packet_size = MAX_REMOTE_PACKET_SIZE;
3967 /* Record the new maximum packet size. */
3968 rs->explicit_packet_size = packet_size;
3971 static const struct protocol_feature remote_protocol_features[] = {
3972 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
3973 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
3974 PACKET_qXfer_auxv },
3975 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
3976 PACKET_qXfer_features },
3977 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
3978 PACKET_qXfer_libraries },
3979 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
3980 PACKET_qXfer_libraries_svr4 },
3981 { "augmented-libraries-svr4-read", PACKET_DISABLE,
3982 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
3983 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
3984 PACKET_qXfer_memory_map },
3985 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
3986 PACKET_qXfer_spu_read },
3987 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
3988 PACKET_qXfer_spu_write },
3989 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
3990 PACKET_qXfer_osdata },
3991 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
3992 PACKET_qXfer_threads },
3993 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
3994 PACKET_qXfer_traceframe_info },
3995 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
3996 PACKET_QPassSignals },
3997 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
3998 PACKET_QProgramSignals },
3999 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
4000 PACKET_QStartNoAckMode },
4001 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
4002 PACKET_multiprocess_feature },
4003 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4004 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
4005 PACKET_qXfer_siginfo_read },
4006 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4007 PACKET_qXfer_siginfo_write },
4008 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
4009 PACKET_ConditionalTracepoints },
4010 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
4011 PACKET_ConditionalBreakpoints },
4012 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
4013 PACKET_BreakpointCommands },
4014 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
4015 PACKET_FastTracepoints },
4016 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
4017 PACKET_StaticTracepoints },
4018 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
4019 PACKET_InstallInTrace},
4020 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
4021 PACKET_DisconnectedTracing_feature },
4022 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4024 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4026 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4027 PACKET_TracepointSource },
4028 { "QAllow", PACKET_DISABLE, remote_supported_packet,
4030 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
4031 PACKET_EnableDisableTracepoints_feature },
4032 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4033 PACKET_qXfer_fdpic },
4034 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4036 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4037 PACKET_QDisableRandomization },
4038 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
4039 { "QTBuffer:size", PACKET_DISABLE,
4040 remote_supported_packet, PACKET_QTBuffer_size},
4041 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
4042 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4043 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
4044 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
4045 PACKET_qXfer_btrace },
4046 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
4047 PACKET_qXfer_btrace_conf },
4048 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
4049 PACKET_Qbtrace_conf_bts_size },
4050 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
4051 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
4052 { "vFile:fstat", PACKET_DISABLE, remote_supported_packet,
4053 PACKET_vFile_fstat },
4056 static char *remote_support_xml;
4058 /* Register string appended to "xmlRegisters=" in qSupported query. */
4061 register_remote_support_xml (const char *xml)
4063 #if defined(HAVE_LIBEXPAT)
4064 if (remote_support_xml == NULL)
4065 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
4068 char *copy = xstrdup (remote_support_xml + 13);
4069 char *p = strtok (copy, ",");
4073 if (strcmp (p, xml) == 0)
4080 while ((p = strtok (NULL, ",")) != NULL);
4083 remote_support_xml = reconcat (remote_support_xml,
4084 remote_support_xml, ",", xml,
4091 remote_query_supported_append (char *msg, const char *append)
4094 return reconcat (msg, msg, ";", append, (char *) NULL);
4096 return xstrdup (append);
4100 remote_query_supported (void)
4102 struct remote_state *rs = get_remote_state ();
4105 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4107 /* The packet support flags are handled differently for this packet
4108 than for most others. We treat an error, a disabled packet, and
4109 an empty response identically: any features which must be reported
4110 to be used will be automatically disabled. An empty buffer
4111 accomplishes this, since that is also the representation for a list
4112 containing no features. */
4115 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
4118 struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
4120 q = remote_query_supported_append (q, "multiprocess+");
4122 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
4123 q = remote_query_supported_append (q, "swbreak+");
4124 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
4125 q = remote_query_supported_append (q, "hwbreak+");
4127 if (remote_support_xml)
4128 q = remote_query_supported_append (q, remote_support_xml);
4130 q = remote_query_supported_append (q, "qRelocInsn+");
4132 q = reconcat (q, "qSupported:", q, (char *) NULL);
4135 do_cleanups (old_chain);
4137 getpkt (&rs->buf, &rs->buf_size, 0);
4139 /* If an error occured, warn, but do not return - just reset the
4140 buffer to empty and go on to disable features. */
4141 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4144 warning (_("Remote failure reply: %s"), rs->buf);
4149 memset (seen, 0, sizeof (seen));
4154 enum packet_support is_supported;
4155 char *p, *end, *name_end, *value;
4157 /* First separate out this item from the rest of the packet. If
4158 there's another item after this, we overwrite the separator
4159 (terminated strings are much easier to work with). */
4161 end = strchr (p, ';');
4164 end = p + strlen (p);
4174 warning (_("empty item in \"qSupported\" response"));
4179 name_end = strchr (p, '=');
4182 /* This is a name=value entry. */
4183 is_supported = PACKET_ENABLE;
4184 value = name_end + 1;
4193 is_supported = PACKET_ENABLE;
4197 is_supported = PACKET_DISABLE;
4201 is_supported = PACKET_SUPPORT_UNKNOWN;
4205 warning (_("unrecognized item \"%s\" "
4206 "in \"qSupported\" response"), p);
4212 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4213 if (strcmp (remote_protocol_features[i].name, p) == 0)
4215 const struct protocol_feature *feature;
4218 feature = &remote_protocol_features[i];
4219 feature->func (feature, is_supported, value);
4224 /* If we increased the packet size, make sure to increase the global
4225 buffer size also. We delay this until after parsing the entire
4226 qSupported packet, because this is the same buffer we were
4228 if (rs->buf_size < rs->explicit_packet_size)
4230 rs->buf_size = rs->explicit_packet_size;
4231 rs->buf = xrealloc (rs->buf, rs->buf_size);
4234 /* Handle the defaults for unmentioned features. */
4235 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4238 const struct protocol_feature *feature;
4240 feature = &remote_protocol_features[i];
4241 feature->func (feature, feature->default_support, NULL);
4245 /* Remove any of the remote.c targets from target stack. Upper targets depend
4246 on it so remove them first. */
4249 remote_unpush_target (void)
4251 pop_all_targets_above (process_stratum - 1);
4255 remote_open_1 (const char *name, int from_tty,
4256 struct target_ops *target, int extended_p)
4258 struct remote_state *rs = get_remote_state ();
4261 error (_("To open a remote debug connection, you need to specify what\n"
4262 "serial device is attached to the remote system\n"
4263 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
4265 /* See FIXME above. */
4266 if (!target_async_permitted)
4267 wait_forever_enabled_p = 1;
4269 /* If we're connected to a running target, target_preopen will kill it.
4270 Ask this question first, before target_preopen has a chance to kill
4272 if (rs->remote_desc != NULL && !have_inferiors ())
4275 && !query (_("Already connected to a remote target. Disconnect? ")))
4276 error (_("Still connected."));
4279 /* Here the possibly existing remote target gets unpushed. */
4280 target_preopen (from_tty);
4282 /* Make sure we send the passed signals list the next time we resume. */
4283 xfree (rs->last_pass_packet);
4284 rs->last_pass_packet = NULL;
4286 /* Make sure we send the program signals list the next time we
4288 xfree (rs->last_program_signals_packet);
4289 rs->last_program_signals_packet = NULL;
4291 remote_fileio_reset ();
4292 reopen_exec_file ();
4295 rs->remote_desc = remote_serial_open (name);
4296 if (!rs->remote_desc)
4297 perror_with_name (name);
4299 if (baud_rate != -1)
4301 if (serial_setbaudrate (rs->remote_desc, baud_rate))
4303 /* The requested speed could not be set. Error out to
4304 top level after closing remote_desc. Take care to
4305 set remote_desc to NULL to avoid closing remote_desc
4307 serial_close (rs->remote_desc);
4308 rs->remote_desc = NULL;
4309 perror_with_name (name);
4313 serial_raw (rs->remote_desc);
4315 /* If there is something sitting in the buffer we might take it as a
4316 response to a command, which would be bad. */
4317 serial_flush_input (rs->remote_desc);
4321 puts_filtered ("Remote debugging using ");
4322 puts_filtered (name);
4323 puts_filtered ("\n");
4325 push_target (target); /* Switch to using remote target now. */
4327 /* Register extra event sources in the event loop. */
4328 remote_async_inferior_event_token
4329 = create_async_event_handler (remote_async_inferior_event_handler,
4331 rs->notif_state = remote_notif_state_allocate ();
4333 /* Reset the target state; these things will be queried either by
4334 remote_query_supported or as they are needed. */
4335 reset_all_packet_configs_support ();
4336 rs->cached_wait_status = 0;
4337 rs->explicit_packet_size = 0;
4339 rs->extended = extended_p;
4340 rs->waiting_for_stop_reply = 0;
4341 rs->ctrlc_pending_p = 0;
4343 rs->general_thread = not_sent_ptid;
4344 rs->continue_thread = not_sent_ptid;
4345 rs->remote_traceframe_number = -1;
4347 /* Probe for ability to use "ThreadInfo" query, as required. */
4348 rs->use_threadinfo_query = 1;
4349 rs->use_threadextra_query = 1;
4351 if (target_async_permitted)
4353 /* With this target we start out by owning the terminal. */
4354 remote_async_terminal_ours_p = 1;
4356 /* FIXME: cagney/1999-09-23: During the initial connection it is
4357 assumed that the target is already ready and able to respond to
4358 requests. Unfortunately remote_start_remote() eventually calls
4359 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
4360 around this. Eventually a mechanism that allows
4361 wait_for_inferior() to expect/get timeouts will be
4363 wait_forever_enabled_p = 0;
4366 /* First delete any symbols previously loaded from shared libraries. */
4367 no_shared_libraries (NULL, 0);
4370 init_thread_list ();
4372 /* Start the remote connection. If error() or QUIT, discard this
4373 target (we'd otherwise be in an inconsistent state) and then
4374 propogate the error on up the exception chain. This ensures that
4375 the caller doesn't stumble along blindly assuming that the
4376 function succeeded. The CLI doesn't have this problem but other
4377 UI's, such as MI do.
4379 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
4380 this function should return an error indication letting the
4381 caller restore the previous state. Unfortunately the command
4382 ``target remote'' is directly wired to this function making that
4383 impossible. On a positive note, the CLI side of this problem has
4384 been fixed - the function set_cmd_context() makes it possible for
4385 all the ``target ....'' commands to share a common callback
4386 function. See cli-dump.c. */
4391 remote_start_remote (from_tty, target, extended_p);
4393 CATCH (ex, RETURN_MASK_ALL)
4395 /* Pop the partially set up target - unless something else did
4396 already before throwing the exception. */
4397 if (rs->remote_desc != NULL)
4398 remote_unpush_target ();
4399 if (target_async_permitted)
4400 wait_forever_enabled_p = 1;
4401 throw_exception (ex);
4406 remote_btrace_reset ();
4408 if (target_async_permitted)
4409 wait_forever_enabled_p = 1;
4412 /* This takes a program previously attached to and detaches it. After
4413 this is done, GDB can be used to debug some other program. We
4414 better not have left any breakpoints in the target program or it'll
4415 die when it hits one. */
4418 remote_detach_1 (const char *args, int from_tty, int extended)
4420 int pid = ptid_get_pid (inferior_ptid);
4421 struct remote_state *rs = get_remote_state ();
4424 error (_("Argument given to \"detach\" when remotely debugging."));
4426 if (!target_has_execution)
4427 error (_("No process to detach from."));
4431 char *exec_file = get_exec_file (0);
4432 if (exec_file == NULL)
4434 printf_unfiltered (_("Detaching from program: %s, %s\n"), exec_file,
4435 target_pid_to_str (pid_to_ptid (pid)));
4436 gdb_flush (gdb_stdout);
4439 /* Tell the remote target to detach. */
4440 if (remote_multi_process_p (rs))
4441 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
4443 strcpy (rs->buf, "D");
4446 getpkt (&rs->buf, &rs->buf_size, 0);
4448 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
4450 else if (rs->buf[0] == '\0')
4451 error (_("Remote doesn't know how to detach"));
4453 error (_("Can't detach process."));
4455 if (from_tty && !extended)
4456 puts_filtered (_("Ending remote debugging.\n"));
4458 target_mourn_inferior ();
4462 remote_detach (struct target_ops *ops, const char *args, int from_tty)
4464 remote_detach_1 (args, from_tty, 0);
4468 extended_remote_detach (struct target_ops *ops, const char *args, int from_tty)
4470 remote_detach_1 (args, from_tty, 1);
4473 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
4476 remote_disconnect (struct target_ops *target, const char *args, int from_tty)
4479 error (_("Argument given to \"disconnect\" when remotely debugging."));
4481 /* Make sure we unpush even the extended remote targets; mourn
4482 won't do it. So call remote_mourn_1 directly instead of
4483 target_mourn_inferior. */
4484 remote_mourn_1 (target);
4487 puts_filtered ("Ending remote debugging.\n");
4490 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
4491 be chatty about it. */
4494 extended_remote_attach_1 (struct target_ops *target, const char *args,
4497 struct remote_state *rs = get_remote_state ();
4499 char *wait_status = NULL;
4501 pid = parse_pid_to_attach (args);
4503 /* Remote PID can be freely equal to getpid, do not check it here the same
4504 way as in other targets. */
4506 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
4507 error (_("This target does not support attaching to a process"));
4511 char *exec_file = get_exec_file (0);
4514 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
4515 target_pid_to_str (pid_to_ptid (pid)));
4517 printf_unfiltered (_("Attaching to %s\n"),
4518 target_pid_to_str (pid_to_ptid (pid)));
4520 gdb_flush (gdb_stdout);
4523 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
4525 getpkt (&rs->buf, &rs->buf_size, 0);
4527 switch (packet_ok (rs->buf,
4528 &remote_protocol_packets[PACKET_vAttach]))
4533 /* Save the reply for later. */
4534 wait_status = alloca (strlen (rs->buf) + 1);
4535 strcpy (wait_status, rs->buf);
4537 else if (strcmp (rs->buf, "OK") != 0)
4538 error (_("Attaching to %s failed with: %s"),
4539 target_pid_to_str (pid_to_ptid (pid)),
4542 case PACKET_UNKNOWN:
4543 error (_("This target does not support attaching to a process"));
4545 error (_("Attaching to %s failed"),
4546 target_pid_to_str (pid_to_ptid (pid)));
4549 set_current_inferior (remote_add_inferior (0, pid, 1));
4551 inferior_ptid = pid_to_ptid (pid);
4555 struct thread_info *thread;
4557 /* Get list of threads. */
4558 remote_update_thread_list (target);
4560 thread = first_thread_of_process (pid);
4562 inferior_ptid = thread->ptid;
4564 inferior_ptid = pid_to_ptid (pid);
4566 /* Invalidate our notion of the remote current thread. */
4567 record_currthread (rs, minus_one_ptid);
4571 /* Now, if we have thread information, update inferior_ptid. */
4572 inferior_ptid = remote_current_thread (inferior_ptid);
4574 /* Add the main thread to the thread list. */
4575 add_thread_silent (inferior_ptid);
4578 /* Next, if the target can specify a description, read it. We do
4579 this before anything involving memory or registers. */
4580 target_find_description ();
4584 /* Use the previously fetched status. */
4585 gdb_assert (wait_status != NULL);
4587 if (target_can_async_p ())
4589 struct notif_event *reply
4590 = remote_notif_parse (¬if_client_stop, wait_status);
4592 push_stop_reply ((struct stop_reply *) reply);
4594 target_async (inferior_event_handler, 0);
4598 gdb_assert (wait_status != NULL);
4599 strcpy (rs->buf, wait_status);
4600 rs->cached_wait_status = 1;
4604 gdb_assert (wait_status == NULL);
4608 extended_remote_attach (struct target_ops *ops, const char *args, int from_tty)
4610 extended_remote_attach_1 (ops, args, from_tty);
4613 /* Implementation of the to_post_attach method. */
4616 extended_remote_post_attach (struct target_ops *ops, int pid)
4618 /* In certain cases GDB might not have had the chance to start
4619 symbol lookup up until now. This could happen if the debugged
4620 binary is not using shared libraries, the vsyscall page is not
4621 present (on Linux) and the binary itself hadn't changed since the
4622 debugging process was started. */
4623 if (symfile_objfile != NULL)
4624 remote_check_symbols();
4628 /* Check for the availability of vCont. This function should also check
4632 remote_vcont_probe (struct remote_state *rs)
4636 strcpy (rs->buf, "vCont?");
4638 getpkt (&rs->buf, &rs->buf_size, 0);
4641 /* Make sure that the features we assume are supported. */
4642 if (startswith (buf, "vCont"))
4645 int support_s, support_S, support_c, support_C;
4651 rs->supports_vCont.t = 0;
4652 rs->supports_vCont.r = 0;
4653 while (p && *p == ';')
4656 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
4658 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
4660 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
4662 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
4664 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
4665 rs->supports_vCont.t = 1;
4666 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
4667 rs->supports_vCont.r = 1;
4669 p = strchr (p, ';');
4672 /* If s, S, c, and C are not all supported, we can't use vCont. Clearing
4673 BUF will make packet_ok disable the packet. */
4674 if (!support_s || !support_S || !support_c || !support_C)
4678 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
4681 /* Helper function for building "vCont" resumptions. Write a
4682 resumption to P. ENDP points to one-passed-the-end of the buffer
4683 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
4684 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
4685 resumed thread should be single-stepped and/or signalled. If PTID
4686 equals minus_one_ptid, then all threads are resumed; if PTID
4687 represents a process, then all threads of the process are resumed;
4688 the thread to be stepped and/or signalled is given in the global
4692 append_resumption (char *p, char *endp,
4693 ptid_t ptid, int step, enum gdb_signal siggnal)
4695 struct remote_state *rs = get_remote_state ();
4697 if (step && siggnal != GDB_SIGNAL_0)
4698 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
4700 /* GDB is willing to range step. */
4701 && use_range_stepping
4702 /* Target supports range stepping. */
4703 && rs->supports_vCont.r
4704 /* We don't currently support range stepping multiple
4705 threads with a wildcard (though the protocol allows it,
4706 so stubs shouldn't make an active effort to forbid
4708 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
4710 struct thread_info *tp;
4712 if (ptid_equal (ptid, minus_one_ptid))
4714 /* If we don't know about the target thread's tid, then
4715 we're resuming magic_null_ptid (see caller). */
4716 tp = find_thread_ptid (magic_null_ptid);
4719 tp = find_thread_ptid (ptid);
4720 gdb_assert (tp != NULL);
4722 if (tp->control.may_range_step)
4724 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4726 p += xsnprintf (p, endp - p, ";r%s,%s",
4727 phex_nz (tp->control.step_range_start,
4729 phex_nz (tp->control.step_range_end,
4733 p += xsnprintf (p, endp - p, ";s");
4736 p += xsnprintf (p, endp - p, ";s");
4737 else if (siggnal != GDB_SIGNAL_0)
4738 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
4740 p += xsnprintf (p, endp - p, ";c");
4742 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
4746 /* All (-1) threads of process. */
4747 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
4749 p += xsnprintf (p, endp - p, ":");
4750 p = write_ptid (p, endp, nptid);
4752 else if (!ptid_equal (ptid, minus_one_ptid))
4754 p += xsnprintf (p, endp - p, ":");
4755 p = write_ptid (p, endp, ptid);
4761 /* Append a vCont continue-with-signal action for threads that have a
4762 non-zero stop signal. */
4765 append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
4767 struct thread_info *thread;
4769 ALL_NON_EXITED_THREADS (thread)
4770 if (ptid_match (thread->ptid, ptid)
4771 && !ptid_equal (inferior_ptid, thread->ptid)
4772 && thread->suspend.stop_signal != GDB_SIGNAL_0)
4774 p = append_resumption (p, endp, thread->ptid,
4775 0, thread->suspend.stop_signal);
4776 thread->suspend.stop_signal = GDB_SIGNAL_0;
4782 /* Resume the remote inferior by using a "vCont" packet. The thread
4783 to be resumed is PTID; STEP and SIGGNAL indicate whether the
4784 resumed thread should be single-stepped and/or signalled. If PTID
4785 equals minus_one_ptid, then all threads are resumed; the thread to
4786 be stepped and/or signalled is given in the global INFERIOR_PTID.
4787 This function returns non-zero iff it resumes the inferior.
4789 This function issues a strict subset of all possible vCont commands at the
4793 remote_vcont_resume (ptid_t ptid, int step, enum gdb_signal siggnal)
4795 struct remote_state *rs = get_remote_state ();
4799 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
4800 remote_vcont_probe (rs);
4802 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
4806 endp = rs->buf + get_remote_packet_size ();
4808 /* If we could generate a wider range of packets, we'd have to worry
4809 about overflowing BUF. Should there be a generic
4810 "multi-part-packet" packet? */
4812 p += xsnprintf (p, endp - p, "vCont");
4814 if (ptid_equal (ptid, magic_null_ptid))
4816 /* MAGIC_NULL_PTID means that we don't have any active threads,
4817 so we don't have any TID numbers the inferior will
4818 understand. Make sure to only send forms that do not specify
4820 append_resumption (p, endp, minus_one_ptid, step, siggnal);
4822 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
4824 /* Resume all threads (of all processes, or of a single
4825 process), with preference for INFERIOR_PTID. This assumes
4826 inferior_ptid belongs to the set of all threads we are about
4828 if (step || siggnal != GDB_SIGNAL_0)
4830 /* Step inferior_ptid, with or without signal. */
4831 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
4834 /* Also pass down any pending signaled resumption for other
4835 threads not the current. */
4836 p = append_pending_thread_resumptions (p, endp, ptid);
4838 /* And continue others without a signal. */
4839 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
4843 /* Scheduler locking; resume only PTID. */
4844 append_resumption (p, endp, ptid, step, siggnal);
4847 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
4852 /* In non-stop, the stub replies to vCont with "OK". The stop
4853 reply will be reported asynchronously by means of a `%Stop'
4855 getpkt (&rs->buf, &rs->buf_size, 0);
4856 if (strcmp (rs->buf, "OK") != 0)
4857 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
4863 /* Tell the remote machine to resume. */
4866 remote_resume (struct target_ops *ops,
4867 ptid_t ptid, int step, enum gdb_signal siggnal)
4869 struct remote_state *rs = get_remote_state ();
4872 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
4873 (explained in remote-notif.c:handle_notification) so
4874 remote_notif_process is not called. We need find a place where
4875 it is safe to start a 'vNotif' sequence. It is good to do it
4876 before resuming inferior, because inferior was stopped and no RSP
4877 traffic at that moment. */
4879 remote_notif_process (rs->notif_state, ¬if_client_stop);
4881 rs->last_sent_signal = siggnal;
4882 rs->last_sent_step = step;
4884 /* The vCont packet doesn't need to specify threads via Hc. */
4885 /* No reverse support (yet) for vCont. */
4886 if (execution_direction != EXEC_REVERSE)
4887 if (remote_vcont_resume (ptid, step, siggnal))
4890 /* All other supported resume packets do use Hc, so set the continue
4892 if (ptid_equal (ptid, minus_one_ptid))
4893 set_continue_thread (any_thread_ptid);
4895 set_continue_thread (ptid);
4898 if (execution_direction == EXEC_REVERSE)
4900 /* We don't pass signals to the target in reverse exec mode. */
4901 if (info_verbose && siggnal != GDB_SIGNAL_0)
4902 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
4905 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
4906 error (_("Remote reverse-step not supported."));
4907 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
4908 error (_("Remote reverse-continue not supported."));
4910 strcpy (buf, step ? "bs" : "bc");
4912 else if (siggnal != GDB_SIGNAL_0)
4914 buf[0] = step ? 'S' : 'C';
4915 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
4916 buf[2] = tohex (((int) siggnal) & 0xf);
4920 strcpy (buf, step ? "s" : "c");
4925 /* We are about to start executing the inferior, let's register it
4926 with the event loop. NOTE: this is the one place where all the
4927 execution commands end up. We could alternatively do this in each
4928 of the execution commands in infcmd.c. */
4929 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
4930 into infcmd.c in order to allow inferior function calls to work
4931 NOT asynchronously. */
4932 if (target_can_async_p ())
4933 target_async (inferior_event_handler, 0);
4935 /* We've just told the target to resume. The remote server will
4936 wait for the inferior to stop, and then send a stop reply. In
4937 the mean time, we can't start another command/query ourselves
4938 because the stub wouldn't be ready to process it. This applies
4939 only to the base all-stop protocol, however. In non-stop (which
4940 only supports vCont), the stub replies with an "OK", and is
4941 immediate able to process further serial input. */
4943 rs->waiting_for_stop_reply = 1;
4947 /* Set up the signal handler for SIGINT, while the target is
4948 executing, ovewriting the 'regular' SIGINT signal handler. */
4950 async_initialize_sigint_signal_handler (void)
4952 signal (SIGINT, async_handle_remote_sigint);
4955 /* Signal handler for SIGINT, while the target is executing. */
4957 async_handle_remote_sigint (int sig)
4959 signal (sig, async_handle_remote_sigint_twice);
4960 /* Note we need to go through gdb_call_async_signal_handler in order
4961 to wake up the event loop on Windows. */
4962 gdb_call_async_signal_handler (async_sigint_remote_token, 0);
4965 /* Signal handler for SIGINT, installed after SIGINT has already been
4966 sent once. It will take effect the second time that the user sends
4969 async_handle_remote_sigint_twice (int sig)
4971 signal (sig, async_handle_remote_sigint);
4972 /* See note in async_handle_remote_sigint. */
4973 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 0);
4976 /* Perform the real interruption of the target execution, in response
4979 async_remote_interrupt (gdb_client_data arg)
4982 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt called\n");
4984 target_stop (inferior_ptid);
4987 /* Perform interrupt, if the first attempt did not succeed. Just give
4988 up on the target alltogether. */
4990 async_remote_interrupt_twice (gdb_client_data arg)
4993 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt_twice called\n");
4998 /* Reinstall the usual SIGINT handlers, after the target has
5001 async_cleanup_sigint_signal_handler (void *dummy)
5003 signal (SIGINT, handle_sigint);
5006 /* Send ^C to target to halt it. Target will respond, and send us a
5008 static void (*ofunc) (int);
5010 /* The command line interface's stop routine. This function is installed
5011 as a signal handler for SIGINT. The first time a user requests a
5012 stop, we call remote_stop to send a break or ^C. If there is no
5013 response from the target (it didn't stop when the user requested it),
5014 we ask the user if he'd like to detach from the target. */
5016 sync_remote_interrupt (int signo)
5018 /* If this doesn't work, try more severe steps. */
5019 signal (signo, sync_remote_interrupt_twice);
5021 gdb_call_async_signal_handler (async_sigint_remote_token, 1);
5024 /* The user typed ^C twice. */
5027 sync_remote_interrupt_twice (int signo)
5029 signal (signo, ofunc);
5030 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 1);
5031 signal (signo, sync_remote_interrupt);
5034 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
5035 thread, all threads of a remote process, or all threads of all
5039 remote_stop_ns (ptid_t ptid)
5041 struct remote_state *rs = get_remote_state ();
5043 char *endp = rs->buf + get_remote_packet_size ();
5045 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
5046 remote_vcont_probe (rs);
5048 if (!rs->supports_vCont.t)
5049 error (_("Remote server does not support stopping threads"));
5051 if (ptid_equal (ptid, minus_one_ptid)
5052 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5053 p += xsnprintf (p, endp - p, "vCont;t");
5058 p += xsnprintf (p, endp - p, "vCont;t:");
5060 if (ptid_is_pid (ptid))
5061 /* All (-1) threads of process. */
5062 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
5065 /* Small optimization: if we already have a stop reply for
5066 this thread, no use in telling the stub we want this
5068 if (peek_stop_reply (ptid))
5074 write_ptid (p, endp, nptid);
5077 /* In non-stop, we get an immediate OK reply. The stop reply will
5078 come in asynchronously by notification. */
5080 getpkt (&rs->buf, &rs->buf_size, 0);
5081 if (strcmp (rs->buf, "OK") != 0)
5082 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
5085 /* All-stop version of target_stop. Sends a break or a ^C to stop the
5086 remote target. It is undefined which thread of which process
5087 reports the stop. */
5090 remote_stop_as (ptid_t ptid)
5092 struct remote_state *rs = get_remote_state ();
5094 rs->ctrlc_pending_p = 1;
5096 /* If the inferior is stopped already, but the core didn't know
5097 about it yet, just ignore the request. The cached wait status
5098 will be collected in remote_wait. */
5099 if (rs->cached_wait_status)
5102 /* Send interrupt_sequence to remote target. */
5103 send_interrupt_sequence ();
5106 /* This is the generic stop called via the target vector. When a target
5107 interrupt is requested, either by the command line or the GUI, we
5108 will eventually end up here. */
5111 remote_stop (struct target_ops *self, ptid_t ptid)
5114 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
5117 remote_stop_ns (ptid);
5119 remote_stop_as (ptid);
5122 /* Ask the user what to do when an interrupt is received. */
5125 interrupt_query (void)
5127 target_terminal_ours ();
5129 if (target_is_async_p ())
5131 signal (SIGINT, handle_sigint);
5136 if (query (_("Interrupted while waiting for the program.\n\
5137 Give up (and stop debugging it)? ")))
5139 remote_unpush_target ();
5144 target_terminal_inferior ();
5147 /* Enable/disable target terminal ownership. Most targets can use
5148 terminal groups to control terminal ownership. Remote targets are
5149 different in that explicit transfer of ownership to/from GDB/target
5153 remote_terminal_inferior (struct target_ops *self)
5155 if (!target_async_permitted)
5156 /* Nothing to do. */
5159 /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
5160 idempotent. The event-loop GDB talking to an asynchronous target
5161 with a synchronous command calls this function from both
5162 event-top.c and infrun.c/infcmd.c. Once GDB stops trying to
5163 transfer the terminal to the target when it shouldn't this guard
5165 if (!remote_async_terminal_ours_p)
5167 delete_file_handler (input_fd);
5168 remote_async_terminal_ours_p = 0;
5169 async_initialize_sigint_signal_handler ();
5170 /* NOTE: At this point we could also register our selves as the
5171 recipient of all input. Any characters typed could then be
5172 passed on down to the target. */
5176 remote_terminal_ours (struct target_ops *self)
5178 if (!target_async_permitted)
5179 /* Nothing to do. */
5182 /* See FIXME in remote_terminal_inferior. */
5183 if (remote_async_terminal_ours_p)
5185 async_cleanup_sigint_signal_handler (NULL);
5186 add_file_handler (input_fd, stdin_event_handler, 0);
5187 remote_async_terminal_ours_p = 1;
5191 remote_console_output (char *msg)
5195 for (p = msg; p[0] && p[1]; p += 2)
5198 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
5202 fputs_unfiltered (tb, gdb_stdtarg);
5204 gdb_flush (gdb_stdtarg);
5207 typedef struct cached_reg
5210 gdb_byte data[MAX_REGISTER_SIZE];
5213 DEF_VEC_O(cached_reg_t);
5215 typedef struct stop_reply
5217 struct notif_event base;
5219 /* The identifier of the thread about this event */
5222 /* The remote state this event is associated with. When the remote
5223 connection, represented by a remote_state object, is closed,
5224 all the associated stop_reply events should be released. */
5225 struct remote_state *rs;
5227 struct target_waitstatus ws;
5229 /* Expedited registers. This makes remote debugging a bit more
5230 efficient for those targets that provide critical registers as
5231 part of their normal status mechanism (as another roundtrip to
5232 fetch them is avoided). */
5233 VEC(cached_reg_t) *regcache;
5235 enum target_stop_reason stop_reason;
5237 CORE_ADDR watch_data_address;
5242 DECLARE_QUEUE_P (stop_reply_p);
5243 DEFINE_QUEUE_P (stop_reply_p);
5244 /* The list of already fetched and acknowledged stop events. This
5245 queue is used for notification Stop, and other notifications
5246 don't need queue for their events, because the notification events
5247 of Stop can't be consumed immediately, so that events should be
5248 queued first, and be consumed by remote_wait_{ns,as} one per
5249 time. Other notifications can consume their events immediately,
5250 so queue is not needed for them. */
5251 static QUEUE (stop_reply_p) *stop_reply_queue;
5254 stop_reply_xfree (struct stop_reply *r)
5256 notif_event_xfree ((struct notif_event *) r);
5260 remote_notif_stop_parse (struct notif_client *self, char *buf,
5261 struct notif_event *event)
5263 remote_parse_stop_reply (buf, (struct stop_reply *) event);
5267 remote_notif_stop_ack (struct notif_client *self, char *buf,
5268 struct notif_event *event)
5270 struct stop_reply *stop_reply = (struct stop_reply *) event;
5273 putpkt ((char *) self->ack_command);
5275 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
5276 /* We got an unknown stop reply. */
5277 error (_("Unknown stop reply"));
5279 push_stop_reply (stop_reply);
5283 remote_notif_stop_can_get_pending_events (struct notif_client *self)
5285 /* We can't get pending events in remote_notif_process for
5286 notification stop, and we have to do this in remote_wait_ns
5287 instead. If we fetch all queued events from stub, remote stub
5288 may exit and we have no chance to process them back in
5290 mark_async_event_handler (remote_async_inferior_event_token);
5295 stop_reply_dtr (struct notif_event *event)
5297 struct stop_reply *r = (struct stop_reply *) event;
5299 VEC_free (cached_reg_t, r->regcache);
5302 static struct notif_event *
5303 remote_notif_stop_alloc_reply (void)
5305 struct notif_event *r
5306 = (struct notif_event *) XNEW (struct stop_reply);
5308 r->dtr = stop_reply_dtr;
5313 /* A client of notification Stop. */
5315 struct notif_client notif_client_stop =
5319 remote_notif_stop_parse,
5320 remote_notif_stop_ack,
5321 remote_notif_stop_can_get_pending_events,
5322 remote_notif_stop_alloc_reply,
5326 /* A parameter to pass data in and out. */
5328 struct queue_iter_param
5331 struct stop_reply *output;
5334 /* Remove stop replies in the queue if its pid is equal to the given
5338 remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
5339 QUEUE_ITER (stop_reply_p) *iter,
5343 struct queue_iter_param *param = data;
5344 struct inferior *inf = param->input;
5346 if (ptid_get_pid (event->ptid) == inf->pid)
5348 stop_reply_xfree (event);
5349 QUEUE_remove_elem (stop_reply_p, q, iter);
5355 /* Discard all pending stop replies of inferior INF. */
5358 discard_pending_stop_replies (struct inferior *inf)
5361 struct queue_iter_param param;
5362 struct stop_reply *reply;
5363 struct remote_state *rs = get_remote_state ();
5364 struct remote_notif_state *rns = rs->notif_state;
5366 /* This function can be notified when an inferior exists. When the
5367 target is not remote, the notification state is NULL. */
5368 if (rs->remote_desc == NULL)
5371 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
5373 /* Discard the in-flight notification. */
5374 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
5376 stop_reply_xfree (reply);
5377 rns->pending_event[notif_client_stop.id] = NULL;
5381 param.output = NULL;
5382 /* Discard the stop replies we have already pulled with
5384 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5385 remove_stop_reply_for_inferior, ¶m);
5388 /* If its remote state is equal to the given remote state,
5389 remove EVENT from the stop reply queue. */
5392 remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
5393 QUEUE_ITER (stop_reply_p) *iter,
5397 struct queue_iter_param *param = data;
5398 struct remote_state *rs = param->input;
5400 if (event->rs == rs)
5402 stop_reply_xfree (event);
5403 QUEUE_remove_elem (stop_reply_p, q, iter);
5409 /* Discard the stop replies for RS in stop_reply_queue. */
5412 discard_pending_stop_replies_in_queue (struct remote_state *rs)
5414 struct queue_iter_param param;
5417 param.output = NULL;
5418 /* Discard the stop replies we have already pulled with
5420 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5421 remove_stop_reply_of_remote_state, ¶m);
5424 /* A parameter to pass data in and out. */
5427 remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
5428 QUEUE_ITER (stop_reply_p) *iter,
5432 struct queue_iter_param *param = data;
5433 ptid_t *ptid = param->input;
5435 if (ptid_match (event->ptid, *ptid))
5437 param->output = event;
5438 QUEUE_remove_elem (stop_reply_p, q, iter);
5445 /* Remove the first reply in 'stop_reply_queue' which matches
5448 static struct stop_reply *
5449 remote_notif_remove_queued_reply (ptid_t ptid)
5451 struct queue_iter_param param;
5453 param.input = &ptid;
5454 param.output = NULL;
5456 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5457 remote_notif_remove_once_on_match, ¶m);
5459 fprintf_unfiltered (gdb_stdlog,
5460 "notif: discard queued event: 'Stop' in %s\n",
5461 target_pid_to_str (ptid));
5463 return param.output;
5466 /* Look for a queued stop reply belonging to PTID. If one is found,
5467 remove it from the queue, and return it. Returns NULL if none is
5468 found. If there are still queued events left to process, tell the
5469 event loop to get back to target_wait soon. */
5471 static struct stop_reply *
5472 queued_stop_reply (ptid_t ptid)
5474 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
5476 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
5477 /* There's still at least an event left. */
5478 mark_async_event_handler (remote_async_inferior_event_token);
5483 /* Push a fully parsed stop reply in the stop reply queue. Since we
5484 know that we now have at least one queued event left to pass to the
5485 core side, tell the event loop to get back to target_wait soon. */
5488 push_stop_reply (struct stop_reply *new_event)
5490 QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
5493 fprintf_unfiltered (gdb_stdlog,
5494 "notif: push 'Stop' %s to queue %d\n",
5495 target_pid_to_str (new_event->ptid),
5496 QUEUE_length (stop_reply_p,
5499 mark_async_event_handler (remote_async_inferior_event_token);
5503 stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
5504 QUEUE_ITER (stop_reply_p) *iter,
5505 struct stop_reply *event,
5508 ptid_t *ptid = data;
5510 return !(ptid_equal (*ptid, event->ptid)
5511 && event->ws.kind == TARGET_WAITKIND_STOPPED);
5514 /* Returns true if we have a stop reply for PTID. */
5517 peek_stop_reply (ptid_t ptid)
5519 return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
5520 stop_reply_match_ptid_and_ws, &ptid);
5523 /* Skip PACKET until the next semi-colon (or end of string). */
5526 skip_to_semicolon (char *p)
5528 while (*p != '\0' && *p != ';')
5533 /* Parse the stop reply in BUF. Either the function succeeds, and the
5534 result is stored in EVENT, or throws an error. */
5537 remote_parse_stop_reply (char *buf, struct stop_reply *event)
5539 struct remote_arch_state *rsa = get_remote_arch_state ();
5543 event->ptid = null_ptid;
5544 event->rs = get_remote_state ();
5545 event->ws.kind = TARGET_WAITKIND_IGNORE;
5546 event->ws.value.integer = 0;
5547 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
5548 event->regcache = NULL;
5553 case 'T': /* Status with PC, SP, FP, ... */
5554 /* Expedited reply, containing Signal, {regno, reg} repeat. */
5555 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
5557 n... = register number
5558 r... = register contents
5561 p = &buf[3]; /* after Txx */
5567 p1 = strchr (p, ':');
5569 error (_("Malformed packet(a) (missing colon): %s\n\
5573 error (_("Malformed packet(a) (missing register number): %s\n\
5577 /* Some "registers" are actually extended stop information.
5578 Note if you're adding a new entry here: GDB 7.9 and
5579 earlier assume that all register "numbers" that start
5580 with an hex digit are real register numbers. Make sure
5581 the server only sends such a packet if it knows the
5582 client understands it. */
5584 if (strncmp (p, "thread", p1 - p) == 0)
5585 event->ptid = read_ptid (++p1, &p);
5586 else if ((strncmp (p, "watch", p1 - p) == 0)
5587 || (strncmp (p, "rwatch", p1 - p) == 0)
5588 || (strncmp (p, "awatch", p1 - p) == 0))
5590 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
5591 p = unpack_varlen_hex (++p1, &addr);
5592 event->watch_data_address = (CORE_ADDR) addr;
5594 else if (strncmp (p, "swbreak", p1 - p) == 0)
5596 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
5598 /* Make sure the stub doesn't forget to indicate support
5600 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
5601 error (_("Unexpected swbreak stop reason"));
5603 /* The value part is documented as "must be empty",
5604 though we ignore it, in case we ever decide to make
5605 use of it in a backward compatible way. */
5606 p = skip_to_semicolon (p1 + 1);
5608 else if (strncmp (p, "hwbreak", p1 - p) == 0)
5610 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
5612 /* Make sure the stub doesn't forget to indicate support
5614 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
5615 error (_("Unexpected hwbreak stop reason"));
5618 p = skip_to_semicolon (p1 + 1);
5620 else if (strncmp (p, "library", p1 - p) == 0)
5622 event->ws.kind = TARGET_WAITKIND_LOADED;
5623 p = skip_to_semicolon (p1 + 1);
5625 else if (strncmp (p, "replaylog", p1 - p) == 0)
5627 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
5628 /* p1 will indicate "begin" or "end", but it makes
5629 no difference for now, so ignore it. */
5630 p = skip_to_semicolon (p1 + 1);
5632 else if (strncmp (p, "core", p1 - p) == 0)
5636 p = unpack_varlen_hex (++p1, &c);
5644 /* Maybe a real ``P'' register number. */
5645 p_temp = unpack_varlen_hex (p, &pnum);
5646 /* If the first invalid character is the colon, we got a
5647 register number. Otherwise, it's an unknown stop
5651 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
5652 cached_reg_t cached_reg;
5655 error (_("Remote sent bad register number %s: %s\n\
5657 hex_string (pnum), p, buf);
5659 cached_reg.num = reg->regnum;
5662 fieldsize = hex2bin (p, cached_reg.data,
5663 register_size (target_gdbarch (),
5666 if (fieldsize < register_size (target_gdbarch (),
5668 warning (_("Remote reply is too short: %s"), buf);
5670 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
5674 /* Not a number. Silently skip unknown optional
5676 p = skip_to_semicolon (p1 + 1);
5681 error (_("Remote register badly formatted: %s\nhere: %s"),
5686 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
5690 case 'S': /* Old style status, just signal only. */
5694 event->ws.kind = TARGET_WAITKIND_STOPPED;
5695 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
5696 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
5697 event->ws.value.sig = (enum gdb_signal) sig;
5699 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
5702 case 'W': /* Target exited. */
5709 /* GDB used to accept only 2 hex chars here. Stubs should
5710 only send more if they detect GDB supports multi-process
5712 p = unpack_varlen_hex (&buf[1], &value);
5716 /* The remote process exited. */
5717 event->ws.kind = TARGET_WAITKIND_EXITED;
5718 event->ws.value.integer = value;
5722 /* The remote process exited with a signal. */
5723 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
5724 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
5725 event->ws.value.sig = (enum gdb_signal) value;
5727 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
5730 /* If no process is specified, assume inferior_ptid. */
5731 pid = ptid_get_pid (inferior_ptid);
5740 else if (startswith (p, "process:"))
5744 p += sizeof ("process:") - 1;
5745 unpack_varlen_hex (p, &upid);
5749 error (_("unknown stop reply packet: %s"), buf);
5752 error (_("unknown stop reply packet: %s"), buf);
5753 event->ptid = pid_to_ptid (pid);
5758 if (non_stop && ptid_equal (event->ptid, null_ptid))
5759 error (_("No process or thread specified in stop reply: %s"), buf);
5762 /* When the stub wants to tell GDB about a new notification reply, it
5763 sends a notification (%Stop, for example). Those can come it at
5764 any time, hence, we have to make sure that any pending
5765 putpkt/getpkt sequence we're making is finished, before querying
5766 the stub for more events with the corresponding ack command
5767 (vStopped, for example). E.g., if we started a vStopped sequence
5768 immediately upon receiving the notification, something like this
5776 1.6) <-- (registers reply to step #1.3)
5778 Obviously, the reply in step #1.6 would be unexpected to a vStopped
5781 To solve this, whenever we parse a %Stop notification successfully,
5782 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
5783 doing whatever we were doing:
5789 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
5790 2.5) <-- (registers reply to step #2.3)
5792 Eventualy after step #2.5, we return to the event loop, which
5793 notices there's an event on the
5794 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
5795 associated callback --- the function below. At this point, we're
5796 always safe to start a vStopped sequence. :
5799 2.7) <-- T05 thread:2
5805 remote_notif_get_pending_events (struct notif_client *nc)
5807 struct remote_state *rs = get_remote_state ();
5809 if (rs->notif_state->pending_event[nc->id] != NULL)
5812 fprintf_unfiltered (gdb_stdlog,
5813 "notif: process: '%s' ack pending event\n",
5817 nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
5818 rs->notif_state->pending_event[nc->id] = NULL;
5822 getpkt (&rs->buf, &rs->buf_size, 0);
5823 if (strcmp (rs->buf, "OK") == 0)
5826 remote_notif_ack (nc, rs->buf);
5832 fprintf_unfiltered (gdb_stdlog,
5833 "notif: process: '%s' no pending reply\n",
5838 /* Called when it is decided that STOP_REPLY holds the info of the
5839 event that is to be returned to the core. This function always
5840 destroys STOP_REPLY. */
5843 process_stop_reply (struct stop_reply *stop_reply,
5844 struct target_waitstatus *status)
5848 *status = stop_reply->ws;
5849 ptid = stop_reply->ptid;
5851 /* If no thread/process was reported by the stub, assume the current
5853 if (ptid_equal (ptid, null_ptid))
5854 ptid = inferior_ptid;
5856 if (status->kind != TARGET_WAITKIND_EXITED
5857 && status->kind != TARGET_WAITKIND_SIGNALLED)
5859 struct remote_state *rs = get_remote_state ();
5861 /* Expedited registers. */
5862 if (stop_reply->regcache)
5864 struct regcache *regcache
5865 = get_thread_arch_regcache (ptid, target_gdbarch ());
5870 VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
5872 regcache_raw_supply (regcache, reg->num, reg->data);
5873 VEC_free (cached_reg_t, stop_reply->regcache);
5876 rs->stop_reason = stop_reply->stop_reason;
5877 rs->remote_watch_data_address = stop_reply->watch_data_address;
5879 remote_notice_new_inferior (ptid, 0);
5880 demand_private_info (ptid)->core = stop_reply->core;
5883 stop_reply_xfree (stop_reply);
5887 /* The non-stop mode version of target_wait. */
5890 remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
5892 struct remote_state *rs = get_remote_state ();
5893 struct stop_reply *stop_reply;
5897 /* If in non-stop mode, get out of getpkt even if a
5898 notification is received. */
5900 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
5901 0 /* forever */, &is_notif);
5904 if (ret != -1 && !is_notif)
5907 case 'E': /* Error of some sort. */
5908 /* We're out of sync with the target now. Did it continue
5909 or not? We can't tell which thread it was in non-stop,
5910 so just ignore this. */
5911 warning (_("Remote failure reply: %s"), rs->buf);
5913 case 'O': /* Console output. */
5914 remote_console_output (rs->buf + 1);
5917 warning (_("Invalid remote reply: %s"), rs->buf);
5921 /* Acknowledge a pending stop reply that may have arrived in the
5923 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
5924 remote_notif_get_pending_events (¬if_client_stop);
5926 /* If indeed we noticed a stop reply, we're done. */
5927 stop_reply = queued_stop_reply (ptid);
5928 if (stop_reply != NULL)
5929 return process_stop_reply (stop_reply, status);
5931 /* Still no event. If we're just polling for an event, then
5932 return to the event loop. */
5933 if (options & TARGET_WNOHANG)
5935 status->kind = TARGET_WAITKIND_IGNORE;
5936 return minus_one_ptid;
5939 /* Otherwise do a blocking wait. */
5940 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
5941 1 /* forever */, &is_notif);
5945 /* Wait until the remote machine stops, then return, storing status in
5946 STATUS just as `wait' would. */
5949 remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
5951 struct remote_state *rs = get_remote_state ();
5952 ptid_t event_ptid = null_ptid;
5954 struct stop_reply *stop_reply;
5958 status->kind = TARGET_WAITKIND_IGNORE;
5959 status->value.integer = 0;
5961 stop_reply = queued_stop_reply (ptid);
5962 if (stop_reply != NULL)
5963 return process_stop_reply (stop_reply, status);
5965 if (rs->cached_wait_status)
5966 /* Use the cached wait status, but only once. */
5967 rs->cached_wait_status = 0;
5973 if (!target_is_async_p ())
5975 ofunc = signal (SIGINT, sync_remote_interrupt);
5976 /* If the user hit C-c before this packet, or between packets,
5977 pretend that it was hit right here. */
5978 if (check_quit_flag ())
5981 sync_remote_interrupt (SIGINT);
5985 /* FIXME: cagney/1999-09-27: If we're in async mode we should
5986 _never_ wait for ever -> test on target_is_async_p().
5987 However, before we do that we need to ensure that the caller
5988 knows how to take the target into/out of async mode. */
5989 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
5990 wait_forever_enabled_p, &is_notif);
5992 if (!target_is_async_p ())
5993 signal (SIGINT, ofunc);
5995 /* GDB gets a notification. Return to core as this event is
5997 if (ret != -1 && is_notif)
5998 return minus_one_ptid;
6003 rs->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6005 /* We got something. */
6006 rs->waiting_for_stop_reply = 0;
6008 /* Assume that the target has acknowledged Ctrl-C unless we receive
6009 an 'F' or 'O' packet. */
6010 if (buf[0] != 'F' && buf[0] != 'O')
6011 rs->ctrlc_pending_p = 0;
6015 case 'E': /* Error of some sort. */
6016 /* We're out of sync with the target now. Did it continue or
6017 not? Not is more likely, so report a stop. */
6018 warning (_("Remote failure reply: %s"), buf);
6019 status->kind = TARGET_WAITKIND_STOPPED;
6020 status->value.sig = GDB_SIGNAL_0;
6022 case 'F': /* File-I/O request. */
6023 remote_fileio_request (buf, rs->ctrlc_pending_p);
6024 rs->ctrlc_pending_p = 0;
6026 case 'T': case 'S': case 'X': case 'W':
6028 struct stop_reply *stop_reply
6029 = (struct stop_reply *) remote_notif_parse (¬if_client_stop,
6032 event_ptid = process_stop_reply (stop_reply, status);
6035 case 'O': /* Console output. */
6036 remote_console_output (buf + 1);
6038 /* The target didn't really stop; keep waiting. */
6039 rs->waiting_for_stop_reply = 1;
6043 if (rs->last_sent_signal != GDB_SIGNAL_0)
6045 /* Zero length reply means that we tried 'S' or 'C' and the
6046 remote system doesn't support it. */
6047 target_terminal_ours_for_output ();
6049 ("Can't send signals to this remote system. %s not sent.\n",
6050 gdb_signal_to_name (rs->last_sent_signal));
6051 rs->last_sent_signal = GDB_SIGNAL_0;
6052 target_terminal_inferior ();
6054 strcpy ((char *) buf, rs->last_sent_step ? "s" : "c");
6055 putpkt ((char *) buf);
6057 /* We just told the target to resume, so a stop reply is in
6059 rs->waiting_for_stop_reply = 1;
6062 /* else fallthrough */
6064 warning (_("Invalid remote reply: %s"), buf);
6066 rs->waiting_for_stop_reply = 1;
6070 if (status->kind == TARGET_WAITKIND_IGNORE)
6072 /* Nothing interesting happened. If we're doing a non-blocking
6073 poll, we're done. Otherwise, go back to waiting. */
6074 if (options & TARGET_WNOHANG)
6075 return minus_one_ptid;
6079 else if (status->kind != TARGET_WAITKIND_EXITED
6080 && status->kind != TARGET_WAITKIND_SIGNALLED)
6082 if (!ptid_equal (event_ptid, null_ptid))
6083 record_currthread (rs, event_ptid);
6085 event_ptid = inferior_ptid;
6088 /* A process exit. Invalidate our notion of current thread. */
6089 record_currthread (rs, minus_one_ptid);
6094 /* Wait until the remote machine stops, then return, storing status in
6095 STATUS just as `wait' would. */
6098 remote_wait (struct target_ops *ops,
6099 ptid_t ptid, struct target_waitstatus *status, int options)
6104 event_ptid = remote_wait_ns (ptid, status, options);
6106 event_ptid = remote_wait_as (ptid, status, options);
6108 if (target_is_async_p ())
6110 /* If there are are events left in the queue tell the event loop
6112 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
6113 mark_async_event_handler (remote_async_inferior_event_token);
6119 /* Fetch a single register using a 'p' packet. */
6122 fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
6124 struct remote_state *rs = get_remote_state ();
6126 char regp[MAX_REGISTER_SIZE];
6129 if (packet_support (PACKET_p) == PACKET_DISABLE)
6132 if (reg->pnum == -1)
6137 p += hexnumstr (p, reg->pnum);
6140 getpkt (&rs->buf, &rs->buf_size, 0);
6144 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
6148 case PACKET_UNKNOWN:
6151 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
6152 gdbarch_register_name (get_regcache_arch (regcache),
6157 /* If this register is unfetchable, tell the regcache. */
6160 regcache_raw_supply (regcache, reg->regnum, NULL);
6164 /* Otherwise, parse and supply the value. */
6170 error (_("fetch_register_using_p: early buf termination"));
6172 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
6175 regcache_raw_supply (regcache, reg->regnum, regp);
6179 /* Fetch the registers included in the target's 'g' packet. */
6182 send_g_packet (void)
6184 struct remote_state *rs = get_remote_state ();
6187 xsnprintf (rs->buf, get_remote_packet_size (), "g");
6188 remote_send (&rs->buf, &rs->buf_size);
6190 /* We can get out of synch in various cases. If the first character
6191 in the buffer is not a hex character, assume that has happened
6192 and try to fetch another packet to read. */
6193 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
6194 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
6195 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
6196 && rs->buf[0] != 'x') /* New: unavailable register value. */
6199 fprintf_unfiltered (gdb_stdlog,
6200 "Bad register packet; fetching a new packet\n");
6201 getpkt (&rs->buf, &rs->buf_size, 0);
6204 buf_len = strlen (rs->buf);
6206 /* Sanity check the received packet. */
6207 if (buf_len % 2 != 0)
6208 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
6214 process_g_packet (struct regcache *regcache)
6216 struct gdbarch *gdbarch = get_regcache_arch (regcache);
6217 struct remote_state *rs = get_remote_state ();
6218 struct remote_arch_state *rsa = get_remote_arch_state ();
6223 buf_len = strlen (rs->buf);
6225 /* Further sanity checks, with knowledge of the architecture. */
6226 if (buf_len > 2 * rsa->sizeof_g_packet)
6227 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
6229 /* Save the size of the packet sent to us by the target. It is used
6230 as a heuristic when determining the max size of packets that the
6231 target can safely receive. */
6232 if (rsa->actual_register_packet_size == 0)
6233 rsa->actual_register_packet_size = buf_len;
6235 /* If this is smaller than we guessed the 'g' packet would be,
6236 update our records. A 'g' reply that doesn't include a register's
6237 value implies either that the register is not available, or that
6238 the 'p' packet must be used. */
6239 if (buf_len < 2 * rsa->sizeof_g_packet)
6241 rsa->sizeof_g_packet = buf_len / 2;
6243 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
6245 if (rsa->regs[i].pnum == -1)
6248 if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
6249 rsa->regs[i].in_g_packet = 0;
6251 rsa->regs[i].in_g_packet = 1;
6255 regs = alloca (rsa->sizeof_g_packet);
6257 /* Unimplemented registers read as all bits zero. */
6258 memset (regs, 0, rsa->sizeof_g_packet);
6260 /* Reply describes registers byte by byte, each byte encoded as two
6261 hex characters. Suck them all up, then supply them to the
6262 register cacheing/storage mechanism. */
6265 for (i = 0; i < rsa->sizeof_g_packet; i++)
6267 if (p[0] == 0 || p[1] == 0)
6268 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
6269 internal_error (__FILE__, __LINE__,
6270 _("unexpected end of 'g' packet reply"));
6272 if (p[0] == 'x' && p[1] == 'x')
6273 regs[i] = 0; /* 'x' */
6275 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
6279 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
6281 struct packet_reg *r = &rsa->regs[i];
6285 if (r->offset * 2 >= strlen (rs->buf))
6286 /* This shouldn't happen - we adjusted in_g_packet above. */
6287 internal_error (__FILE__, __LINE__,
6288 _("unexpected end of 'g' packet reply"));
6289 else if (rs->buf[r->offset * 2] == 'x')
6291 gdb_assert (r->offset * 2 < strlen (rs->buf));
6292 /* The register isn't available, mark it as such (at
6293 the same time setting the value to zero). */
6294 regcache_raw_supply (regcache, r->regnum, NULL);
6297 regcache_raw_supply (regcache, r->regnum,
6304 fetch_registers_using_g (struct regcache *regcache)
6307 process_g_packet (regcache);
6310 /* Make the remote selected traceframe match GDB's selected
6314 set_remote_traceframe (void)
6317 struct remote_state *rs = get_remote_state ();
6319 if (rs->remote_traceframe_number == get_traceframe_number ())
6322 /* Avoid recursion, remote_trace_find calls us again. */
6323 rs->remote_traceframe_number = get_traceframe_number ();
6325 newnum = target_trace_find (tfind_number,
6326 get_traceframe_number (), 0, 0, NULL);
6328 /* Should not happen. If it does, all bets are off. */
6329 if (newnum != get_traceframe_number ())
6330 warning (_("could not set remote traceframe"));
6334 remote_fetch_registers (struct target_ops *ops,
6335 struct regcache *regcache, int regnum)
6337 struct remote_arch_state *rsa = get_remote_arch_state ();
6340 set_remote_traceframe ();
6341 set_general_thread (inferior_ptid);
6345 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
6347 gdb_assert (reg != NULL);
6349 /* If this register might be in the 'g' packet, try that first -
6350 we are likely to read more than one register. If this is the
6351 first 'g' packet, we might be overly optimistic about its
6352 contents, so fall back to 'p'. */
6353 if (reg->in_g_packet)
6355 fetch_registers_using_g (regcache);
6356 if (reg->in_g_packet)
6360 if (fetch_register_using_p (regcache, reg))
6363 /* This register is not available. */
6364 regcache_raw_supply (regcache, reg->regnum, NULL);
6369 fetch_registers_using_g (regcache);
6371 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6372 if (!rsa->regs[i].in_g_packet)
6373 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
6375 /* This register is not available. */
6376 regcache_raw_supply (regcache, i, NULL);
6380 /* Prepare to store registers. Since we may send them all (using a
6381 'G' request), we have to read out the ones we don't want to change
6385 remote_prepare_to_store (struct target_ops *self, struct regcache *regcache)
6387 struct remote_arch_state *rsa = get_remote_arch_state ();
6389 gdb_byte buf[MAX_REGISTER_SIZE];
6391 /* Make sure the entire registers array is valid. */
6392 switch (packet_support (PACKET_P))
6394 case PACKET_DISABLE:
6395 case PACKET_SUPPORT_UNKNOWN:
6396 /* Make sure all the necessary registers are cached. */
6397 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6398 if (rsa->regs[i].in_g_packet)
6399 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
6406 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
6407 packet was not recognized. */
6410 store_register_using_P (const struct regcache *regcache,
6411 struct packet_reg *reg)
6413 struct gdbarch *gdbarch = get_regcache_arch (regcache);
6414 struct remote_state *rs = get_remote_state ();
6415 /* Try storing a single register. */
6416 char *buf = rs->buf;
6417 gdb_byte regp[MAX_REGISTER_SIZE];
6420 if (packet_support (PACKET_P) == PACKET_DISABLE)
6423 if (reg->pnum == -1)
6426 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
6427 p = buf + strlen (buf);
6428 regcache_raw_collect (regcache, reg->regnum, regp);
6429 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
6431 getpkt (&rs->buf, &rs->buf_size, 0);
6433 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
6438 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
6439 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
6440 case PACKET_UNKNOWN:
6443 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
6447 /* Store register REGNUM, or all registers if REGNUM == -1, from the
6448 contents of the register cache buffer. FIXME: ignores errors. */
6451 store_registers_using_G (const struct regcache *regcache)
6453 struct remote_state *rs = get_remote_state ();
6454 struct remote_arch_state *rsa = get_remote_arch_state ();
6458 /* Extract all the registers in the regcache copying them into a
6463 regs = alloca (rsa->sizeof_g_packet);
6464 memset (regs, 0, rsa->sizeof_g_packet);
6465 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6467 struct packet_reg *r = &rsa->regs[i];
6470 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
6474 /* Command describes registers byte by byte,
6475 each byte encoded as two hex characters. */
6478 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
6480 bin2hex (regs, p, rsa->sizeof_g_packet);
6482 getpkt (&rs->buf, &rs->buf_size, 0);
6483 if (packet_check_result (rs->buf) == PACKET_ERROR)
6484 error (_("Could not write registers; remote failure reply '%s'"),
6488 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
6489 of the register cache buffer. FIXME: ignores errors. */
6492 remote_store_registers (struct target_ops *ops,
6493 struct regcache *regcache, int regnum)
6495 struct remote_arch_state *rsa = get_remote_arch_state ();
6498 set_remote_traceframe ();
6499 set_general_thread (inferior_ptid);
6503 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
6505 gdb_assert (reg != NULL);
6507 /* Always prefer to store registers using the 'P' packet if
6508 possible; we often change only a small number of registers.
6509 Sometimes we change a larger number; we'd need help from a
6510 higher layer to know to use 'G'. */
6511 if (store_register_using_P (regcache, reg))
6514 /* For now, don't complain if we have no way to write the
6515 register. GDB loses track of unavailable registers too
6516 easily. Some day, this may be an error. We don't have
6517 any way to read the register, either... */
6518 if (!reg->in_g_packet)
6521 store_registers_using_G (regcache);
6525 store_registers_using_G (regcache);
6527 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6528 if (!rsa->regs[i].in_g_packet)
6529 if (!store_register_using_P (regcache, &rsa->regs[i]))
6530 /* See above for why we do not issue an error here. */
6535 /* Return the number of hex digits in num. */
6538 hexnumlen (ULONGEST num)
6542 for (i = 0; num != 0; i++)
6548 /* Set BUF to the minimum number of hex digits representing NUM. */
6551 hexnumstr (char *buf, ULONGEST num)
6553 int len = hexnumlen (num);
6555 return hexnumnstr (buf, num, len);
6559 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
6562 hexnumnstr (char *buf, ULONGEST num, int width)
6568 for (i = width - 1; i >= 0; i--)
6570 buf[i] = "0123456789abcdef"[(num & 0xf)];
6577 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
6580 remote_address_masked (CORE_ADDR addr)
6582 unsigned int address_size = remote_address_size;
6584 /* If "remoteaddresssize" was not set, default to target address size. */
6586 address_size = gdbarch_addr_bit (target_gdbarch ());
6588 if (address_size > 0
6589 && address_size < (sizeof (ULONGEST) * 8))
6591 /* Only create a mask when that mask can safely be constructed
6592 in a ULONGEST variable. */
6595 mask = (mask << address_size) - 1;
6601 /* Determine whether the remote target supports binary downloading.
6602 This is accomplished by sending a no-op memory write of zero length
6603 to the target at the specified address. It does not suffice to send
6604 the whole packet, since many stubs strip the eighth bit and
6605 subsequently compute a wrong checksum, which causes real havoc with
6608 NOTE: This can still lose if the serial line is not eight-bit
6609 clean. In cases like this, the user should clear "remote
6613 check_binary_download (CORE_ADDR addr)
6615 struct remote_state *rs = get_remote_state ();
6617 switch (packet_support (PACKET_X))
6619 case PACKET_DISABLE:
6623 case PACKET_SUPPORT_UNKNOWN:
6629 p += hexnumstr (p, (ULONGEST) addr);
6631 p += hexnumstr (p, (ULONGEST) 0);
6635 putpkt_binary (rs->buf, (int) (p - rs->buf));
6636 getpkt (&rs->buf, &rs->buf_size, 0);
6638 if (rs->buf[0] == '\0')
6641 fprintf_unfiltered (gdb_stdlog,
6642 "binary downloading NOT "
6643 "supported by target\n");
6644 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
6649 fprintf_unfiltered (gdb_stdlog,
6650 "binary downloading supported by target\n");
6651 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
6658 /* Write memory data directly to the remote machine.
6659 This does not inform the data cache; the data cache uses this.
6660 HEADER is the starting part of the packet.
6661 MEMADDR is the address in the remote memory space.
6662 MYADDR is the address of the buffer in our space.
6663 LEN is the number of bytes.
6664 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
6665 should send data as binary ('X'), or hex-encoded ('M').
6667 The function creates packet of the form
6668 <HEADER><ADDRESS>,<LENGTH>:<DATA>
6670 where encoding of <DATA> is termined by PACKET_FORMAT.
6672 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
6675 Return the transferred status, error or OK (an
6676 'enum target_xfer_status' value). Save the number of bytes
6677 transferred in *XFERED_LEN. Only transfer a single packet. */
6679 static enum target_xfer_status
6680 remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
6681 const gdb_byte *myaddr, ULONGEST len,
6682 ULONGEST *xfered_len, char packet_format,
6685 struct remote_state *rs = get_remote_state ();
6695 if (packet_format != 'X' && packet_format != 'M')
6696 internal_error (__FILE__, __LINE__,
6697 _("remote_write_bytes_aux: bad packet format"));
6700 return TARGET_XFER_EOF;
6702 payload_size = get_memory_write_packet_size ();
6704 /* The packet buffer will be large enough for the payload;
6705 get_memory_packet_size ensures this. */
6708 /* Compute the size of the actual payload by subtracting out the
6709 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
6711 payload_size -= strlen ("$,:#NN");
6713 /* The comma won't be used. */
6715 header_length = strlen (header);
6716 payload_size -= header_length;
6717 payload_size -= hexnumlen (memaddr);
6719 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
6721 strcat (rs->buf, header);
6722 p = rs->buf + strlen (header);
6724 /* Compute a best guess of the number of bytes actually transfered. */
6725 if (packet_format == 'X')
6727 /* Best guess at number of bytes that will fit. */
6728 todo = min (len, payload_size);
6730 payload_size -= hexnumlen (todo);
6731 todo = min (todo, payload_size);
6735 /* Num bytes that will fit. */
6736 todo = min (len, payload_size / 2);
6738 payload_size -= hexnumlen (todo);
6739 todo = min (todo, payload_size / 2);
6743 internal_error (__FILE__, __LINE__,
6744 _("minimum packet size too small to write data"));
6746 /* If we already need another packet, then try to align the end
6747 of this packet to a useful boundary. */
6748 if (todo > 2 * REMOTE_ALIGN_WRITES && todo < len)
6749 todo = ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
6751 /* Append "<memaddr>". */
6752 memaddr = remote_address_masked (memaddr);
6753 p += hexnumstr (p, (ULONGEST) memaddr);
6760 /* Append <len>. Retain the location/size of <len>. It may need to
6761 be adjusted once the packet body has been created. */
6763 plenlen = hexnumstr (p, (ULONGEST) todo);
6771 /* Append the packet body. */
6772 if (packet_format == 'X')
6774 /* Binary mode. Send target system values byte by byte, in
6775 increasing byte addresses. Only escape certain critical
6777 payload_length = remote_escape_output (myaddr, todo, (gdb_byte *) p,
6778 &nr_bytes, payload_size);
6780 /* If not all TODO bytes fit, then we'll need another packet. Make
6781 a second try to keep the end of the packet aligned. Don't do
6782 this if the packet is tiny. */
6783 if (nr_bytes < todo && nr_bytes > 2 * REMOTE_ALIGN_WRITES)
6787 new_nr_bytes = (((memaddr + nr_bytes) & ~(REMOTE_ALIGN_WRITES - 1))
6789 if (new_nr_bytes != nr_bytes)
6790 payload_length = remote_escape_output (myaddr, new_nr_bytes,
6791 (gdb_byte *) p, &nr_bytes,
6795 p += payload_length;
6796 if (use_length && nr_bytes < todo)
6798 /* Escape chars have filled up the buffer prematurely,
6799 and we have actually sent fewer bytes than planned.
6800 Fix-up the length field of the packet. Use the same
6801 number of characters as before. */
6802 plen += hexnumnstr (plen, (ULONGEST) nr_bytes, plenlen);
6803 *plen = ':'; /* overwrite \0 from hexnumnstr() */
6808 /* Normal mode: Send target system values byte by byte, in
6809 increasing byte addresses. Each byte is encoded as a two hex
6811 nr_bytes = bin2hex (myaddr, p, todo);
6815 putpkt_binary (rs->buf, (int) (p - rs->buf));
6816 getpkt (&rs->buf, &rs->buf_size, 0);
6818 if (rs->buf[0] == 'E')
6819 return TARGET_XFER_E_IO;
6821 /* Return NR_BYTES, not TODO, in case escape chars caused us to send
6822 fewer bytes than we'd planned. */
6823 *xfered_len = (ULONGEST) nr_bytes;
6824 return TARGET_XFER_OK;
6827 /* Write memory data directly to the remote machine.
6828 This does not inform the data cache; the data cache uses this.
6829 MEMADDR is the address in the remote memory space.
6830 MYADDR is the address of the buffer in our space.
6831 LEN is the number of bytes.
6833 Return the transferred status, error or OK (an
6834 'enum target_xfer_status' value). Save the number of bytes
6835 transferred in *XFERED_LEN. Only transfer a single packet. */
6837 static enum target_xfer_status
6838 remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
6839 ULONGEST *xfered_len)
6841 char *packet_format = 0;
6843 /* Check whether the target supports binary download. */
6844 check_binary_download (memaddr);
6846 switch (packet_support (PACKET_X))
6849 packet_format = "X";
6851 case PACKET_DISABLE:
6852 packet_format = "M";
6854 case PACKET_SUPPORT_UNKNOWN:
6855 internal_error (__FILE__, __LINE__,
6856 _("remote_write_bytes: bad internal state"));
6858 internal_error (__FILE__, __LINE__, _("bad switch"));
6861 return remote_write_bytes_aux (packet_format,
6862 memaddr, myaddr, len, xfered_len,
6863 packet_format[0], 1);
6866 /* Read memory data directly from the remote machine.
6867 This does not use the data cache; the data cache uses this.
6868 MEMADDR is the address in the remote memory space.
6869 MYADDR is the address of the buffer in our space.
6870 LEN is the number of bytes.
6872 Return the transferred status, error or OK (an
6873 'enum target_xfer_status' value). Save the number of bytes
6874 transferred in *XFERED_LEN. */
6876 static enum target_xfer_status
6877 remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len,
6878 ULONGEST *xfered_len)
6880 struct remote_state *rs = get_remote_state ();
6881 int max_buf_size; /* Max size of packet output buffer. */
6886 max_buf_size = get_memory_read_packet_size ();
6887 /* The packet buffer will be large enough for the payload;
6888 get_memory_packet_size ensures this. */
6890 /* Number if bytes that will fit. */
6891 todo = min (len, max_buf_size / 2);
6893 /* Construct "m"<memaddr>","<len>". */
6894 memaddr = remote_address_masked (memaddr);
6897 p += hexnumstr (p, (ULONGEST) memaddr);
6899 p += hexnumstr (p, (ULONGEST) todo);
6902 getpkt (&rs->buf, &rs->buf_size, 0);
6903 if (rs->buf[0] == 'E'
6904 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
6905 && rs->buf[3] == '\0')
6906 return TARGET_XFER_E_IO;
6907 /* Reply describes memory byte by byte, each byte encoded as two hex
6910 i = hex2bin (p, myaddr, todo);
6911 /* Return what we have. Let higher layers handle partial reads. */
6912 *xfered_len = (ULONGEST) i;
6913 return TARGET_XFER_OK;
6916 /* Using the set of read-only target sections of remote, read live
6919 For interface/parameters/return description see target.h,
6922 static enum target_xfer_status
6923 remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
6924 ULONGEST memaddr, ULONGEST len,
6925 ULONGEST *xfered_len)
6927 struct target_section *secp;
6928 struct target_section_table *table;
6930 secp = target_section_by_addr (ops, memaddr);
6932 && (bfd_get_section_flags (secp->the_bfd_section->owner,
6933 secp->the_bfd_section)
6936 struct target_section *p;
6937 ULONGEST memend = memaddr + len;
6939 table = target_get_section_table (ops);
6941 for (p = table->sections; p < table->sections_end; p++)
6943 if (memaddr >= p->addr)
6945 if (memend <= p->endaddr)
6947 /* Entire transfer is within this section. */
6948 return remote_read_bytes_1 (memaddr, readbuf, len,
6951 else if (memaddr >= p->endaddr)
6953 /* This section ends before the transfer starts. */
6958 /* This section overlaps the transfer. Just do half. */
6959 len = p->endaddr - memaddr;
6960 return remote_read_bytes_1 (memaddr, readbuf, len,
6967 return TARGET_XFER_EOF;
6970 /* Similar to remote_read_bytes_1, but it reads from the remote stub
6971 first if the requested memory is unavailable in traceframe.
6972 Otherwise, fall back to remote_read_bytes_1. */
6974 static enum target_xfer_status
6975 remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
6976 gdb_byte *myaddr, ULONGEST len, ULONGEST *xfered_len)
6979 return TARGET_XFER_EOF;
6981 if (get_traceframe_number () != -1)
6983 VEC(mem_range_s) *available;
6985 /* If we fail to get the set of available memory, then the
6986 target does not support querying traceframe info, and so we
6987 attempt reading from the traceframe anyway (assuming the
6988 target implements the old QTro packet then). */
6989 if (traceframe_available_memory (&available, memaddr, len))
6991 struct cleanup *old_chain;
6993 old_chain = make_cleanup (VEC_cleanup(mem_range_s), &available);
6995 if (VEC_empty (mem_range_s, available)
6996 || VEC_index (mem_range_s, available, 0)->start != memaddr)
6998 enum target_xfer_status res;
7000 /* Don't read into the traceframe's available
7002 if (!VEC_empty (mem_range_s, available))
7004 LONGEST oldlen = len;
7006 len = VEC_index (mem_range_s, available, 0)->start - memaddr;
7007 gdb_assert (len <= oldlen);
7010 do_cleanups (old_chain);
7012 /* This goes through the topmost target again. */
7013 res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
7015 if (res == TARGET_XFER_OK)
7016 return TARGET_XFER_OK;
7019 /* No use trying further, we know some memory starting
7020 at MEMADDR isn't available. */
7022 return TARGET_XFER_UNAVAILABLE;
7026 /* Don't try to read more than how much is available, in
7027 case the target implements the deprecated QTro packet to
7028 cater for older GDBs (the target's knowledge of read-only
7029 sections may be outdated by now). */
7030 len = VEC_index (mem_range_s, available, 0)->length;
7032 do_cleanups (old_chain);
7036 return remote_read_bytes_1 (memaddr, myaddr, len, xfered_len);
7041 /* Sends a packet with content determined by the printf format string
7042 FORMAT and the remaining arguments, then gets the reply. Returns
7043 whether the packet was a success, a failure, or unknown. */
7045 static enum packet_result remote_send_printf (const char *format, ...)
7046 ATTRIBUTE_PRINTF (1, 2);
7048 static enum packet_result
7049 remote_send_printf (const char *format, ...)
7051 struct remote_state *rs = get_remote_state ();
7052 int max_size = get_remote_packet_size ();
7055 va_start (ap, format);
7058 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
7059 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
7061 if (putpkt (rs->buf) < 0)
7062 error (_("Communication problem with target."));
7065 getpkt (&rs->buf, &rs->buf_size, 0);
7067 return packet_check_result (rs->buf);
7071 restore_remote_timeout (void *p)
7073 int value = *(int *)p;
7075 remote_timeout = value;
7078 /* Flash writing can take quite some time. We'll set
7079 effectively infinite timeout for flash operations.
7080 In future, we'll need to decide on a better approach. */
7081 static const int remote_flash_timeout = 1000;
7084 remote_flash_erase (struct target_ops *ops,
7085 ULONGEST address, LONGEST length)
7087 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
7088 int saved_remote_timeout = remote_timeout;
7089 enum packet_result ret;
7090 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7091 &saved_remote_timeout);
7093 remote_timeout = remote_flash_timeout;
7095 ret = remote_send_printf ("vFlashErase:%s,%s",
7096 phex (address, addr_size),
7100 case PACKET_UNKNOWN:
7101 error (_("Remote target does not support flash erase"));
7103 error (_("Error erasing flash with vFlashErase packet"));
7108 do_cleanups (back_to);
7111 static enum target_xfer_status
7112 remote_flash_write (struct target_ops *ops, ULONGEST address,
7113 ULONGEST length, ULONGEST *xfered_len,
7114 const gdb_byte *data)
7116 int saved_remote_timeout = remote_timeout;
7117 enum target_xfer_status ret;
7118 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7119 &saved_remote_timeout);
7121 remote_timeout = remote_flash_timeout;
7122 ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length,
7124 do_cleanups (back_to);
7130 remote_flash_done (struct target_ops *ops)
7132 int saved_remote_timeout = remote_timeout;
7134 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7135 &saved_remote_timeout);
7137 remote_timeout = remote_flash_timeout;
7138 ret = remote_send_printf ("vFlashDone");
7139 do_cleanups (back_to);
7143 case PACKET_UNKNOWN:
7144 error (_("Remote target does not support vFlashDone"));
7146 error (_("Error finishing flash operation"));
7153 remote_files_info (struct target_ops *ignore)
7155 puts_filtered ("Debugging a target over a serial line.\n");
7158 /* Stuff for dealing with the packets which are part of this protocol.
7159 See comment at top of file for details. */
7161 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
7162 error to higher layers. Called when a serial error is detected.
7163 The exception message is STRING, followed by a colon and a blank,
7164 the system error message for errno at function entry and final dot
7165 for output compatibility with throw_perror_with_name. */
7168 unpush_and_perror (const char *string)
7170 int saved_errno = errno;
7172 remote_unpush_target ();
7173 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
7174 safe_strerror (saved_errno));
7177 /* Read a single character from the remote end. */
7180 readchar (int timeout)
7183 struct remote_state *rs = get_remote_state ();
7185 ch = serial_readchar (rs->remote_desc, timeout);
7190 switch ((enum serial_rc) ch)
7193 remote_unpush_target ();
7194 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
7197 unpush_and_perror (_("Remote communication error. "
7198 "Target disconnected."));
7200 case SERIAL_TIMEOUT:
7206 /* Wrapper for serial_write that closes the target and throws if
7210 remote_serial_write (const char *str, int len)
7212 struct remote_state *rs = get_remote_state ();
7214 if (serial_write (rs->remote_desc, str, len))
7216 unpush_and_perror (_("Remote communication error. "
7217 "Target disconnected."));
7221 /* Send the command in *BUF to the remote machine, and read the reply
7222 into *BUF. Report an error if we get an error reply. Resize
7223 *BUF using xrealloc if necessary to hold the result, and update
7227 remote_send (char **buf,
7231 getpkt (buf, sizeof_buf, 0);
7233 if ((*buf)[0] == 'E')
7234 error (_("Remote failure reply: %s"), *buf);
7237 /* Return a pointer to an xmalloc'ed string representing an escaped
7238 version of BUF, of len N. E.g. \n is converted to \\n, \t to \\t,
7239 etc. The caller is responsible for releasing the returned
7243 escape_buffer (const char *buf, int n)
7245 struct cleanup *old_chain;
7246 struct ui_file *stb;
7249 stb = mem_fileopen ();
7250 old_chain = make_cleanup_ui_file_delete (stb);
7252 fputstrn_unfiltered (buf, n, '\\', stb);
7253 str = ui_file_xstrdup (stb, NULL);
7254 do_cleanups (old_chain);
7258 /* Display a null-terminated packet on stdout, for debugging, using C
7262 print_packet (const char *buf)
7264 puts_filtered ("\"");
7265 fputstr_filtered (buf, '"', gdb_stdout);
7266 puts_filtered ("\"");
7270 putpkt (const char *buf)
7272 return putpkt_binary (buf, strlen (buf));
7275 /* Send a packet to the remote machine, with error checking. The data
7276 of the packet is in BUF. The string in BUF can be at most
7277 get_remote_packet_size () - 5 to account for the $, # and checksum,
7278 and for a possible /0 if we are debugging (remote_debug) and want
7279 to print the sent packet as a string. */
7282 putpkt_binary (const char *buf, int cnt)
7284 struct remote_state *rs = get_remote_state ();
7286 unsigned char csum = 0;
7287 char *buf2 = alloca (cnt + 6);
7294 /* Catch cases like trying to read memory or listing threads while
7295 we're waiting for a stop reply. The remote server wouldn't be
7296 ready to handle this request, so we'd hang and timeout. We don't
7297 have to worry about this in synchronous mode, because in that
7298 case it's not possible to issue a command while the target is
7299 running. This is not a problem in non-stop mode, because in that
7300 case, the stub is always ready to process serial input. */
7301 if (!non_stop && target_is_async_p () && rs->waiting_for_stop_reply)
7303 error (_("Cannot execute this command while the target is running.\n"
7304 "Use the \"interrupt\" command to stop the target\n"
7305 "and then try again."));
7308 /* We're sending out a new packet. Make sure we don't look at a
7309 stale cached response. */
7310 rs->cached_wait_status = 0;
7312 /* Copy the packet into buffer BUF2, encapsulating it
7313 and giving it a checksum. */
7318 for (i = 0; i < cnt; i++)
7324 *p++ = tohex ((csum >> 4) & 0xf);
7325 *p++ = tohex (csum & 0xf);
7327 /* Send it over and over until we get a positive ack. */
7331 int started_error_output = 0;
7335 struct cleanup *old_chain;
7339 str = escape_buffer (buf2, p - buf2);
7340 old_chain = make_cleanup (xfree, str);
7341 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
7342 gdb_flush (gdb_stdlog);
7343 do_cleanups (old_chain);
7345 remote_serial_write (buf2, p - buf2);
7347 /* If this is a no acks version of the remote protocol, send the
7348 packet and move on. */
7352 /* Read until either a timeout occurs (-2) or '+' is read.
7353 Handle any notification that arrives in the mean time. */
7356 ch = readchar (remote_timeout);
7364 case SERIAL_TIMEOUT:
7367 if (started_error_output)
7369 putchar_unfiltered ('\n');
7370 started_error_output = 0;
7379 fprintf_unfiltered (gdb_stdlog, "Ack\n");
7383 fprintf_unfiltered (gdb_stdlog, "Nak\n");
7385 case SERIAL_TIMEOUT:
7389 break; /* Retransmit buffer. */
7393 fprintf_unfiltered (gdb_stdlog,
7394 "Packet instead of Ack, ignoring it\n");
7395 /* It's probably an old response sent because an ACK
7396 was lost. Gobble up the packet and ack it so it
7397 doesn't get retransmitted when we resend this
7400 remote_serial_write ("+", 1);
7401 continue; /* Now, go look for +. */
7408 /* If we got a notification, handle it, and go back to looking
7410 /* We've found the start of a notification. Now
7411 collect the data. */
7412 val = read_frame (&rs->buf, &rs->buf_size);
7417 struct cleanup *old_chain;
7420 str = escape_buffer (rs->buf, val);
7421 old_chain = make_cleanup (xfree, str);
7422 fprintf_unfiltered (gdb_stdlog,
7423 " Notification received: %s\n",
7425 do_cleanups (old_chain);
7427 handle_notification (rs->notif_state, rs->buf);
7428 /* We're in sync now, rewait for the ack. */
7435 if (!started_error_output)
7437 started_error_output = 1;
7438 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
7440 fputc_unfiltered (ch & 0177, gdb_stdlog);
7441 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
7450 if (!started_error_output)
7452 started_error_output = 1;
7453 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
7455 fputc_unfiltered (ch & 0177, gdb_stdlog);
7459 break; /* Here to retransmit. */
7463 /* This is wrong. If doing a long backtrace, the user should be
7464 able to get out next time we call QUIT, without anything as
7465 violent as interrupt_query. If we want to provide a way out of
7466 here without getting to the next QUIT, it should be based on
7467 hitting ^C twice as in remote_wait. */
7478 /* Come here after finding the start of a frame when we expected an
7479 ack. Do our best to discard the rest of this packet. */
7488 c = readchar (remote_timeout);
7491 case SERIAL_TIMEOUT:
7492 /* Nothing we can do. */
7495 /* Discard the two bytes of checksum and stop. */
7496 c = readchar (remote_timeout);
7498 c = readchar (remote_timeout);
7501 case '*': /* Run length encoding. */
7502 /* Discard the repeat count. */
7503 c = readchar (remote_timeout);
7508 /* A regular character. */
7514 /* Come here after finding the start of the frame. Collect the rest
7515 into *BUF, verifying the checksum, length, and handling run-length
7516 compression. NUL terminate the buffer. If there is not enough room,
7517 expand *BUF using xrealloc.
7519 Returns -1 on error, number of characters in buffer (ignoring the
7520 trailing NULL) on success. (could be extended to return one of the
7521 SERIAL status indications). */
7524 read_frame (char **buf_p,
7531 struct remote_state *rs = get_remote_state ();
7538 c = readchar (remote_timeout);
7541 case SERIAL_TIMEOUT:
7543 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
7547 fputs_filtered ("Saw new packet start in middle of old one\n",
7549 return -1; /* Start a new packet, count retries. */
7552 unsigned char pktcsum;
7558 check_0 = readchar (remote_timeout);
7560 check_1 = readchar (remote_timeout);
7562 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
7565 fputs_filtered ("Timeout in checksum, retrying\n",
7569 else if (check_0 < 0 || check_1 < 0)
7572 fputs_filtered ("Communication error in checksum\n",
7577 /* Don't recompute the checksum; with no ack packets we
7578 don't have any way to indicate a packet retransmission
7583 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
7584 if (csum == pktcsum)
7589 struct cleanup *old_chain;
7592 str = escape_buffer (buf, bc);
7593 old_chain = make_cleanup (xfree, str);
7594 fprintf_unfiltered (gdb_stdlog,
7595 "Bad checksum, sentsum=0x%x, "
7596 "csum=0x%x, buf=%s\n",
7597 pktcsum, csum, str);
7598 do_cleanups (old_chain);
7600 /* Number of characters in buffer ignoring trailing
7604 case '*': /* Run length encoding. */
7609 c = readchar (remote_timeout);
7611 repeat = c - ' ' + 3; /* Compute repeat count. */
7613 /* The character before ``*'' is repeated. */
7615 if (repeat > 0 && repeat <= 255 && bc > 0)
7617 if (bc + repeat - 1 >= *sizeof_buf - 1)
7619 /* Make some more room in the buffer. */
7620 *sizeof_buf += repeat;
7621 *buf_p = xrealloc (*buf_p, *sizeof_buf);
7625 memset (&buf[bc], buf[bc - 1], repeat);
7631 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
7635 if (bc >= *sizeof_buf - 1)
7637 /* Make some more room in the buffer. */
7639 *buf_p = xrealloc (*buf_p, *sizeof_buf);
7650 /* Read a packet from the remote machine, with error checking, and
7651 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
7652 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
7653 rather than timing out; this is used (in synchronous mode) to wait
7654 for a target that is is executing user code to stop. */
7655 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
7656 don't have to change all the calls to getpkt to deal with the
7657 return value, because at the moment I don't know what the right
7658 thing to do it for those. */
7666 timed_out = getpkt_sane (buf, sizeof_buf, forever);
7670 /* Read a packet from the remote machine, with error checking, and
7671 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
7672 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
7673 rather than timing out; this is used (in synchronous mode) to wait
7674 for a target that is is executing user code to stop. If FOREVER ==
7675 0, this function is allowed to time out gracefully and return an
7676 indication of this to the caller. Otherwise return the number of
7677 bytes read. If EXPECTING_NOTIF, consider receiving a notification
7678 enough reason to return to the caller. *IS_NOTIF is an output
7679 boolean that indicates whether *BUF holds a notification or not
7680 (a regular packet). */
7683 getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
7684 int expecting_notif, int *is_notif)
7686 struct remote_state *rs = get_remote_state ();
7692 /* We're reading a new response. Make sure we don't look at a
7693 previously cached response. */
7694 rs->cached_wait_status = 0;
7696 strcpy (*buf, "timeout");
7699 timeout = watchdog > 0 ? watchdog : -1;
7700 else if (expecting_notif)
7701 timeout = 0; /* There should already be a char in the buffer. If
7704 timeout = remote_timeout;
7708 /* Process any number of notifications, and then return when
7712 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
7714 for (tries = 1; tries <= MAX_TRIES; tries++)
7716 /* This can loop forever if the remote side sends us
7717 characters continuously, but if it pauses, we'll get
7718 SERIAL_TIMEOUT from readchar because of timeout. Then
7719 we'll count that as a retry.
7721 Note that even when forever is set, we will only wait
7722 forever prior to the start of a packet. After that, we
7723 expect characters to arrive at a brisk pace. They should
7724 show up within remote_timeout intervals. */
7726 c = readchar (timeout);
7727 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
7729 if (c == SERIAL_TIMEOUT)
7731 if (expecting_notif)
7732 return -1; /* Don't complain, it's normal to not get
7733 anything in this case. */
7735 if (forever) /* Watchdog went off? Kill the target. */
7738 remote_unpush_target ();
7739 throw_error (TARGET_CLOSE_ERROR,
7740 _("Watchdog timeout has expired. "
7741 "Target detached."));
7744 fputs_filtered ("Timed out.\n", gdb_stdlog);
7748 /* We've found the start of a packet or notification.
7749 Now collect the data. */
7750 val = read_frame (buf, sizeof_buf);
7755 remote_serial_write ("-", 1);
7758 if (tries > MAX_TRIES)
7760 /* We have tried hard enough, and just can't receive the
7761 packet/notification. Give up. */
7762 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
7764 /* Skip the ack char if we're in no-ack mode. */
7765 if (!rs->noack_mode)
7766 remote_serial_write ("+", 1);
7770 /* If we got an ordinary packet, return that to our caller. */
7775 struct cleanup *old_chain;
7778 str = escape_buffer (*buf, val);
7779 old_chain = make_cleanup (xfree, str);
7780 fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
7781 do_cleanups (old_chain);
7784 /* Skip the ack char if we're in no-ack mode. */
7785 if (!rs->noack_mode)
7786 remote_serial_write ("+", 1);
7787 if (is_notif != NULL)
7792 /* If we got a notification, handle it, and go back to looking
7796 gdb_assert (c == '%');
7800 struct cleanup *old_chain;
7803 str = escape_buffer (*buf, val);
7804 old_chain = make_cleanup (xfree, str);
7805 fprintf_unfiltered (gdb_stdlog,
7806 " Notification received: %s\n",
7808 do_cleanups (old_chain);
7810 if (is_notif != NULL)
7813 handle_notification (rs->notif_state, *buf);
7815 /* Notifications require no acknowledgement. */
7817 if (expecting_notif)
7824 getpkt_sane (char **buf, long *sizeof_buf, int forever)
7826 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
7830 getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
7833 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
7839 remote_kill (struct target_ops *ops)
7842 /* Catch errors so the user can quit from gdb even when we
7843 aren't on speaking terms with the remote system. */
7848 CATCH (ex, RETURN_MASK_ERROR)
7850 if (ex.error == TARGET_CLOSE_ERROR)
7852 /* If we got an (EOF) error that caused the target
7853 to go away, then we're done, that's what we wanted.
7854 "k" is susceptible to cause a premature EOF, given
7855 that the remote server isn't actually required to
7856 reply to "k", and it can happen that it doesn't
7857 even get to reply ACK to the "k". */
7861 /* Otherwise, something went wrong. We didn't actually kill
7862 the target. Just propagate the exception, and let the
7863 user or higher layers decide what to do. */
7864 throw_exception (ex);
7868 /* We've killed the remote end, we get to mourn it. Since this is
7869 target remote, single-process, mourning the inferior also
7870 unpushes remote_ops. */
7871 target_mourn_inferior ();
7875 remote_vkill (int pid, struct remote_state *rs)
7877 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
7880 /* Tell the remote target to detach. */
7881 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
7883 getpkt (&rs->buf, &rs->buf_size, 0);
7885 switch (packet_ok (rs->buf,
7886 &remote_protocol_packets[PACKET_vKill]))
7892 case PACKET_UNKNOWN:
7895 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
7900 extended_remote_kill (struct target_ops *ops)
7903 int pid = ptid_get_pid (inferior_ptid);
7904 struct remote_state *rs = get_remote_state ();
7906 res = remote_vkill (pid, rs);
7907 if (res == -1 && !(rs->extended && remote_multi_process_p (rs)))
7909 /* Don't try 'k' on a multi-process aware stub -- it has no way
7910 to specify the pid. */
7914 getpkt (&rs->buf, &rs->buf_size, 0);
7915 if (rs->buf[0] != 'O' || rs->buf[0] != 'K')
7918 /* Don't wait for it to die. I'm not really sure it matters whether
7919 we do or not. For the existing stubs, kill is a noop. */
7925 error (_("Can't kill process"));
7927 target_mourn_inferior ();
7931 remote_mourn (struct target_ops *ops)
7933 remote_mourn_1 (ops);
7936 /* Worker function for remote_mourn. */
7938 remote_mourn_1 (struct target_ops *target)
7940 unpush_target (target);
7942 /* remote_close takes care of doing most of the clean up. */
7943 generic_mourn_inferior ();
7947 extended_remote_mourn_1 (struct target_ops *target)
7949 struct remote_state *rs = get_remote_state ();
7951 /* In case we got here due to an error, but we're going to stay
7953 rs->waiting_for_stop_reply = 0;
7955 /* If the current general thread belonged to the process we just
7956 detached from or has exited, the remote side current general
7957 thread becomes undefined. Considering a case like this:
7959 - We just got here due to a detach.
7960 - The process that we're detaching from happens to immediately
7961 report a global breakpoint being hit in non-stop mode, in the
7962 same thread we had selected before.
7963 - GDB attaches to this process again.
7964 - This event happens to be the next event we handle.
7966 GDB would consider that the current general thread didn't need to
7967 be set on the stub side (with Hg), since for all it knew,
7968 GENERAL_THREAD hadn't changed.
7970 Notice that although in all-stop mode, the remote server always
7971 sets the current thread to the thread reporting the stop event,
7972 that doesn't happen in non-stop mode; in non-stop, the stub *must
7973 not* change the current thread when reporting a breakpoint hit,
7974 due to the decoupling of event reporting and event handling.
7976 To keep things simple, we always invalidate our notion of the
7978 record_currthread (rs, minus_one_ptid);
7980 /* Unlike "target remote", we do not want to unpush the target; then
7981 the next time the user says "run", we won't be connected. */
7983 /* Call common code to mark the inferior as not running. */
7984 generic_mourn_inferior ();
7986 if (!have_inferiors ())
7988 if (!remote_multi_process_p (rs))
7990 /* Check whether the target is running now - some remote stubs
7991 automatically restart after kill. */
7993 getpkt (&rs->buf, &rs->buf_size, 0);
7995 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
7997 /* Assume that the target has been restarted. Set
7998 inferior_ptid so that bits of core GDB realizes
7999 there's something here, e.g., so that the user can
8000 say "kill" again. */
8001 inferior_ptid = magic_null_ptid;
8008 extended_remote_mourn (struct target_ops *ops)
8010 extended_remote_mourn_1 (ops);
8014 extended_remote_supports_disable_randomization (struct target_ops *self)
8016 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
8020 extended_remote_disable_randomization (int val)
8022 struct remote_state *rs = get_remote_state ();
8025 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
8028 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
8030 error (_("Target does not support QDisableRandomization."));
8031 if (strcmp (reply, "OK") != 0)
8032 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
8036 extended_remote_run (char *args)
8038 struct remote_state *rs = get_remote_state ();
8041 /* If the user has disabled vRun support, or we have detected that
8042 support is not available, do not try it. */
8043 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
8046 strcpy (rs->buf, "vRun;");
8047 len = strlen (rs->buf);
8049 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
8050 error (_("Remote file name too long for run packet"));
8051 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
8052 strlen (remote_exec_file));
8054 gdb_assert (args != NULL);
8057 struct cleanup *back_to;
8061 argv = gdb_buildargv (args);
8062 back_to = make_cleanup_freeargv (argv);
8063 for (i = 0; argv[i] != NULL; i++)
8065 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
8066 error (_("Argument list too long for run packet"));
8067 rs->buf[len++] = ';';
8068 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
8071 do_cleanups (back_to);
8074 rs->buf[len++] = '\0';
8077 getpkt (&rs->buf, &rs->buf_size, 0);
8079 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
8082 /* We have a wait response. All is well. */
8084 case PACKET_UNKNOWN:
8087 if (remote_exec_file[0] == '\0')
8088 error (_("Running the default executable on the remote target failed; "
8089 "try \"set remote exec-file\"?"));
8091 error (_("Running \"%s\" on the remote target failed"),
8094 gdb_assert_not_reached (_("bad switch"));
8098 /* In the extended protocol we want to be able to do things like
8099 "run" and have them basically work as expected. So we need
8100 a special create_inferior function. We support changing the
8101 executable file and the command line arguments, but not the
8105 extended_remote_create_inferior (struct target_ops *ops,
8106 char *exec_file, char *args,
8107 char **env, int from_tty)
8111 struct remote_state *rs = get_remote_state ();
8113 /* If running asynchronously, register the target file descriptor
8114 with the event loop. */
8115 if (target_can_async_p ())
8116 target_async (inferior_event_handler, 0);
8118 /* Disable address space randomization if requested (and supported). */
8119 if (extended_remote_supports_disable_randomization (ops))
8120 extended_remote_disable_randomization (disable_randomization);
8122 /* Now restart the remote server. */
8123 run_worked = extended_remote_run (args) != -1;
8126 /* vRun was not supported. Fail if we need it to do what the
8128 if (remote_exec_file[0])
8129 error (_("Remote target does not support \"set remote exec-file\""));
8131 error (_("Remote target does not support \"set args\" or run <ARGS>"));
8133 /* Fall back to "R". */
8134 extended_remote_restart ();
8137 if (!have_inferiors ())
8139 /* Clean up from the last time we ran, before we mark the target
8140 running again. This will mark breakpoints uninserted, and
8141 get_offsets may insert breakpoints. */
8142 init_thread_list ();
8143 init_wait_for_inferior ();
8146 /* vRun's success return is a stop reply. */
8147 stop_reply = run_worked ? rs->buf : NULL;
8148 add_current_inferior_and_thread (stop_reply);
8150 /* Get updated offsets, if the stub uses qOffsets. */
8155 /* Given a location's target info BP_TGT and the packet buffer BUF, output
8156 the list of conditions (in agent expression bytecode format), if any, the
8157 target needs to evaluate. The output is placed into the packet buffer
8158 started from BUF and ended at BUF_END. */
8161 remote_add_target_side_condition (struct gdbarch *gdbarch,
8162 struct bp_target_info *bp_tgt, char *buf,
8165 struct agent_expr *aexpr = NULL;
8168 char *buf_start = buf;
8170 if (VEC_empty (agent_expr_p, bp_tgt->conditions))
8173 buf += strlen (buf);
8174 xsnprintf (buf, buf_end - buf, "%s", ";");
8177 /* Send conditions to the target and free the vector. */
8179 VEC_iterate (agent_expr_p, bp_tgt->conditions, ix, aexpr);
8182 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
8183 buf += strlen (buf);
8184 for (i = 0; i < aexpr->len; ++i)
8185 buf = pack_hex_byte (buf, aexpr->buf[i]);
8192 remote_add_target_side_commands (struct gdbarch *gdbarch,
8193 struct bp_target_info *bp_tgt, char *buf)
8195 struct agent_expr *aexpr = NULL;
8198 if (VEC_empty (agent_expr_p, bp_tgt->tcommands))
8201 buf += strlen (buf);
8203 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
8204 buf += strlen (buf);
8206 /* Concatenate all the agent expressions that are commands into the
8209 VEC_iterate (agent_expr_p, bp_tgt->tcommands, ix, aexpr);
8212 sprintf (buf, "X%x,", aexpr->len);
8213 buf += strlen (buf);
8214 for (i = 0; i < aexpr->len; ++i)
8215 buf = pack_hex_byte (buf, aexpr->buf[i]);
8220 /* Insert a breakpoint. On targets that have software breakpoint
8221 support, we ask the remote target to do the work; on targets
8222 which don't, we insert a traditional memory breakpoint. */
8225 remote_insert_breakpoint (struct target_ops *ops,
8226 struct gdbarch *gdbarch,
8227 struct bp_target_info *bp_tgt)
8229 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
8230 If it succeeds, then set the support to PACKET_ENABLE. If it
8231 fails, and the user has explicitly requested the Z support then
8232 report an error, otherwise, mark it disabled and go on. */
8234 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
8236 CORE_ADDR addr = bp_tgt->reqstd_address;
8237 struct remote_state *rs;
8240 struct condition_list *cond = NULL;
8242 /* Make sure the remote is pointing at the right process, if
8244 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8245 set_general_process ();
8247 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
8249 rs = get_remote_state ();
8251 endbuf = rs->buf + get_remote_packet_size ();
8256 addr = (ULONGEST) remote_address_masked (addr);
8257 p += hexnumstr (p, addr);
8258 xsnprintf (p, endbuf - p, ",%d", bpsize);
8260 if (remote_supports_cond_breakpoints (ops))
8261 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
8263 if (remote_can_run_breakpoint_commands (ops))
8264 remote_add_target_side_commands (gdbarch, bp_tgt, p);
8267 getpkt (&rs->buf, &rs->buf_size, 0);
8269 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
8274 bp_tgt->placed_address = addr;
8275 bp_tgt->placed_size = bpsize;
8277 case PACKET_UNKNOWN:
8282 /* If this breakpoint has target-side commands but this stub doesn't
8283 support Z0 packets, throw error. */
8284 if (!VEC_empty (agent_expr_p, bp_tgt->tcommands))
8285 throw_error (NOT_SUPPORTED_ERROR, _("\
8286 Target doesn't support breakpoints that have target side commands."));
8288 return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
8292 remote_remove_breakpoint (struct target_ops *ops,
8293 struct gdbarch *gdbarch,
8294 struct bp_target_info *bp_tgt)
8296 CORE_ADDR addr = bp_tgt->placed_address;
8297 struct remote_state *rs = get_remote_state ();
8299 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
8302 char *endbuf = rs->buf + get_remote_packet_size ();
8304 /* Make sure the remote is pointing at the right process, if
8306 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8307 set_general_process ();
8313 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
8314 p += hexnumstr (p, addr);
8315 xsnprintf (p, endbuf - p, ",%d", bp_tgt->placed_size);
8318 getpkt (&rs->buf, &rs->buf_size, 0);
8320 return (rs->buf[0] == 'E');
8323 return memory_remove_breakpoint (ops, gdbarch, bp_tgt);
8327 watchpoint_to_Z_packet (int type)
8332 return Z_PACKET_WRITE_WP;
8335 return Z_PACKET_READ_WP;
8338 return Z_PACKET_ACCESS_WP;
8341 internal_error (__FILE__, __LINE__,
8342 _("hw_bp_to_z: bad watchpoint type %d"), type);
8347 remote_insert_watchpoint (struct target_ops *self,
8348 CORE_ADDR addr, int len, int type,
8349 struct expression *cond)
8351 struct remote_state *rs = get_remote_state ();
8352 char *endbuf = rs->buf + get_remote_packet_size ();
8354 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
8356 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
8359 /* Make sure the remote is pointing at the right process, if
8361 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8362 set_general_process ();
8364 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
8365 p = strchr (rs->buf, '\0');
8366 addr = remote_address_masked (addr);
8367 p += hexnumstr (p, (ULONGEST) addr);
8368 xsnprintf (p, endbuf - p, ",%x", len);
8371 getpkt (&rs->buf, &rs->buf_size, 0);
8373 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
8377 case PACKET_UNKNOWN:
8382 internal_error (__FILE__, __LINE__,
8383 _("remote_insert_watchpoint: reached end of function"));
8387 remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
8388 CORE_ADDR start, int length)
8390 CORE_ADDR diff = remote_address_masked (addr - start);
8392 return diff < length;
8397 remote_remove_watchpoint (struct target_ops *self,
8398 CORE_ADDR addr, int len, int type,
8399 struct expression *cond)
8401 struct remote_state *rs = get_remote_state ();
8402 char *endbuf = rs->buf + get_remote_packet_size ();
8404 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
8406 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
8409 /* Make sure the remote is pointing at the right process, if
8411 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8412 set_general_process ();
8414 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
8415 p = strchr (rs->buf, '\0');
8416 addr = remote_address_masked (addr);
8417 p += hexnumstr (p, (ULONGEST) addr);
8418 xsnprintf (p, endbuf - p, ",%x", len);
8420 getpkt (&rs->buf, &rs->buf_size, 0);
8422 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
8425 case PACKET_UNKNOWN:
8430 internal_error (__FILE__, __LINE__,
8431 _("remote_remove_watchpoint: reached end of function"));
8435 int remote_hw_watchpoint_limit = -1;
8436 int remote_hw_watchpoint_length_limit = -1;
8437 int remote_hw_breakpoint_limit = -1;
8440 remote_region_ok_for_hw_watchpoint (struct target_ops *self,
8441 CORE_ADDR addr, int len)
8443 if (remote_hw_watchpoint_length_limit == 0)
8445 else if (remote_hw_watchpoint_length_limit < 0)
8447 else if (len <= remote_hw_watchpoint_length_limit)
8454 remote_check_watch_resources (struct target_ops *self,
8455 int type, int cnt, int ot)
8457 if (type == bp_hardware_breakpoint)
8459 if (remote_hw_breakpoint_limit == 0)
8461 else if (remote_hw_breakpoint_limit < 0)
8463 else if (cnt <= remote_hw_breakpoint_limit)
8468 if (remote_hw_watchpoint_limit == 0)
8470 else if (remote_hw_watchpoint_limit < 0)
8474 else if (cnt <= remote_hw_watchpoint_limit)
8480 /* The to_stopped_by_sw_breakpoint method of target remote. */
8483 remote_stopped_by_sw_breakpoint (struct target_ops *ops)
8485 struct remote_state *rs = get_remote_state ();
8487 return rs->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT;
8490 /* The to_supports_stopped_by_sw_breakpoint method of target
8494 remote_supports_stopped_by_sw_breakpoint (struct target_ops *ops)
8496 struct remote_state *rs = get_remote_state ();
8498 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
8501 /* The to_stopped_by_hw_breakpoint method of target remote. */
8504 remote_stopped_by_hw_breakpoint (struct target_ops *ops)
8506 struct remote_state *rs = get_remote_state ();
8508 return rs->stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT;
8511 /* The to_supports_stopped_by_hw_breakpoint method of target
8515 remote_supports_stopped_by_hw_breakpoint (struct target_ops *ops)
8517 struct remote_state *rs = get_remote_state ();
8519 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
8523 remote_stopped_by_watchpoint (struct target_ops *ops)
8525 struct remote_state *rs = get_remote_state ();
8527 return rs->stop_reason == TARGET_STOPPED_BY_WATCHPOINT;
8531 remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
8533 struct remote_state *rs = get_remote_state ();
8536 if (remote_stopped_by_watchpoint (target))
8538 *addr_p = rs->remote_watch_data_address;
8547 remote_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
8548 struct bp_target_info *bp_tgt)
8550 CORE_ADDR addr = bp_tgt->reqstd_address;
8551 struct remote_state *rs;
8556 /* The length field should be set to the size of a breakpoint
8557 instruction, even though we aren't inserting one ourselves. */
8559 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
8561 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
8564 /* Make sure the remote is pointing at the right process, if
8566 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8567 set_general_process ();
8569 rs = get_remote_state ();
8571 endbuf = rs->buf + get_remote_packet_size ();
8577 addr = remote_address_masked (addr);
8578 p += hexnumstr (p, (ULONGEST) addr);
8579 xsnprintf (p, endbuf - p, ",%x", bpsize);
8581 if (remote_supports_cond_breakpoints (self))
8582 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
8584 if (remote_can_run_breakpoint_commands (self))
8585 remote_add_target_side_commands (gdbarch, bp_tgt, p);
8588 getpkt (&rs->buf, &rs->buf_size, 0);
8590 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
8593 if (rs->buf[1] == '.')
8595 message = strchr (rs->buf + 2, '.');
8597 error (_("Remote failure reply: %s"), message + 1);
8600 case PACKET_UNKNOWN:
8603 bp_tgt->placed_address = addr;
8604 bp_tgt->placed_size = bpsize;
8607 internal_error (__FILE__, __LINE__,
8608 _("remote_insert_hw_breakpoint: reached end of function"));
8613 remote_remove_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
8614 struct bp_target_info *bp_tgt)
8617 struct remote_state *rs = get_remote_state ();
8619 char *endbuf = rs->buf + get_remote_packet_size ();
8621 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
8624 /* Make sure the remote is pointing at the right process, if
8626 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8627 set_general_process ();
8633 addr = remote_address_masked (bp_tgt->placed_address);
8634 p += hexnumstr (p, (ULONGEST) addr);
8635 xsnprintf (p, endbuf - p, ",%x", bp_tgt->placed_size);
8638 getpkt (&rs->buf, &rs->buf_size, 0);
8640 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
8643 case PACKET_UNKNOWN:
8648 internal_error (__FILE__, __LINE__,
8649 _("remote_remove_hw_breakpoint: reached end of function"));
8652 /* Verify memory using the "qCRC:" request. */
8655 remote_verify_memory (struct target_ops *ops,
8656 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
8658 struct remote_state *rs = get_remote_state ();
8659 unsigned long host_crc, target_crc;
8662 /* It doesn't make sense to use qCRC if the remote target is
8663 connected but not running. */
8664 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
8666 enum packet_result result;
8668 /* Make sure the remote is pointing at the right process. */
8669 set_general_process ();
8671 /* FIXME: assumes lma can fit into long. */
8672 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
8673 (long) lma, (long) size);
8676 /* Be clever; compute the host_crc before waiting for target
8678 host_crc = xcrc32 (data, size, 0xffffffff);
8680 getpkt (&rs->buf, &rs->buf_size, 0);
8682 result = packet_ok (rs->buf,
8683 &remote_protocol_packets[PACKET_qCRC]);
8684 if (result == PACKET_ERROR)
8686 else if (result == PACKET_OK)
8688 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
8689 target_crc = target_crc * 16 + fromhex (*tmp);
8691 return (host_crc == target_crc);
8695 return simple_verify_memory (ops, data, lma, size);
8698 /* compare-sections command
8700 With no arguments, compares each loadable section in the exec bfd
8701 with the same memory range on the target, and reports mismatches.
8702 Useful for verifying the image on the target against the exec file. */
8705 compare_sections_command (char *args, int from_tty)
8708 struct cleanup *old_chain;
8710 const char *sectname;
8719 error (_("command cannot be used without an exec file"));
8721 /* Make sure the remote is pointing at the right process. */
8722 set_general_process ();
8724 if (args != NULL && strcmp (args, "-r") == 0)
8730 for (s = exec_bfd->sections; s; s = s->next)
8732 if (!(s->flags & SEC_LOAD))
8733 continue; /* Skip non-loadable section. */
8735 if (read_only && (s->flags & SEC_READONLY) == 0)
8736 continue; /* Skip writeable sections */
8738 size = bfd_get_section_size (s);
8740 continue; /* Skip zero-length section. */
8742 sectname = bfd_get_section_name (exec_bfd, s);
8743 if (args && strcmp (args, sectname) != 0)
8744 continue; /* Not the section selected by user. */
8746 matched = 1; /* Do this section. */
8749 sectdata = xmalloc (size);
8750 old_chain = make_cleanup (xfree, sectdata);
8751 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
8753 res = target_verify_memory (sectdata, lma, size);
8756 error (_("target memory fault, section %s, range %s -- %s"), sectname,
8757 paddress (target_gdbarch (), lma),
8758 paddress (target_gdbarch (), lma + size));
8760 printf_filtered ("Section %s, range %s -- %s: ", sectname,
8761 paddress (target_gdbarch (), lma),
8762 paddress (target_gdbarch (), lma + size));
8764 printf_filtered ("matched.\n");
8767 printf_filtered ("MIS-MATCHED!\n");
8771 do_cleanups (old_chain);
8774 warning (_("One or more sections of the target image does not match\n\
8775 the loaded file\n"));
8776 if (args && !matched)
8777 printf_filtered (_("No loaded section named '%s'.\n"), args);
8780 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
8781 into remote target. The number of bytes written to the remote
8782 target is returned, or -1 for error. */
8784 static enum target_xfer_status
8785 remote_write_qxfer (struct target_ops *ops, const char *object_name,
8786 const char *annex, const gdb_byte *writebuf,
8787 ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
8788 struct packet_config *packet)
8792 struct remote_state *rs = get_remote_state ();
8793 int max_size = get_memory_write_packet_size ();
8795 if (packet->support == PACKET_DISABLE)
8796 return TARGET_XFER_E_IO;
8798 /* Insert header. */
8799 i = snprintf (rs->buf, max_size,
8800 "qXfer:%s:write:%s:%s:",
8801 object_name, annex ? annex : "",
8802 phex_nz (offset, sizeof offset));
8803 max_size -= (i + 1);
8805 /* Escape as much data as fits into rs->buf. */
8806 buf_len = remote_escape_output
8807 (writebuf, len, (gdb_byte *) rs->buf + i, &max_size, max_size);
8809 if (putpkt_binary (rs->buf, i + buf_len) < 0
8810 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
8811 || packet_ok (rs->buf, packet) != PACKET_OK)
8812 return TARGET_XFER_E_IO;
8814 unpack_varlen_hex (rs->buf, &n);
8817 return TARGET_XFER_OK;
8820 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
8821 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
8822 number of bytes read is returned, or 0 for EOF, or -1 for error.
8823 The number of bytes read may be less than LEN without indicating an
8824 EOF. PACKET is checked and updated to indicate whether the remote
8825 target supports this object. */
8827 static enum target_xfer_status
8828 remote_read_qxfer (struct target_ops *ops, const char *object_name,
8830 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
8831 ULONGEST *xfered_len,
8832 struct packet_config *packet)
8834 struct remote_state *rs = get_remote_state ();
8835 LONGEST i, n, packet_len;
8837 if (packet->support == PACKET_DISABLE)
8838 return TARGET_XFER_E_IO;
8840 /* Check whether we've cached an end-of-object packet that matches
8842 if (rs->finished_object)
8844 if (strcmp (object_name, rs->finished_object) == 0
8845 && strcmp (annex ? annex : "", rs->finished_annex) == 0
8846 && offset == rs->finished_offset)
8847 return TARGET_XFER_EOF;
8850 /* Otherwise, we're now reading something different. Discard
8852 xfree (rs->finished_object);
8853 xfree (rs->finished_annex);
8854 rs->finished_object = NULL;
8855 rs->finished_annex = NULL;
8858 /* Request only enough to fit in a single packet. The actual data
8859 may not, since we don't know how much of it will need to be escaped;
8860 the target is free to respond with slightly less data. We subtract
8861 five to account for the response type and the protocol frame. */
8862 n = min (get_remote_packet_size () - 5, len);
8863 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
8864 object_name, annex ? annex : "",
8865 phex_nz (offset, sizeof offset),
8866 phex_nz (n, sizeof n));
8867 i = putpkt (rs->buf);
8869 return TARGET_XFER_E_IO;
8872 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
8873 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
8874 return TARGET_XFER_E_IO;
8876 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
8877 error (_("Unknown remote qXfer reply: %s"), rs->buf);
8879 /* 'm' means there is (or at least might be) more data after this
8880 batch. That does not make sense unless there's at least one byte
8881 of data in this reply. */
8882 if (rs->buf[0] == 'm' && packet_len == 1)
8883 error (_("Remote qXfer reply contained no data."));
8885 /* Got some data. */
8886 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
8887 packet_len - 1, readbuf, n);
8889 /* 'l' is an EOF marker, possibly including a final block of data,
8890 or possibly empty. If we have the final block of a non-empty
8891 object, record this fact to bypass a subsequent partial read. */
8892 if (rs->buf[0] == 'l' && offset + i > 0)
8894 rs->finished_object = xstrdup (object_name);
8895 rs->finished_annex = xstrdup (annex ? annex : "");
8896 rs->finished_offset = offset + i;
8900 return TARGET_XFER_EOF;
8904 return TARGET_XFER_OK;
8908 static enum target_xfer_status
8909 remote_xfer_partial (struct target_ops *ops, enum target_object object,
8910 const char *annex, gdb_byte *readbuf,
8911 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
8912 ULONGEST *xfered_len)
8914 struct remote_state *rs;
8919 set_remote_traceframe ();
8920 set_general_thread (inferior_ptid);
8922 rs = get_remote_state ();
8924 /* Handle memory using the standard memory routines. */
8925 if (object == TARGET_OBJECT_MEMORY)
8927 /* If the remote target is connected but not running, we should
8928 pass this request down to a lower stratum (e.g. the executable
8930 if (!target_has_execution)
8931 return TARGET_XFER_EOF;
8933 if (writebuf != NULL)
8934 return remote_write_bytes (offset, writebuf, len, xfered_len);
8936 return remote_read_bytes (ops, offset, readbuf, len, xfered_len);
8939 /* Handle SPU memory using qxfer packets. */
8940 if (object == TARGET_OBJECT_SPU)
8943 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
8944 xfered_len, &remote_protocol_packets
8945 [PACKET_qXfer_spu_read]);
8947 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
8948 xfered_len, &remote_protocol_packets
8949 [PACKET_qXfer_spu_write]);
8952 /* Handle extra signal info using qxfer packets. */
8953 if (object == TARGET_OBJECT_SIGNAL_INFO)
8956 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
8957 xfered_len, &remote_protocol_packets
8958 [PACKET_qXfer_siginfo_read]);
8960 return remote_write_qxfer (ops, "siginfo", annex,
8961 writebuf, offset, len, xfered_len,
8962 &remote_protocol_packets
8963 [PACKET_qXfer_siginfo_write]);
8966 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
8969 return remote_read_qxfer (ops, "statictrace", annex,
8970 readbuf, offset, len, xfered_len,
8971 &remote_protocol_packets
8972 [PACKET_qXfer_statictrace_read]);
8974 return TARGET_XFER_E_IO;
8977 /* Only handle flash writes. */
8978 if (writebuf != NULL)
8984 case TARGET_OBJECT_FLASH:
8985 return remote_flash_write (ops, offset, len, xfered_len,
8989 return TARGET_XFER_E_IO;
8993 /* Map pre-existing objects onto letters. DO NOT do this for new
8994 objects!!! Instead specify new query packets. */
8997 case TARGET_OBJECT_AVR:
9001 case TARGET_OBJECT_AUXV:
9002 gdb_assert (annex == NULL);
9003 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
9005 &remote_protocol_packets[PACKET_qXfer_auxv]);
9007 case TARGET_OBJECT_AVAILABLE_FEATURES:
9008 return remote_read_qxfer
9009 (ops, "features", annex, readbuf, offset, len, xfered_len,
9010 &remote_protocol_packets[PACKET_qXfer_features]);
9012 case TARGET_OBJECT_LIBRARIES:
9013 return remote_read_qxfer
9014 (ops, "libraries", annex, readbuf, offset, len, xfered_len,
9015 &remote_protocol_packets[PACKET_qXfer_libraries]);
9017 case TARGET_OBJECT_LIBRARIES_SVR4:
9018 return remote_read_qxfer
9019 (ops, "libraries-svr4", annex, readbuf, offset, len, xfered_len,
9020 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
9022 case TARGET_OBJECT_MEMORY_MAP:
9023 gdb_assert (annex == NULL);
9024 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
9026 &remote_protocol_packets[PACKET_qXfer_memory_map]);
9028 case TARGET_OBJECT_OSDATA:
9029 /* Should only get here if we're connected. */
9030 gdb_assert (rs->remote_desc);
9031 return remote_read_qxfer
9032 (ops, "osdata", annex, readbuf, offset, len, xfered_len,
9033 &remote_protocol_packets[PACKET_qXfer_osdata]);
9035 case TARGET_OBJECT_THREADS:
9036 gdb_assert (annex == NULL);
9037 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
9039 &remote_protocol_packets[PACKET_qXfer_threads]);
9041 case TARGET_OBJECT_TRACEFRAME_INFO:
9042 gdb_assert (annex == NULL);
9043 return remote_read_qxfer
9044 (ops, "traceframe-info", annex, readbuf, offset, len, xfered_len,
9045 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
9047 case TARGET_OBJECT_FDPIC:
9048 return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
9050 &remote_protocol_packets[PACKET_qXfer_fdpic]);
9052 case TARGET_OBJECT_OPENVMS_UIB:
9053 return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
9055 &remote_protocol_packets[PACKET_qXfer_uib]);
9057 case TARGET_OBJECT_BTRACE:
9058 return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
9060 &remote_protocol_packets[PACKET_qXfer_btrace]);
9062 case TARGET_OBJECT_BTRACE_CONF:
9063 return remote_read_qxfer (ops, "btrace-conf", annex, readbuf, offset,
9065 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
9068 return TARGET_XFER_E_IO;
9071 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
9072 large enough let the caller deal with it. */
9073 if (len < get_remote_packet_size ())
9074 return TARGET_XFER_E_IO;
9075 len = get_remote_packet_size ();
9077 /* Except for querying the minimum buffer size, target must be open. */
9078 if (!rs->remote_desc)
9079 error (_("remote query is only available after target open"));
9081 gdb_assert (annex != NULL);
9082 gdb_assert (readbuf != NULL);
9088 /* We used one buffer char for the remote protocol q command and
9089 another for the query type. As the remote protocol encapsulation
9090 uses 4 chars plus one extra in case we are debugging
9091 (remote_debug), we have PBUFZIZ - 7 left to pack the query
9094 while (annex[i] && (i < (get_remote_packet_size () - 8)))
9096 /* Bad caller may have sent forbidden characters. */
9097 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
9102 gdb_assert (annex[i] == '\0');
9104 i = putpkt (rs->buf);
9106 return TARGET_XFER_E_IO;
9108 getpkt (&rs->buf, &rs->buf_size, 0);
9109 strcpy ((char *) readbuf, rs->buf);
9111 *xfered_len = strlen ((char *) readbuf);
9112 return TARGET_XFER_OK;
9116 remote_search_memory (struct target_ops* ops,
9117 CORE_ADDR start_addr, ULONGEST search_space_len,
9118 const gdb_byte *pattern, ULONGEST pattern_len,
9119 CORE_ADDR *found_addrp)
9121 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
9122 struct remote_state *rs = get_remote_state ();
9123 int max_size = get_memory_write_packet_size ();
9124 struct packet_config *packet =
9125 &remote_protocol_packets[PACKET_qSearch_memory];
9126 /* Number of packet bytes used to encode the pattern;
9127 this could be more than PATTERN_LEN due to escape characters. */
9128 int escaped_pattern_len;
9129 /* Amount of pattern that was encodable in the packet. */
9130 int used_pattern_len;
9133 ULONGEST found_addr;
9135 /* Don't go to the target if we don't have to.
9136 This is done before checking packet->support to avoid the possibility that
9137 a success for this edge case means the facility works in general. */
9138 if (pattern_len > search_space_len)
9140 if (pattern_len == 0)
9142 *found_addrp = start_addr;
9146 /* If we already know the packet isn't supported, fall back to the simple
9147 way of searching memory. */
9149 if (packet_config_support (packet) == PACKET_DISABLE)
9151 /* Target doesn't provided special support, fall back and use the
9152 standard support (copy memory and do the search here). */
9153 return simple_search_memory (ops, start_addr, search_space_len,
9154 pattern, pattern_len, found_addrp);
9157 /* Make sure the remote is pointing at the right process. */
9158 set_general_process ();
9160 /* Insert header. */
9161 i = snprintf (rs->buf, max_size,
9162 "qSearch:memory:%s;%s;",
9163 phex_nz (start_addr, addr_size),
9164 phex_nz (search_space_len, sizeof (search_space_len)));
9165 max_size -= (i + 1);
9167 /* Escape as much data as fits into rs->buf. */
9168 escaped_pattern_len =
9169 remote_escape_output (pattern, pattern_len, (gdb_byte *) rs->buf + i,
9170 &used_pattern_len, max_size);
9172 /* Bail if the pattern is too large. */
9173 if (used_pattern_len != pattern_len)
9174 error (_("Pattern is too large to transmit to remote target."));
9176 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
9177 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9178 || packet_ok (rs->buf, packet) != PACKET_OK)
9180 /* The request may not have worked because the command is not
9181 supported. If so, fall back to the simple way. */
9182 if (packet->support == PACKET_DISABLE)
9184 return simple_search_memory (ops, start_addr, search_space_len,
9185 pattern, pattern_len, found_addrp);
9190 if (rs->buf[0] == '0')
9192 else if (rs->buf[0] == '1')
9195 if (rs->buf[1] != ',')
9196 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
9197 unpack_varlen_hex (rs->buf + 2, &found_addr);
9198 *found_addrp = found_addr;
9201 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
9207 remote_rcmd (struct target_ops *self, const char *command,
9208 struct ui_file *outbuf)
9210 struct remote_state *rs = get_remote_state ();
9213 if (!rs->remote_desc)
9214 error (_("remote rcmd is only available after target open"));
9216 /* Send a NULL command across as an empty command. */
9217 if (command == NULL)
9220 /* The query prefix. */
9221 strcpy (rs->buf, "qRcmd,");
9222 p = strchr (rs->buf, '\0');
9224 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
9225 > get_remote_packet_size ())
9226 error (_("\"monitor\" command ``%s'' is too long."), command);
9228 /* Encode the actual command. */
9229 bin2hex ((const gdb_byte *) command, p, strlen (command));
9231 if (putpkt (rs->buf) < 0)
9232 error (_("Communication problem with target."));
9234 /* get/display the response */
9239 /* XXX - see also remote_get_noisy_reply(). */
9240 QUIT; /* Allow user to bail out with ^C. */
9242 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
9244 /* Timeout. Continue to (try to) read responses.
9245 This is better than stopping with an error, assuming the stub
9246 is still executing the (long) monitor command.
9247 If needed, the user can interrupt gdb using C-c, obtaining
9248 an effect similar to stop on timeout. */
9253 error (_("Target does not support this command."));
9254 if (buf[0] == 'O' && buf[1] != 'K')
9256 remote_console_output (buf + 1); /* 'O' message from stub. */
9259 if (strcmp (buf, "OK") == 0)
9261 if (strlen (buf) == 3 && buf[0] == 'E'
9262 && isdigit (buf[1]) && isdigit (buf[2]))
9264 error (_("Protocol error with Rcmd"));
9266 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
9268 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
9270 fputc_unfiltered (c, outbuf);
9276 static VEC(mem_region_s) *
9277 remote_memory_map (struct target_ops *ops)
9279 VEC(mem_region_s) *result = NULL;
9280 char *text = target_read_stralloc (¤t_target,
9281 TARGET_OBJECT_MEMORY_MAP, NULL);
9285 struct cleanup *back_to = make_cleanup (xfree, text);
9287 result = parse_memory_map (text);
9288 do_cleanups (back_to);
9295 packet_command (char *args, int from_tty)
9297 struct remote_state *rs = get_remote_state ();
9299 if (!rs->remote_desc)
9300 error (_("command can only be used with remote target"));
9303 error (_("remote-packet command requires packet text as argument"));
9305 puts_filtered ("sending: ");
9306 print_packet (args);
9307 puts_filtered ("\n");
9310 getpkt (&rs->buf, &rs->buf_size, 0);
9311 puts_filtered ("received: ");
9312 print_packet (rs->buf);
9313 puts_filtered ("\n");
9317 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
9319 static void display_thread_info (struct gdb_ext_thread_info *info);
9321 static void threadset_test_cmd (char *cmd, int tty);
9323 static void threadalive_test (char *cmd, int tty);
9325 static void threadlist_test_cmd (char *cmd, int tty);
9327 int get_and_display_threadinfo (threadref *ref);
9329 static void threadinfo_test_cmd (char *cmd, int tty);
9331 static int thread_display_step (threadref *ref, void *context);
9333 static void threadlist_update_test_cmd (char *cmd, int tty);
9335 static void init_remote_threadtests (void);
9337 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
9340 threadset_test_cmd (char *cmd, int tty)
9342 int sample_thread = SAMPLE_THREAD;
9344 printf_filtered (_("Remote threadset test\n"));
9345 set_general_thread (sample_thread);
9350 threadalive_test (char *cmd, int tty)
9352 int sample_thread = SAMPLE_THREAD;
9353 int pid = ptid_get_pid (inferior_ptid);
9354 ptid_t ptid = ptid_build (pid, sample_thread, 0);
9356 if (remote_thread_alive (ptid))
9357 printf_filtered ("PASS: Thread alive test\n");
9359 printf_filtered ("FAIL: Thread alive test\n");
9362 void output_threadid (char *title, threadref *ref);
9365 output_threadid (char *title, threadref *ref)
9369 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
9371 printf_filtered ("%s %s\n", title, (&hexid[0]));
9375 threadlist_test_cmd (char *cmd, int tty)
9378 threadref nextthread;
9379 int done, result_count;
9380 threadref threadlist[3];
9382 printf_filtered ("Remote Threadlist test\n");
9383 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
9384 &result_count, &threadlist[0]))
9385 printf_filtered ("FAIL: threadlist test\n");
9388 threadref *scan = threadlist;
9389 threadref *limit = scan + result_count;
9391 while (scan < limit)
9392 output_threadid (" thread ", scan++);
9397 display_thread_info (struct gdb_ext_thread_info *info)
9399 output_threadid ("Threadid: ", &info->threadid);
9400 printf_filtered ("Name: %s\n ", info->shortname);
9401 printf_filtered ("State: %s\n", info->display);
9402 printf_filtered ("other: %s\n\n", info->more_display);
9406 get_and_display_threadinfo (threadref *ref)
9410 struct gdb_ext_thread_info threadinfo;
9412 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
9413 | TAG_MOREDISPLAY | TAG_DISPLAY;
9414 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
9415 display_thread_info (&threadinfo);
9420 threadinfo_test_cmd (char *cmd, int tty)
9422 int athread = SAMPLE_THREAD;
9426 int_to_threadref (&thread, athread);
9427 printf_filtered ("Remote Threadinfo test\n");
9428 if (!get_and_display_threadinfo (&thread))
9429 printf_filtered ("FAIL cannot get thread info\n");
9433 thread_display_step (threadref *ref, void *context)
9435 /* output_threadid(" threadstep ",ref); *//* simple test */
9436 return get_and_display_threadinfo (ref);
9440 threadlist_update_test_cmd (char *cmd, int tty)
9442 printf_filtered ("Remote Threadlist update test\n");
9443 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
9447 init_remote_threadtests (void)
9449 add_com ("tlist", class_obscure, threadlist_test_cmd,
9450 _("Fetch and print the remote list of "
9451 "thread identifiers, one pkt only"));
9452 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
9453 _("Fetch and display info about one thread"));
9454 add_com ("tset", class_obscure, threadset_test_cmd,
9455 _("Test setting to a different thread"));
9456 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
9457 _("Iterate through updating all remote thread info"));
9458 add_com ("talive", class_obscure, threadalive_test,
9459 _(" Remote thread alive test "));
9464 /* Convert a thread ID to a string. Returns the string in a static
9468 remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
9470 static char buf[64];
9471 struct remote_state *rs = get_remote_state ();
9473 if (ptid_equal (ptid, null_ptid))
9474 return normal_pid_to_str (ptid);
9475 else if (ptid_is_pid (ptid))
9477 /* Printing an inferior target id. */
9479 /* When multi-process extensions are off, there's no way in the
9480 remote protocol to know the remote process id, if there's any
9481 at all. There's one exception --- when we're connected with
9482 target extended-remote, and we manually attached to a process
9483 with "attach PID". We don't record anywhere a flag that
9484 allows us to distinguish that case from the case of
9485 connecting with extended-remote and the stub already being
9486 attached to a process, and reporting yes to qAttached, hence
9487 no smart special casing here. */
9488 if (!remote_multi_process_p (rs))
9490 xsnprintf (buf, sizeof buf, "Remote target");
9494 return normal_pid_to_str (ptid);
9498 if (ptid_equal (magic_null_ptid, ptid))
9499 xsnprintf (buf, sizeof buf, "Thread <main>");
9500 else if (rs->extended && remote_multi_process_p (rs))
9501 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
9502 ptid_get_pid (ptid), ptid_get_lwp (ptid));
9504 xsnprintf (buf, sizeof buf, "Thread %ld",
9505 ptid_get_lwp (ptid));
9510 /* Get the address of the thread local variable in OBJFILE which is
9511 stored at OFFSET within the thread local storage for thread PTID. */
9514 remote_get_thread_local_address (struct target_ops *ops,
9515 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
9517 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
9519 struct remote_state *rs = get_remote_state ();
9521 char *endp = rs->buf + get_remote_packet_size ();
9522 enum packet_result result;
9524 strcpy (p, "qGetTLSAddr:");
9526 p = write_ptid (p, endp, ptid);
9528 p += hexnumstr (p, offset);
9530 p += hexnumstr (p, lm);
9534 getpkt (&rs->buf, &rs->buf_size, 0);
9535 result = packet_ok (rs->buf,
9536 &remote_protocol_packets[PACKET_qGetTLSAddr]);
9537 if (result == PACKET_OK)
9541 unpack_varlen_hex (rs->buf, &result);
9544 else if (result == PACKET_UNKNOWN)
9545 throw_error (TLS_GENERIC_ERROR,
9546 _("Remote target doesn't support qGetTLSAddr packet"));
9548 throw_error (TLS_GENERIC_ERROR,
9549 _("Remote target failed to process qGetTLSAddr request"));
9552 throw_error (TLS_GENERIC_ERROR,
9553 _("TLS not supported or disabled on this target"));
9558 /* Provide thread local base, i.e. Thread Information Block address.
9559 Returns 1 if ptid is found and thread_local_base is non zero. */
9562 remote_get_tib_address (struct target_ops *self, ptid_t ptid, CORE_ADDR *addr)
9564 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
9566 struct remote_state *rs = get_remote_state ();
9568 char *endp = rs->buf + get_remote_packet_size ();
9569 enum packet_result result;
9571 strcpy (p, "qGetTIBAddr:");
9573 p = write_ptid (p, endp, ptid);
9577 getpkt (&rs->buf, &rs->buf_size, 0);
9578 result = packet_ok (rs->buf,
9579 &remote_protocol_packets[PACKET_qGetTIBAddr]);
9580 if (result == PACKET_OK)
9584 unpack_varlen_hex (rs->buf, &result);
9586 *addr = (CORE_ADDR) result;
9589 else if (result == PACKET_UNKNOWN)
9590 error (_("Remote target doesn't support qGetTIBAddr packet"));
9592 error (_("Remote target failed to process qGetTIBAddr request"));
9595 error (_("qGetTIBAddr not supported or disabled on this target"));
9600 /* Support for inferring a target description based on the current
9601 architecture and the size of a 'g' packet. While the 'g' packet
9602 can have any size (since optional registers can be left off the
9603 end), some sizes are easily recognizable given knowledge of the
9604 approximate architecture. */
9606 struct remote_g_packet_guess
9609 const struct target_desc *tdesc;
9611 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
9612 DEF_VEC_O(remote_g_packet_guess_s);
9614 struct remote_g_packet_data
9616 VEC(remote_g_packet_guess_s) *guesses;
9619 static struct gdbarch_data *remote_g_packet_data_handle;
9622 remote_g_packet_data_init (struct obstack *obstack)
9624 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
9628 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
9629 const struct target_desc *tdesc)
9631 struct remote_g_packet_data *data
9632 = gdbarch_data (gdbarch, remote_g_packet_data_handle);
9633 struct remote_g_packet_guess new_guess, *guess;
9636 gdb_assert (tdesc != NULL);
9639 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
9641 if (guess->bytes == bytes)
9642 internal_error (__FILE__, __LINE__,
9643 _("Duplicate g packet description added for size %d"),
9646 new_guess.bytes = bytes;
9647 new_guess.tdesc = tdesc;
9648 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
9651 /* Return 1 if remote_read_description would do anything on this target
9652 and architecture, 0 otherwise. */
9655 remote_read_description_p (struct target_ops *target)
9657 struct remote_g_packet_data *data
9658 = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
9660 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
9666 static const struct target_desc *
9667 remote_read_description (struct target_ops *target)
9669 struct remote_g_packet_data *data
9670 = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
9672 /* Do not try this during initial connection, when we do not know
9673 whether there is a running but stopped thread. */
9674 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
9675 return target->beneath->to_read_description (target->beneath);
9677 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
9679 struct remote_g_packet_guess *guess;
9681 int bytes = send_g_packet ();
9684 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
9686 if (guess->bytes == bytes)
9687 return guess->tdesc;
9689 /* We discard the g packet. A minor optimization would be to
9690 hold on to it, and fill the register cache once we have selected
9691 an architecture, but it's too tricky to do safely. */
9694 return target->beneath->to_read_description (target->beneath);
9697 /* Remote file transfer support. This is host-initiated I/O, not
9698 target-initiated; for target-initiated, see remote-fileio.c. */
9700 /* If *LEFT is at least the length of STRING, copy STRING to
9701 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9702 decrease *LEFT. Otherwise raise an error. */
9705 remote_buffer_add_string (char **buffer, int *left, char *string)
9707 int len = strlen (string);
9710 error (_("Packet too long for target."));
9712 memcpy (*buffer, string, len);
9716 /* NUL-terminate the buffer as a convenience, if there is
9722 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
9723 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9724 decrease *LEFT. Otherwise raise an error. */
9727 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
9730 if (2 * len > *left)
9731 error (_("Packet too long for target."));
9733 bin2hex (bytes, *buffer, len);
9737 /* NUL-terminate the buffer as a convenience, if there is
9743 /* If *LEFT is large enough, convert VALUE to hex and add it to
9744 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9745 decrease *LEFT. Otherwise raise an error. */
9748 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
9750 int len = hexnumlen (value);
9753 error (_("Packet too long for target."));
9755 hexnumstr (*buffer, value);
9759 /* NUL-terminate the buffer as a convenience, if there is
9765 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
9766 value, *REMOTE_ERRNO to the remote error number or zero if none
9767 was included, and *ATTACHMENT to point to the start of the annex
9768 if any. The length of the packet isn't needed here; there may
9769 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
9771 Return 0 if the packet could be parsed, -1 if it could not. If
9772 -1 is returned, the other variables may not be initialized. */
9775 remote_hostio_parse_result (char *buffer, int *retcode,
9776 int *remote_errno, char **attachment)
9783 if (buffer[0] != 'F')
9787 *retcode = strtol (&buffer[1], &p, 16);
9788 if (errno != 0 || p == &buffer[1])
9791 /* Check for ",errno". */
9795 *remote_errno = strtol (p + 1, &p2, 16);
9796 if (errno != 0 || p + 1 == p2)
9801 /* Check for ";attachment". If there is no attachment, the
9802 packet should end here. */
9805 *attachment = p + 1;
9808 else if (*p == '\0')
9814 /* Send a prepared I/O packet to the target and read its response.
9815 The prepared packet is in the global RS->BUF before this function
9816 is called, and the answer is there when we return.
9818 COMMAND_BYTES is the length of the request to send, which may include
9819 binary data. WHICH_PACKET is the packet configuration to check
9820 before attempting a packet. If an error occurs, *REMOTE_ERRNO
9821 is set to the error number and -1 is returned. Otherwise the value
9822 returned by the function is returned.
9824 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
9825 attachment is expected; an error will be reported if there's a
9826 mismatch. If one is found, *ATTACHMENT will be set to point into
9827 the packet buffer and *ATTACHMENT_LEN will be set to the
9828 attachment's length. */
9831 remote_hostio_send_command (int command_bytes, int which_packet,
9832 int *remote_errno, char **attachment,
9833 int *attachment_len)
9835 struct remote_state *rs = get_remote_state ();
9836 int ret, bytes_read;
9837 char *attachment_tmp;
9839 if (!rs->remote_desc
9840 || packet_support (which_packet) == PACKET_DISABLE)
9842 *remote_errno = FILEIO_ENOSYS;
9846 putpkt_binary (rs->buf, command_bytes);
9847 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
9849 /* If it timed out, something is wrong. Don't try to parse the
9853 *remote_errno = FILEIO_EINVAL;
9857 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
9860 *remote_errno = FILEIO_EINVAL;
9862 case PACKET_UNKNOWN:
9863 *remote_errno = FILEIO_ENOSYS;
9869 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
9872 *remote_errno = FILEIO_EINVAL;
9876 /* Make sure we saw an attachment if and only if we expected one. */
9877 if ((attachment_tmp == NULL && attachment != NULL)
9878 || (attachment_tmp != NULL && attachment == NULL))
9880 *remote_errno = FILEIO_EINVAL;
9884 /* If an attachment was found, it must point into the packet buffer;
9885 work out how many bytes there were. */
9886 if (attachment_tmp != NULL)
9888 *attachment = attachment_tmp;
9889 *attachment_len = bytes_read - (*attachment - rs->buf);
9895 /* Open FILENAME on the remote target, using FLAGS and MODE. Return a
9896 remote file descriptor, or -1 if an error occurs (and set
9900 remote_hostio_open (struct target_ops *self,
9901 const char *filename, int flags, int mode,
9904 struct remote_state *rs = get_remote_state ();
9906 int left = get_remote_packet_size () - 1;
9908 remote_buffer_add_string (&p, &left, "vFile:open:");
9910 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
9912 remote_buffer_add_string (&p, &left, ",");
9914 remote_buffer_add_int (&p, &left, flags);
9915 remote_buffer_add_string (&p, &left, ",");
9917 remote_buffer_add_int (&p, &left, mode);
9919 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
9920 remote_errno, NULL, NULL);
9923 /* Write up to LEN bytes from WRITE_BUF to FD on the remote target.
9924 Return the number of bytes written, or -1 if an error occurs (and
9925 set *REMOTE_ERRNO). */
9928 remote_hostio_pwrite (struct target_ops *self,
9929 int fd, const gdb_byte *write_buf, int len,
9930 ULONGEST offset, int *remote_errno)
9932 struct remote_state *rs = get_remote_state ();
9934 int left = get_remote_packet_size ();
9937 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
9939 remote_buffer_add_int (&p, &left, fd);
9940 remote_buffer_add_string (&p, &left, ",");
9942 remote_buffer_add_int (&p, &left, offset);
9943 remote_buffer_add_string (&p, &left, ",");
9945 p += remote_escape_output (write_buf, len, (gdb_byte *) p, &out_len,
9946 get_remote_packet_size () - (p - rs->buf));
9948 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
9949 remote_errno, NULL, NULL);
9952 /* Read up to LEN bytes FD on the remote target into READ_BUF
9953 Return the number of bytes read, or -1 if an error occurs (and
9954 set *REMOTE_ERRNO). */
9957 remote_hostio_pread (struct target_ops *self,
9958 int fd, gdb_byte *read_buf, int len,
9959 ULONGEST offset, int *remote_errno)
9961 struct remote_state *rs = get_remote_state ();
9964 int left = get_remote_packet_size ();
9965 int ret, attachment_len;
9968 remote_buffer_add_string (&p, &left, "vFile:pread:");
9970 remote_buffer_add_int (&p, &left, fd);
9971 remote_buffer_add_string (&p, &left, ",");
9973 remote_buffer_add_int (&p, &left, len);
9974 remote_buffer_add_string (&p, &left, ",");
9976 remote_buffer_add_int (&p, &left, offset);
9978 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
9979 remote_errno, &attachment,
9985 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
9987 if (read_len != ret)
9988 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
9993 /* Close FD on the remote target. Return 0, or -1 if an error occurs
9994 (and set *REMOTE_ERRNO). */
9997 remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
9999 struct remote_state *rs = get_remote_state ();
10001 int left = get_remote_packet_size () - 1;
10003 remote_buffer_add_string (&p, &left, "vFile:close:");
10005 remote_buffer_add_int (&p, &left, fd);
10007 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
10008 remote_errno, NULL, NULL);
10011 /* Unlink FILENAME on the remote target. Return 0, or -1 if an error
10012 occurs (and set *REMOTE_ERRNO). */
10015 remote_hostio_unlink (struct target_ops *self,
10016 const char *filename, int *remote_errno)
10018 struct remote_state *rs = get_remote_state ();
10020 int left = get_remote_packet_size () - 1;
10022 remote_buffer_add_string (&p, &left, "vFile:unlink:");
10024 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10025 strlen (filename));
10027 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
10028 remote_errno, NULL, NULL);
10031 /* Read value of symbolic link FILENAME on the remote target. Return
10032 a null-terminated string allocated via xmalloc, or NULL if an error
10033 occurs (and set *REMOTE_ERRNO). */
10036 remote_hostio_readlink (struct target_ops *self,
10037 const char *filename, int *remote_errno)
10039 struct remote_state *rs = get_remote_state ();
10042 int left = get_remote_packet_size ();
10043 int len, attachment_len;
10047 remote_buffer_add_string (&p, &left, "vFile:readlink:");
10049 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10050 strlen (filename));
10052 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
10053 remote_errno, &attachment,
10059 ret = xmalloc (len + 1);
10061 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
10062 (gdb_byte *) ret, len);
10063 if (read_len != len)
10064 error (_("Readlink returned %d, but %d bytes."), len, read_len);
10070 /* Read information about the open file FD on the remote target
10071 into ST. Return 0 on success, or -1 if an error occurs (and
10072 set *REMOTE_ERRNO). */
10075 remote_hostio_fstat (struct target_ops *self,
10076 int fd, struct stat *st,
10079 struct remote_state *rs = get_remote_state ();
10081 int left = get_remote_packet_size ();
10082 int attachment_len, ret;
10084 struct fio_stat fst;
10087 if (packet_support (PACKET_vFile_fstat) != PACKET_ENABLE)
10089 /* Strictly we should return -1, ENOSYS here, but when
10090 "set sysroot remote:" was implemented in August 2008
10091 BFD's need for a stat function was sidestepped with
10092 this hack. This was not remedied until March 2015
10093 so we retain the previous behavior to avoid breaking
10096 Note that the memset is a March 2015 addition; older
10097 GDBs set st_size *and nothing else* so the structure
10098 would have garbage in all other fields. This might
10099 break something but retaining the previous behavior
10100 here would be just too wrong. */
10102 memset (st, 0, sizeof (struct stat));
10103 st->st_size = INT_MAX;
10107 remote_buffer_add_string (&p, &left, "vFile:fstat:");
10109 remote_buffer_add_int (&p, &left, fd);
10111 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
10112 remote_errno, &attachment,
10117 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
10118 (gdb_byte *) &fst, sizeof (fst));
10120 if (read_len != ret)
10121 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
10123 if (read_len != sizeof (fst))
10124 error (_("vFile:fstat returned %d bytes, but expecting %d."),
10125 read_len, (int) sizeof (fst));
10127 remote_fileio_to_host_stat (&fst, st);
10133 remote_fileio_errno_to_host (int errnum)
10139 case FILEIO_ENOENT:
10147 case FILEIO_EACCES:
10149 case FILEIO_EFAULT:
10153 case FILEIO_EEXIST:
10155 case FILEIO_ENODEV:
10157 case FILEIO_ENOTDIR:
10159 case FILEIO_EISDIR:
10161 case FILEIO_EINVAL:
10163 case FILEIO_ENFILE:
10165 case FILEIO_EMFILE:
10169 case FILEIO_ENOSPC:
10171 case FILEIO_ESPIPE:
10175 case FILEIO_ENOSYS:
10177 case FILEIO_ENAMETOOLONG:
10178 return ENAMETOOLONG;
10184 remote_hostio_error (int errnum)
10186 int host_error = remote_fileio_errno_to_host (errnum);
10188 if (host_error == -1)
10189 error (_("Unknown remote I/O error %d"), errnum);
10191 error (_("Remote I/O error: %s"), safe_strerror (host_error));
10195 remote_hostio_close_cleanup (void *opaque)
10197 int fd = *(int *) opaque;
10200 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
10205 remote_bfd_iovec_open (struct bfd *abfd, void *open_closure)
10207 const char *filename = bfd_get_filename (abfd);
10208 int fd, remote_errno;
10211 gdb_assert (remote_filename_p (filename));
10213 fd = remote_hostio_open (find_target_at (process_stratum),
10214 filename + 7, FILEIO_O_RDONLY, 0, &remote_errno);
10217 errno = remote_fileio_errno_to_host (remote_errno);
10218 bfd_set_error (bfd_error_system_call);
10222 stream = xmalloc (sizeof (int));
10228 remote_bfd_iovec_close (struct bfd *abfd, void *stream)
10230 int fd = *(int *)stream;
10235 /* Ignore errors on close; these may happen if the remote
10236 connection was already torn down. */
10237 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
10239 /* Zero means success. */
10244 remote_bfd_iovec_pread (struct bfd *abfd, void *stream, void *buf,
10245 file_ptr nbytes, file_ptr offset)
10247 int fd = *(int *)stream;
10249 file_ptr pos, bytes;
10252 while (nbytes > pos)
10254 bytes = remote_hostio_pread (find_target_at (process_stratum),
10255 fd, (gdb_byte *) buf + pos, nbytes - pos,
10256 offset + pos, &remote_errno);
10258 /* Success, but no bytes, means end-of-file. */
10262 errno = remote_fileio_errno_to_host (remote_errno);
10263 bfd_set_error (bfd_error_system_call);
10274 remote_bfd_iovec_stat (struct bfd *abfd, void *stream, struct stat *sb)
10276 int fd = *(int *) stream;
10280 result = remote_hostio_fstat (find_target_at (process_stratum),
10281 fd, sb, &remote_errno);
10285 errno = remote_fileio_errno_to_host (remote_errno);
10286 bfd_set_error (bfd_error_system_call);
10293 remote_filename_p (const char *filename)
10295 return startswith (filename, REMOTE_SYSROOT_PREFIX);
10299 remote_bfd_open (const char *remote_file, const char *target)
10301 bfd *abfd = gdb_bfd_openr_iovec (remote_file, target,
10302 remote_bfd_iovec_open, NULL,
10303 remote_bfd_iovec_pread,
10304 remote_bfd_iovec_close,
10305 remote_bfd_iovec_stat);
10311 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
10313 struct cleanup *back_to, *close_cleanup;
10314 int retcode, fd, remote_errno, bytes, io_size;
10317 int bytes_in_buffer;
10320 struct remote_state *rs = get_remote_state ();
10322 if (!rs->remote_desc)
10323 error (_("command can only be used with remote target"));
10325 file = gdb_fopen_cloexec (local_file, "rb");
10327 perror_with_name (local_file);
10328 back_to = make_cleanup_fclose (file);
10330 fd = remote_hostio_open (find_target_at (process_stratum),
10331 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
10333 0700, &remote_errno);
10335 remote_hostio_error (remote_errno);
10337 /* Send up to this many bytes at once. They won't all fit in the
10338 remote packet limit, so we'll transfer slightly fewer. */
10339 io_size = get_remote_packet_size ();
10340 buffer = xmalloc (io_size);
10341 make_cleanup (xfree, buffer);
10343 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
10345 bytes_in_buffer = 0;
10348 while (bytes_in_buffer || !saw_eof)
10352 bytes = fread (buffer + bytes_in_buffer, 1,
10353 io_size - bytes_in_buffer,
10358 error (_("Error reading %s."), local_file);
10361 /* EOF. Unless there is something still in the
10362 buffer from the last iteration, we are done. */
10364 if (bytes_in_buffer == 0)
10372 bytes += bytes_in_buffer;
10373 bytes_in_buffer = 0;
10375 retcode = remote_hostio_pwrite (find_target_at (process_stratum),
10377 offset, &remote_errno);
10380 remote_hostio_error (remote_errno);
10381 else if (retcode == 0)
10382 error (_("Remote write of %d bytes returned 0!"), bytes);
10383 else if (retcode < bytes)
10385 /* Short write. Save the rest of the read data for the next
10387 bytes_in_buffer = bytes - retcode;
10388 memmove (buffer, buffer + retcode, bytes_in_buffer);
10394 discard_cleanups (close_cleanup);
10395 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
10396 remote_hostio_error (remote_errno);
10399 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
10400 do_cleanups (back_to);
10404 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
10406 struct cleanup *back_to, *close_cleanup;
10407 int fd, remote_errno, bytes, io_size;
10411 struct remote_state *rs = get_remote_state ();
10413 if (!rs->remote_desc)
10414 error (_("command can only be used with remote target"));
10416 fd = remote_hostio_open (find_target_at (process_stratum),
10417 remote_file, FILEIO_O_RDONLY, 0, &remote_errno);
10419 remote_hostio_error (remote_errno);
10421 file = gdb_fopen_cloexec (local_file, "wb");
10423 perror_with_name (local_file);
10424 back_to = make_cleanup_fclose (file);
10426 /* Send up to this many bytes at once. They won't all fit in the
10427 remote packet limit, so we'll transfer slightly fewer. */
10428 io_size = get_remote_packet_size ();
10429 buffer = xmalloc (io_size);
10430 make_cleanup (xfree, buffer);
10432 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
10437 bytes = remote_hostio_pread (find_target_at (process_stratum),
10438 fd, buffer, io_size, offset, &remote_errno);
10440 /* Success, but no bytes, means end-of-file. */
10443 remote_hostio_error (remote_errno);
10447 bytes = fwrite (buffer, 1, bytes, file);
10449 perror_with_name (local_file);
10452 discard_cleanups (close_cleanup);
10453 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
10454 remote_hostio_error (remote_errno);
10457 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
10458 do_cleanups (back_to);
10462 remote_file_delete (const char *remote_file, int from_tty)
10464 int retcode, remote_errno;
10465 struct remote_state *rs = get_remote_state ();
10467 if (!rs->remote_desc)
10468 error (_("command can only be used with remote target"));
10470 retcode = remote_hostio_unlink (find_target_at (process_stratum),
10471 remote_file, &remote_errno);
10473 remote_hostio_error (remote_errno);
10476 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
10480 remote_put_command (char *args, int from_tty)
10482 struct cleanup *back_to;
10486 error_no_arg (_("file to put"));
10488 argv = gdb_buildargv (args);
10489 back_to = make_cleanup_freeargv (argv);
10490 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
10491 error (_("Invalid parameters to remote put"));
10493 remote_file_put (argv[0], argv[1], from_tty);
10495 do_cleanups (back_to);
10499 remote_get_command (char *args, int from_tty)
10501 struct cleanup *back_to;
10505 error_no_arg (_("file to get"));
10507 argv = gdb_buildargv (args);
10508 back_to = make_cleanup_freeargv (argv);
10509 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
10510 error (_("Invalid parameters to remote get"));
10512 remote_file_get (argv[0], argv[1], from_tty);
10514 do_cleanups (back_to);
10518 remote_delete_command (char *args, int from_tty)
10520 struct cleanup *back_to;
10524 error_no_arg (_("file to delete"));
10526 argv = gdb_buildargv (args);
10527 back_to = make_cleanup_freeargv (argv);
10528 if (argv[0] == NULL || argv[1] != NULL)
10529 error (_("Invalid parameters to remote delete"));
10531 remote_file_delete (argv[0], from_tty);
10533 do_cleanups (back_to);
10537 remote_command (char *args, int from_tty)
10539 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
10543 remote_can_execute_reverse (struct target_ops *self)
10545 if (packet_support (PACKET_bs) == PACKET_ENABLE
10546 || packet_support (PACKET_bc) == PACKET_ENABLE)
10553 remote_supports_non_stop (struct target_ops *self)
10559 remote_supports_disable_randomization (struct target_ops *self)
10561 /* Only supported in extended mode. */
10566 remote_supports_multi_process (struct target_ops *self)
10568 struct remote_state *rs = get_remote_state ();
10570 /* Only extended-remote handles being attached to multiple
10571 processes, even though plain remote can use the multi-process
10572 thread id extensions, so that GDB knows the target process's
10574 return rs->extended && remote_multi_process_p (rs);
10578 remote_supports_cond_tracepoints (void)
10580 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
10584 remote_supports_cond_breakpoints (struct target_ops *self)
10586 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
10590 remote_supports_fast_tracepoints (void)
10592 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
10596 remote_supports_static_tracepoints (void)
10598 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
10602 remote_supports_install_in_trace (void)
10604 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
10608 remote_supports_enable_disable_tracepoint (struct target_ops *self)
10610 return (packet_support (PACKET_EnableDisableTracepoints_feature)
10615 remote_supports_string_tracing (struct target_ops *self)
10617 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
10621 remote_can_run_breakpoint_commands (struct target_ops *self)
10623 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
10627 remote_trace_init (struct target_ops *self)
10630 remote_get_noisy_reply (&target_buf, &target_buf_size);
10631 if (strcmp (target_buf, "OK") != 0)
10632 error (_("Target does not support this command."));
10635 static void free_actions_list (char **actions_list);
10636 static void free_actions_list_cleanup_wrapper (void *);
10638 free_actions_list_cleanup_wrapper (void *al)
10640 free_actions_list (al);
10644 free_actions_list (char **actions_list)
10648 if (actions_list == 0)
10651 for (ndx = 0; actions_list[ndx]; ndx++)
10652 xfree (actions_list[ndx]);
10654 xfree (actions_list);
10657 /* Recursive routine to walk through command list including loops, and
10658 download packets for each command. */
10661 remote_download_command_source (int num, ULONGEST addr,
10662 struct command_line *cmds)
10664 struct remote_state *rs = get_remote_state ();
10665 struct command_line *cmd;
10667 for (cmd = cmds; cmd; cmd = cmd->next)
10669 QUIT; /* Allow user to bail out with ^C. */
10670 strcpy (rs->buf, "QTDPsrc:");
10671 encode_source_string (num, addr, "cmd", cmd->line,
10672 rs->buf + strlen (rs->buf),
10673 rs->buf_size - strlen (rs->buf));
10675 remote_get_noisy_reply (&target_buf, &target_buf_size);
10676 if (strcmp (target_buf, "OK"))
10677 warning (_("Target does not support source download."));
10679 if (cmd->control_type == while_control
10680 || cmd->control_type == while_stepping_control)
10682 remote_download_command_source (num, addr, *cmd->body_list);
10684 QUIT; /* Allow user to bail out with ^C. */
10685 strcpy (rs->buf, "QTDPsrc:");
10686 encode_source_string (num, addr, "cmd", "end",
10687 rs->buf + strlen (rs->buf),
10688 rs->buf_size - strlen (rs->buf));
10690 remote_get_noisy_reply (&target_buf, &target_buf_size);
10691 if (strcmp (target_buf, "OK"))
10692 warning (_("Target does not support source download."));
10698 remote_download_tracepoint (struct target_ops *self, struct bp_location *loc)
10700 #define BUF_SIZE 2048
10704 char buf[BUF_SIZE];
10705 char **tdp_actions;
10706 char **stepping_actions;
10708 struct cleanup *old_chain = NULL;
10709 struct agent_expr *aexpr;
10710 struct cleanup *aexpr_chain = NULL;
10712 struct breakpoint *b = loc->owner;
10713 struct tracepoint *t = (struct tracepoint *) b;
10715 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
10716 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
10718 (void) make_cleanup (free_actions_list_cleanup_wrapper,
10721 tpaddr = loc->address;
10722 sprintf_vma (addrbuf, tpaddr);
10723 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
10724 addrbuf, /* address */
10725 (b->enable_state == bp_enabled ? 'E' : 'D'),
10726 t->step_count, t->pass_count);
10727 /* Fast tracepoints are mostly handled by the target, but we can
10728 tell the target how big of an instruction block should be moved
10730 if (b->type == bp_fast_tracepoint)
10732 /* Only test for support at download time; we may not know
10733 target capabilities at definition time. */
10734 if (remote_supports_fast_tracepoints ())
10738 if (gdbarch_fast_tracepoint_valid_at (target_gdbarch (),
10739 tpaddr, &isize, NULL))
10740 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
10743 /* If it passed validation at definition but fails now,
10744 something is very wrong. */
10745 internal_error (__FILE__, __LINE__,
10746 _("Fast tracepoint not "
10747 "valid during download"));
10750 /* Fast tracepoints are functionally identical to regular
10751 tracepoints, so don't take lack of support as a reason to
10752 give up on the trace run. */
10753 warning (_("Target does not support fast tracepoints, "
10754 "downloading %d as regular tracepoint"), b->number);
10756 else if (b->type == bp_static_tracepoint)
10758 /* Only test for support at download time; we may not know
10759 target capabilities at definition time. */
10760 if (remote_supports_static_tracepoints ())
10762 struct static_tracepoint_marker marker;
10764 if (target_static_tracepoint_marker_at (tpaddr, &marker))
10765 strcat (buf, ":S");
10767 error (_("Static tracepoint not valid during download"));
10770 /* Fast tracepoints are functionally identical to regular
10771 tracepoints, so don't take lack of support as a reason
10772 to give up on the trace run. */
10773 error (_("Target does not support static tracepoints"));
10775 /* If the tracepoint has a conditional, make it into an agent
10776 expression and append to the definition. */
10779 /* Only test support at download time, we may not know target
10780 capabilities at definition time. */
10781 if (remote_supports_cond_tracepoints ())
10783 aexpr = gen_eval_for_expr (tpaddr, loc->cond);
10784 aexpr_chain = make_cleanup_free_agent_expr (aexpr);
10785 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
10787 pkt = buf + strlen (buf);
10788 for (ndx = 0; ndx < aexpr->len; ++ndx)
10789 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
10791 do_cleanups (aexpr_chain);
10794 warning (_("Target does not support conditional tracepoints, "
10795 "ignoring tp %d cond"), b->number);
10798 if (b->commands || *default_collect)
10801 remote_get_noisy_reply (&target_buf, &target_buf_size);
10802 if (strcmp (target_buf, "OK"))
10803 error (_("Target does not support tracepoints."));
10805 /* do_single_steps (t); */
10808 for (ndx = 0; tdp_actions[ndx]; ndx++)
10810 QUIT; /* Allow user to bail out with ^C. */
10811 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
10812 b->number, addrbuf, /* address */
10814 ((tdp_actions[ndx + 1] || stepping_actions)
10817 remote_get_noisy_reply (&target_buf,
10819 if (strcmp (target_buf, "OK"))
10820 error (_("Error on target while setting tracepoints."));
10823 if (stepping_actions)
10825 for (ndx = 0; stepping_actions[ndx]; ndx++)
10827 QUIT; /* Allow user to bail out with ^C. */
10828 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
10829 b->number, addrbuf, /* address */
10830 ((ndx == 0) ? "S" : ""),
10831 stepping_actions[ndx],
10832 (stepping_actions[ndx + 1] ? "-" : ""));
10834 remote_get_noisy_reply (&target_buf,
10836 if (strcmp (target_buf, "OK"))
10837 error (_("Error on target while setting tracepoints."));
10841 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
10843 if (b->addr_string)
10845 strcpy (buf, "QTDPsrc:");
10846 encode_source_string (b->number, loc->address,
10847 "at", b->addr_string, buf + strlen (buf),
10848 2048 - strlen (buf));
10851 remote_get_noisy_reply (&target_buf, &target_buf_size);
10852 if (strcmp (target_buf, "OK"))
10853 warning (_("Target does not support source download."));
10855 if (b->cond_string)
10857 strcpy (buf, "QTDPsrc:");
10858 encode_source_string (b->number, loc->address,
10859 "cond", b->cond_string, buf + strlen (buf),
10860 2048 - strlen (buf));
10862 remote_get_noisy_reply (&target_buf, &target_buf_size);
10863 if (strcmp (target_buf, "OK"))
10864 warning (_("Target does not support source download."));
10866 remote_download_command_source (b->number, loc->address,
10867 breakpoint_commands (b));
10870 do_cleanups (old_chain);
10874 remote_can_download_tracepoint (struct target_ops *self)
10876 struct remote_state *rs = get_remote_state ();
10877 struct trace_status *ts;
10880 /* Don't try to install tracepoints until we've relocated our
10881 symbols, and fetched and merged the target's tracepoint list with
10883 if (rs->starting_up)
10886 ts = current_trace_status ();
10887 status = remote_get_trace_status (self, ts);
10889 if (status == -1 || !ts->running_known || !ts->running)
10892 /* If we are in a tracing experiment, but remote stub doesn't support
10893 installing tracepoint in trace, we have to return. */
10894 if (!remote_supports_install_in_trace ())
10902 remote_download_trace_state_variable (struct target_ops *self,
10903 struct trace_state_variable *tsv)
10905 struct remote_state *rs = get_remote_state ();
10908 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
10909 tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
10911 p = rs->buf + strlen (rs->buf);
10912 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
10913 error (_("Trace state variable name too long for tsv definition packet"));
10914 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, strlen (tsv->name));
10917 remote_get_noisy_reply (&target_buf, &target_buf_size);
10918 if (*target_buf == '\0')
10919 error (_("Target does not support this command."));
10920 if (strcmp (target_buf, "OK") != 0)
10921 error (_("Error on target while downloading trace state variable."));
10925 remote_enable_tracepoint (struct target_ops *self,
10926 struct bp_location *location)
10928 struct remote_state *rs = get_remote_state ();
10931 sprintf_vma (addr_buf, location->address);
10932 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
10933 location->owner->number, addr_buf);
10935 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
10936 if (*rs->buf == '\0')
10937 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
10938 if (strcmp (rs->buf, "OK") != 0)
10939 error (_("Error on target while enabling tracepoint."));
10943 remote_disable_tracepoint (struct target_ops *self,
10944 struct bp_location *location)
10946 struct remote_state *rs = get_remote_state ();
10949 sprintf_vma (addr_buf, location->address);
10950 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
10951 location->owner->number, addr_buf);
10953 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
10954 if (*rs->buf == '\0')
10955 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
10956 if (strcmp (rs->buf, "OK") != 0)
10957 error (_("Error on target while disabling tracepoint."));
10961 remote_trace_set_readonly_regions (struct target_ops *self)
10965 bfd_size_type size;
10971 return; /* No information to give. */
10973 strcpy (target_buf, "QTro");
10974 offset = strlen (target_buf);
10975 for (s = exec_bfd->sections; s; s = s->next)
10977 char tmp1[40], tmp2[40];
10980 if ((s->flags & SEC_LOAD) == 0 ||
10981 /* (s->flags & SEC_CODE) == 0 || */
10982 (s->flags & SEC_READONLY) == 0)
10986 vma = bfd_get_section_vma (abfd, s);
10987 size = bfd_get_section_size (s);
10988 sprintf_vma (tmp1, vma);
10989 sprintf_vma (tmp2, vma + size);
10990 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
10991 if (offset + sec_length + 1 > target_buf_size)
10993 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
10995 Too many sections for read-only sections definition packet."));
10998 xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
11000 offset += sec_length;
11004 putpkt (target_buf);
11005 getpkt (&target_buf, &target_buf_size, 0);
11010 remote_trace_start (struct target_ops *self)
11012 putpkt ("QTStart");
11013 remote_get_noisy_reply (&target_buf, &target_buf_size);
11014 if (*target_buf == '\0')
11015 error (_("Target does not support this command."));
11016 if (strcmp (target_buf, "OK") != 0)
11017 error (_("Bogus reply from target: %s"), target_buf);
11021 remote_get_trace_status (struct target_ops *self, struct trace_status *ts)
11023 /* Initialize it just to avoid a GCC false warning. */
11025 /* FIXME we need to get register block size some other way. */
11026 extern int trace_regblock_size;
11027 enum packet_result result;
11029 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
11032 trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
11034 putpkt ("qTStatus");
11038 p = remote_get_noisy_reply (&target_buf, &target_buf_size);
11040 CATCH (ex, RETURN_MASK_ERROR)
11042 if (ex.error != TARGET_CLOSE_ERROR)
11044 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
11047 throw_exception (ex);
11051 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
11053 /* If the remote target doesn't do tracing, flag it. */
11054 if (result == PACKET_UNKNOWN)
11057 /* We're working with a live target. */
11058 ts->filename = NULL;
11061 error (_("Bogus trace status reply from target: %s"), target_buf);
11063 /* Function 'parse_trace_status' sets default value of each field of
11064 'ts' at first, so we don't have to do it here. */
11065 parse_trace_status (p, ts);
11067 return ts->running;
11071 remote_get_tracepoint_status (struct target_ops *self, struct breakpoint *bp,
11072 struct uploaded_tp *utp)
11074 struct remote_state *rs = get_remote_state ();
11076 struct bp_location *loc;
11077 struct tracepoint *tp = (struct tracepoint *) bp;
11078 size_t size = get_remote_packet_size ();
11082 tp->base.hit_count = 0;
11083 tp->traceframe_usage = 0;
11084 for (loc = tp->base.loc; loc; loc = loc->next)
11086 /* If the tracepoint was never downloaded, don't go asking for
11088 if (tp->number_on_target == 0)
11090 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
11091 phex_nz (loc->address, 0));
11093 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11094 if (reply && *reply)
11097 parse_tracepoint_status (reply + 1, bp, utp);
11103 utp->hit_count = 0;
11104 utp->traceframe_usage = 0;
11105 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
11106 phex_nz (utp->addr, 0));
11108 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11109 if (reply && *reply)
11112 parse_tracepoint_status (reply + 1, bp, utp);
11118 remote_trace_stop (struct target_ops *self)
11121 remote_get_noisy_reply (&target_buf, &target_buf_size);
11122 if (*target_buf == '\0')
11123 error (_("Target does not support this command."));
11124 if (strcmp (target_buf, "OK") != 0)
11125 error (_("Bogus reply from target: %s"), target_buf);
11129 remote_trace_find (struct target_ops *self,
11130 enum trace_find_type type, int num,
11131 CORE_ADDR addr1, CORE_ADDR addr2,
11134 struct remote_state *rs = get_remote_state ();
11135 char *endbuf = rs->buf + get_remote_packet_size ();
11137 int target_frameno = -1, target_tracept = -1;
11139 /* Lookups other than by absolute frame number depend on the current
11140 trace selected, so make sure it is correct on the remote end
11142 if (type != tfind_number)
11143 set_remote_traceframe ();
11146 strcpy (p, "QTFrame:");
11147 p = strchr (p, '\0');
11151 xsnprintf (p, endbuf - p, "%x", num);
11154 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
11157 xsnprintf (p, endbuf - p, "tdp:%x", num);
11160 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
11161 phex_nz (addr2, 0));
11163 case tfind_outside:
11164 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
11165 phex_nz (addr2, 0));
11168 error (_("Unknown trace find type %d"), type);
11172 reply = remote_get_noisy_reply (&(rs->buf), &rs->buf_size);
11173 if (*reply == '\0')
11174 error (_("Target does not support this command."));
11176 while (reply && *reply)
11181 target_frameno = (int) strtol (p, &reply, 16);
11183 error (_("Unable to parse trace frame number"));
11184 /* Don't update our remote traceframe number cache on failure
11185 to select a remote traceframe. */
11186 if (target_frameno == -1)
11191 target_tracept = (int) strtol (p, &reply, 16);
11193 error (_("Unable to parse tracepoint number"));
11195 case 'O': /* "OK"? */
11196 if (reply[1] == 'K' && reply[2] == '\0')
11199 error (_("Bogus reply from target: %s"), reply);
11202 error (_("Bogus reply from target: %s"), reply);
11205 *tpp = target_tracept;
11207 rs->remote_traceframe_number = target_frameno;
11208 return target_frameno;
11212 remote_get_trace_state_variable_value (struct target_ops *self,
11213 int tsvnum, LONGEST *val)
11215 struct remote_state *rs = get_remote_state ();
11219 set_remote_traceframe ();
11221 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
11223 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11224 if (reply && *reply)
11228 unpack_varlen_hex (reply + 1, &uval);
11229 *val = (LONGEST) uval;
11237 remote_save_trace_data (struct target_ops *self, const char *filename)
11239 struct remote_state *rs = get_remote_state ();
11243 strcpy (p, "QTSave:");
11245 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
11246 error (_("Remote file name too long for trace save packet"));
11247 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
11250 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11251 if (*reply == '\0')
11252 error (_("Target does not support this command."));
11253 if (strcmp (reply, "OK") != 0)
11254 error (_("Bogus reply from target: %s"), reply);
11258 /* This is basically a memory transfer, but needs to be its own packet
11259 because we don't know how the target actually organizes its trace
11260 memory, plus we want to be able to ask for as much as possible, but
11261 not be unhappy if we don't get as much as we ask for. */
11264 remote_get_raw_trace_data (struct target_ops *self,
11265 gdb_byte *buf, ULONGEST offset, LONGEST len)
11267 struct remote_state *rs = get_remote_state ();
11273 strcpy (p, "qTBuffer:");
11275 p += hexnumstr (p, offset);
11277 p += hexnumstr (p, len);
11281 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11282 if (reply && *reply)
11284 /* 'l' by itself means we're at the end of the buffer and
11285 there is nothing more to get. */
11289 /* Convert the reply into binary. Limit the number of bytes to
11290 convert according to our passed-in buffer size, rather than
11291 what was returned in the packet; if the target is
11292 unexpectedly generous and gives us a bigger reply than we
11293 asked for, we don't want to crash. */
11294 rslt = hex2bin (target_buf, buf, len);
11298 /* Something went wrong, flag as an error. */
11303 remote_set_disconnected_tracing (struct target_ops *self, int val)
11305 struct remote_state *rs = get_remote_state ();
11307 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
11311 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
11313 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11314 if (*reply == '\0')
11315 error (_("Target does not support this command."));
11316 if (strcmp (reply, "OK") != 0)
11317 error (_("Bogus reply from target: %s"), reply);
11320 warning (_("Target does not support disconnected tracing."));
11324 remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
11326 struct thread_info *info = find_thread_ptid (ptid);
11328 if (info && info->priv)
11329 return info->priv->core;
11334 remote_set_circular_trace_buffer (struct target_ops *self, int val)
11336 struct remote_state *rs = get_remote_state ();
11339 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
11341 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11342 if (*reply == '\0')
11343 error (_("Target does not support this command."));
11344 if (strcmp (reply, "OK") != 0)
11345 error (_("Bogus reply from target: %s"), reply);
11348 static struct traceframe_info *
11349 remote_traceframe_info (struct target_ops *self)
11353 text = target_read_stralloc (¤t_target,
11354 TARGET_OBJECT_TRACEFRAME_INFO, NULL);
11357 struct traceframe_info *info;
11358 struct cleanup *back_to = make_cleanup (xfree, text);
11360 info = parse_traceframe_info (text);
11361 do_cleanups (back_to);
11368 /* Handle the qTMinFTPILen packet. Returns the minimum length of
11369 instruction on which a fast tracepoint may be placed. Returns -1
11370 if the packet is not supported, and 0 if the minimum instruction
11371 length is unknown. */
11374 remote_get_min_fast_tracepoint_insn_len (struct target_ops *self)
11376 struct remote_state *rs = get_remote_state ();
11379 /* If we're not debugging a process yet, the IPA can't be
11381 if (!target_has_execution)
11384 /* Make sure the remote is pointing at the right process. */
11385 set_general_process ();
11387 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
11389 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11390 if (*reply == '\0')
11394 ULONGEST min_insn_len;
11396 unpack_varlen_hex (reply, &min_insn_len);
11398 return (int) min_insn_len;
11403 remote_set_trace_buffer_size (struct target_ops *self, LONGEST val)
11405 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
11407 struct remote_state *rs = get_remote_state ();
11408 char *buf = rs->buf;
11409 char *endbuf = rs->buf + get_remote_packet_size ();
11410 enum packet_result result;
11412 gdb_assert (val >= 0 || val == -1);
11413 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
11414 /* Send -1 as literal "-1" to avoid host size dependency. */
11418 buf += hexnumstr (buf, (ULONGEST) -val);
11421 buf += hexnumstr (buf, (ULONGEST) val);
11424 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11425 result = packet_ok (rs->buf,
11426 &remote_protocol_packets[PACKET_QTBuffer_size]);
11428 if (result != PACKET_OK)
11429 warning (_("Bogus reply from target: %s"), rs->buf);
11434 remote_set_trace_notes (struct target_ops *self,
11435 const char *user, const char *notes,
11436 const char *stop_notes)
11438 struct remote_state *rs = get_remote_state ();
11440 char *buf = rs->buf;
11441 char *endbuf = rs->buf + get_remote_packet_size ();
11444 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
11447 buf += xsnprintf (buf, endbuf - buf, "user:");
11448 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
11454 buf += xsnprintf (buf, endbuf - buf, "notes:");
11455 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
11461 buf += xsnprintf (buf, endbuf - buf, "tstop:");
11462 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
11466 /* Ensure the buffer is terminated. */
11470 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11471 if (*reply == '\0')
11474 if (strcmp (reply, "OK") != 0)
11475 error (_("Bogus reply from target: %s"), reply);
11481 remote_use_agent (struct target_ops *self, int use)
11483 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
11485 struct remote_state *rs = get_remote_state ();
11487 /* If the stub supports QAgent. */
11488 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
11490 getpkt (&rs->buf, &rs->buf_size, 0);
11492 if (strcmp (rs->buf, "OK") == 0)
11503 remote_can_use_agent (struct target_ops *self)
11505 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
11508 struct btrace_target_info
11510 /* The ptid of the traced thread. */
11513 /* The obtained branch trace configuration. */
11514 struct btrace_config conf;
11517 /* Reset our idea of our target's btrace configuration. */
11520 remote_btrace_reset (void)
11522 struct remote_state *rs = get_remote_state ();
11524 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
11527 /* Check whether the target supports branch tracing. */
11530 remote_supports_btrace (struct target_ops *self, enum btrace_format format)
11532 if (packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
11534 if (packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
11539 case BTRACE_FORMAT_NONE:
11542 case BTRACE_FORMAT_BTS:
11543 return (packet_support (PACKET_Qbtrace_bts) == PACKET_ENABLE);
11546 internal_error (__FILE__, __LINE__, _("Unknown branch trace format"));
11549 /* Synchronize the configuration with the target. */
11552 btrace_sync_conf (const struct btrace_config *conf)
11554 struct packet_config *packet;
11555 struct remote_state *rs;
11556 char *buf, *pos, *endbuf;
11558 rs = get_remote_state ();
11560 endbuf = buf + get_remote_packet_size ();
11562 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
11563 if (packet_config_support (packet) == PACKET_ENABLE
11564 && conf->bts.size != rs->btrace_config.bts.size)
11567 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
11571 getpkt (&buf, &rs->buf_size, 0);
11573 if (packet_ok (buf, packet) == PACKET_ERROR)
11575 if (buf[0] == 'E' && buf[1] == '.')
11576 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
11578 error (_("Failed to configure the BTS buffer size."));
11581 rs->btrace_config.bts.size = conf->bts.size;
11585 /* Read the current thread's btrace configuration from the target and
11586 store it into CONF. */
11589 btrace_read_config (struct btrace_config *conf)
11593 xml = target_read_stralloc (¤t_target,
11594 TARGET_OBJECT_BTRACE_CONF, "");
11597 struct cleanup *cleanup;
11599 cleanup = make_cleanup (xfree, xml);
11600 parse_xml_btrace_conf (conf, xml);
11601 do_cleanups (cleanup);
11605 /* Enable branch tracing. */
11607 static struct btrace_target_info *
11608 remote_enable_btrace (struct target_ops *self, ptid_t ptid,
11609 const struct btrace_config *conf)
11611 struct btrace_target_info *tinfo = NULL;
11612 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
11613 struct remote_state *rs = get_remote_state ();
11614 char *buf = rs->buf;
11615 char *endbuf = rs->buf + get_remote_packet_size ();
11617 if (packet_config_support (packet) != PACKET_ENABLE)
11618 error (_("Target does not support branch tracing."));
11620 btrace_sync_conf (conf);
11622 set_general_thread (ptid);
11624 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
11626 getpkt (&rs->buf, &rs->buf_size, 0);
11628 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
11630 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
11631 error (_("Could not enable branch tracing for %s: %s"),
11632 target_pid_to_str (ptid), rs->buf + 2);
11634 error (_("Could not enable branch tracing for %s."),
11635 target_pid_to_str (ptid));
11638 tinfo = xzalloc (sizeof (*tinfo));
11639 tinfo->ptid = ptid;
11641 /* If we fail to read the configuration, we lose some information, but the
11642 tracing itself is not impacted. */
11645 btrace_read_config (&tinfo->conf);
11647 CATCH (err, RETURN_MASK_ERROR)
11649 if (err.message != NULL)
11650 warning ("%s", err.message);
11657 /* Disable branch tracing. */
11660 remote_disable_btrace (struct target_ops *self,
11661 struct btrace_target_info *tinfo)
11663 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
11664 struct remote_state *rs = get_remote_state ();
11665 char *buf = rs->buf;
11666 char *endbuf = rs->buf + get_remote_packet_size ();
11668 if (packet_config_support (packet) != PACKET_ENABLE)
11669 error (_("Target does not support branch tracing."));
11671 set_general_thread (tinfo->ptid);
11673 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
11675 getpkt (&rs->buf, &rs->buf_size, 0);
11677 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
11679 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
11680 error (_("Could not disable branch tracing for %s: %s"),
11681 target_pid_to_str (tinfo->ptid), rs->buf + 2);
11683 error (_("Could not disable branch tracing for %s."),
11684 target_pid_to_str (tinfo->ptid));
11690 /* Teardown branch tracing. */
11693 remote_teardown_btrace (struct target_ops *self,
11694 struct btrace_target_info *tinfo)
11696 /* We must not talk to the target during teardown. */
11700 /* Read the branch trace. */
11702 static enum btrace_error
11703 remote_read_btrace (struct target_ops *self,
11704 struct btrace_data *btrace,
11705 struct btrace_target_info *tinfo,
11706 enum btrace_read_type type)
11708 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
11709 struct remote_state *rs = get_remote_state ();
11710 struct cleanup *cleanup;
11714 if (packet_config_support (packet) != PACKET_ENABLE)
11715 error (_("Target does not support branch tracing."));
11717 #if !defined(HAVE_LIBEXPAT)
11718 error (_("Cannot process branch tracing result. XML parsing not supported."));
11723 case BTRACE_READ_ALL:
11726 case BTRACE_READ_NEW:
11729 case BTRACE_READ_DELTA:
11733 internal_error (__FILE__, __LINE__,
11734 _("Bad branch tracing read type: %u."),
11735 (unsigned int) type);
11738 xml = target_read_stralloc (¤t_target,
11739 TARGET_OBJECT_BTRACE, annex);
11741 return BTRACE_ERR_UNKNOWN;
11743 cleanup = make_cleanup (xfree, xml);
11744 parse_xml_btrace (btrace, xml);
11745 do_cleanups (cleanup);
11747 return BTRACE_ERR_NONE;
11750 static const struct btrace_config *
11751 remote_btrace_conf (struct target_ops *self,
11752 const struct btrace_target_info *tinfo)
11754 return &tinfo->conf;
11758 remote_augmented_libraries_svr4_read (struct target_ops *self)
11760 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
11764 /* Implementation of to_load. */
11767 remote_load (struct target_ops *self, const char *name, int from_tty)
11769 generic_load (name, from_tty);
11773 init_remote_ops (void)
11775 remote_ops.to_shortname = "remote";
11776 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
11777 remote_ops.to_doc =
11778 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
11779 Specify the serial device it is connected to\n\
11780 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
11781 remote_ops.to_open = remote_open;
11782 remote_ops.to_close = remote_close;
11783 remote_ops.to_detach = remote_detach;
11784 remote_ops.to_disconnect = remote_disconnect;
11785 remote_ops.to_resume = remote_resume;
11786 remote_ops.to_wait = remote_wait;
11787 remote_ops.to_fetch_registers = remote_fetch_registers;
11788 remote_ops.to_store_registers = remote_store_registers;
11789 remote_ops.to_prepare_to_store = remote_prepare_to_store;
11790 remote_ops.to_files_info = remote_files_info;
11791 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
11792 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
11793 remote_ops.to_stopped_by_sw_breakpoint = remote_stopped_by_sw_breakpoint;
11794 remote_ops.to_supports_stopped_by_sw_breakpoint = remote_supports_stopped_by_sw_breakpoint;
11795 remote_ops.to_stopped_by_hw_breakpoint = remote_stopped_by_hw_breakpoint;
11796 remote_ops.to_supports_stopped_by_hw_breakpoint = remote_supports_stopped_by_hw_breakpoint;
11797 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
11798 remote_ops.to_stopped_data_address = remote_stopped_data_address;
11799 remote_ops.to_watchpoint_addr_within_range =
11800 remote_watchpoint_addr_within_range;
11801 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
11802 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
11803 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
11804 remote_ops.to_region_ok_for_hw_watchpoint
11805 = remote_region_ok_for_hw_watchpoint;
11806 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
11807 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
11808 remote_ops.to_kill = remote_kill;
11809 remote_ops.to_load = remote_load;
11810 remote_ops.to_mourn_inferior = remote_mourn;
11811 remote_ops.to_pass_signals = remote_pass_signals;
11812 remote_ops.to_program_signals = remote_program_signals;
11813 remote_ops.to_thread_alive = remote_thread_alive;
11814 remote_ops.to_update_thread_list = remote_update_thread_list;
11815 remote_ops.to_pid_to_str = remote_pid_to_str;
11816 remote_ops.to_extra_thread_info = remote_threads_extra_info;
11817 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
11818 remote_ops.to_stop = remote_stop;
11819 remote_ops.to_xfer_partial = remote_xfer_partial;
11820 remote_ops.to_rcmd = remote_rcmd;
11821 remote_ops.to_log_command = serial_log_command;
11822 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
11823 remote_ops.to_stratum = process_stratum;
11824 remote_ops.to_has_all_memory = default_child_has_all_memory;
11825 remote_ops.to_has_memory = default_child_has_memory;
11826 remote_ops.to_has_stack = default_child_has_stack;
11827 remote_ops.to_has_registers = default_child_has_registers;
11828 remote_ops.to_has_execution = default_child_has_execution;
11829 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
11830 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
11831 remote_ops.to_magic = OPS_MAGIC;
11832 remote_ops.to_memory_map = remote_memory_map;
11833 remote_ops.to_flash_erase = remote_flash_erase;
11834 remote_ops.to_flash_done = remote_flash_done;
11835 remote_ops.to_read_description = remote_read_description;
11836 remote_ops.to_search_memory = remote_search_memory;
11837 remote_ops.to_can_async_p = remote_can_async_p;
11838 remote_ops.to_is_async_p = remote_is_async_p;
11839 remote_ops.to_async = remote_async;
11840 remote_ops.to_terminal_inferior = remote_terminal_inferior;
11841 remote_ops.to_terminal_ours = remote_terminal_ours;
11842 remote_ops.to_supports_non_stop = remote_supports_non_stop;
11843 remote_ops.to_supports_multi_process = remote_supports_multi_process;
11844 remote_ops.to_supports_disable_randomization
11845 = remote_supports_disable_randomization;
11846 remote_ops.to_fileio_open = remote_hostio_open;
11847 remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
11848 remote_ops.to_fileio_pread = remote_hostio_pread;
11849 remote_ops.to_fileio_close = remote_hostio_close;
11850 remote_ops.to_fileio_unlink = remote_hostio_unlink;
11851 remote_ops.to_fileio_readlink = remote_hostio_readlink;
11852 remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
11853 remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
11854 remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
11855 remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
11856 remote_ops.to_trace_init = remote_trace_init;
11857 remote_ops.to_download_tracepoint = remote_download_tracepoint;
11858 remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
11859 remote_ops.to_download_trace_state_variable
11860 = remote_download_trace_state_variable;
11861 remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
11862 remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
11863 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
11864 remote_ops.to_trace_start = remote_trace_start;
11865 remote_ops.to_get_trace_status = remote_get_trace_status;
11866 remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
11867 remote_ops.to_trace_stop = remote_trace_stop;
11868 remote_ops.to_trace_find = remote_trace_find;
11869 remote_ops.to_get_trace_state_variable_value
11870 = remote_get_trace_state_variable_value;
11871 remote_ops.to_save_trace_data = remote_save_trace_data;
11872 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
11873 remote_ops.to_upload_trace_state_variables
11874 = remote_upload_trace_state_variables;
11875 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
11876 remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
11877 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
11878 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
11879 remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
11880 remote_ops.to_set_trace_notes = remote_set_trace_notes;
11881 remote_ops.to_core_of_thread = remote_core_of_thread;
11882 remote_ops.to_verify_memory = remote_verify_memory;
11883 remote_ops.to_get_tib_address = remote_get_tib_address;
11884 remote_ops.to_set_permissions = remote_set_permissions;
11885 remote_ops.to_static_tracepoint_marker_at
11886 = remote_static_tracepoint_marker_at;
11887 remote_ops.to_static_tracepoint_markers_by_strid
11888 = remote_static_tracepoint_markers_by_strid;
11889 remote_ops.to_traceframe_info = remote_traceframe_info;
11890 remote_ops.to_use_agent = remote_use_agent;
11891 remote_ops.to_can_use_agent = remote_can_use_agent;
11892 remote_ops.to_supports_btrace = remote_supports_btrace;
11893 remote_ops.to_enable_btrace = remote_enable_btrace;
11894 remote_ops.to_disable_btrace = remote_disable_btrace;
11895 remote_ops.to_teardown_btrace = remote_teardown_btrace;
11896 remote_ops.to_read_btrace = remote_read_btrace;
11897 remote_ops.to_btrace_conf = remote_btrace_conf;
11898 remote_ops.to_augmented_libraries_svr4_read =
11899 remote_augmented_libraries_svr4_read;
11902 /* Set up the extended remote vector by making a copy of the standard
11903 remote vector and adding to it. */
11906 init_extended_remote_ops (void)
11908 extended_remote_ops = remote_ops;
11910 extended_remote_ops.to_shortname = "extended-remote";
11911 extended_remote_ops.to_longname =
11912 "Extended remote serial target in gdb-specific protocol";
11913 extended_remote_ops.to_doc =
11914 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
11915 Specify the serial device it is connected to (e.g. /dev/ttya).";
11916 extended_remote_ops.to_open = extended_remote_open;
11917 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
11918 extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
11919 extended_remote_ops.to_detach = extended_remote_detach;
11920 extended_remote_ops.to_attach = extended_remote_attach;
11921 extended_remote_ops.to_post_attach = extended_remote_post_attach;
11922 extended_remote_ops.to_kill = extended_remote_kill;
11923 extended_remote_ops.to_supports_disable_randomization
11924 = extended_remote_supports_disable_randomization;
11928 remote_can_async_p (struct target_ops *ops)
11930 struct remote_state *rs = get_remote_state ();
11932 if (!target_async_permitted)
11933 /* We only enable async when the user specifically asks for it. */
11936 /* We're async whenever the serial device is. */
11937 return serial_can_async_p (rs->remote_desc);
11941 remote_is_async_p (struct target_ops *ops)
11943 struct remote_state *rs = get_remote_state ();
11945 if (!target_async_permitted)
11946 /* We only enable async when the user specifically asks for it. */
11949 /* We're async whenever the serial device is. */
11950 return serial_is_async_p (rs->remote_desc);
11953 /* Pass the SERIAL event on and up to the client. One day this code
11954 will be able to delay notifying the client of an event until the
11955 point where an entire packet has been received. */
11957 static serial_event_ftype remote_async_serial_handler;
11960 remote_async_serial_handler (struct serial *scb, void *context)
11962 struct remote_state *rs = context;
11964 /* Don't propogate error information up to the client. Instead let
11965 the client find out about the error by querying the target. */
11966 rs->async_client_callback (INF_REG_EVENT, rs->async_client_context);
11970 remote_async_inferior_event_handler (gdb_client_data data)
11972 inferior_event_handler (INF_REG_EVENT, NULL);
11976 remote_async (struct target_ops *ops,
11977 void (*callback) (enum inferior_event_type event_type,
11981 struct remote_state *rs = get_remote_state ();
11983 if (callback != NULL)
11985 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
11986 rs->async_client_callback = callback;
11987 rs->async_client_context = context;
11989 /* If there are pending events in the stop reply queue tell the
11990 event loop to process them. */
11991 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
11992 mark_async_event_handler (remote_async_inferior_event_token);
11996 serial_async (rs->remote_desc, NULL, NULL);
11997 clear_async_event_handler (remote_async_inferior_event_token);
12002 set_remote_cmd (char *args, int from_tty)
12004 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
12008 show_remote_cmd (char *args, int from_tty)
12010 /* We can't just use cmd_show_list here, because we want to skip
12011 the redundant "show remote Z-packet" and the legacy aliases. */
12012 struct cleanup *showlist_chain;
12013 struct cmd_list_element *list = remote_show_cmdlist;
12014 struct ui_out *uiout = current_uiout;
12016 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
12017 for (; list != NULL; list = list->next)
12018 if (strcmp (list->name, "Z-packet") == 0)
12020 else if (list->type == not_set_cmd)
12021 /* Alias commands are exactly like the original, except they
12022 don't have the normal type. */
12026 struct cleanup *option_chain
12027 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
12029 ui_out_field_string (uiout, "name", list->name);
12030 ui_out_text (uiout, ": ");
12031 if (list->type == show_cmd)
12032 do_show_command ((char *) NULL, from_tty, list);
12034 cmd_func (list, NULL, from_tty);
12035 /* Close the tuple. */
12036 do_cleanups (option_chain);
12039 /* Close the tuple. */
12040 do_cleanups (showlist_chain);
12044 /* Function to be called whenever a new objfile (shlib) is detected. */
12046 remote_new_objfile (struct objfile *objfile)
12048 struct remote_state *rs = get_remote_state ();
12050 if (rs->remote_desc != 0) /* Have a remote connection. */
12051 remote_check_symbols ();
12054 /* Pull all the tracepoints defined on the target and create local
12055 data structures representing them. We don't want to create real
12056 tracepoints yet, we don't want to mess up the user's existing
12060 remote_upload_tracepoints (struct target_ops *self, struct uploaded_tp **utpp)
12062 struct remote_state *rs = get_remote_state ();
12065 /* Ask for a first packet of tracepoint definition. */
12067 getpkt (&rs->buf, &rs->buf_size, 0);
12069 while (*p && *p != 'l')
12071 parse_tracepoint_definition (p, utpp);
12072 /* Ask for another packet of tracepoint definition. */
12074 getpkt (&rs->buf, &rs->buf_size, 0);
12081 remote_upload_trace_state_variables (struct target_ops *self,
12082 struct uploaded_tsv **utsvp)
12084 struct remote_state *rs = get_remote_state ();
12087 /* Ask for a first packet of variable definition. */
12089 getpkt (&rs->buf, &rs->buf_size, 0);
12091 while (*p && *p != 'l')
12093 parse_tsv_definition (p, utsvp);
12094 /* Ask for another packet of variable definition. */
12096 getpkt (&rs->buf, &rs->buf_size, 0);
12102 /* The "set/show range-stepping" show hook. */
12105 show_range_stepping (struct ui_file *file, int from_tty,
12106 struct cmd_list_element *c,
12109 fprintf_filtered (file,
12110 _("Debugger's willingness to use range stepping "
12111 "is %s.\n"), value);
12114 /* The "set/show range-stepping" set hook. */
12117 set_range_stepping (char *ignore_args, int from_tty,
12118 struct cmd_list_element *c)
12120 struct remote_state *rs = get_remote_state ();
12122 /* Whene enabling, check whether range stepping is actually
12123 supported by the target, and warn if not. */
12124 if (use_range_stepping)
12126 if (rs->remote_desc != NULL)
12128 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
12129 remote_vcont_probe (rs);
12131 if (packet_support (PACKET_vCont) == PACKET_ENABLE
12132 && rs->supports_vCont.r)
12136 warning (_("Range stepping is not supported by the current target"));
12141 _initialize_remote (void)
12143 struct remote_state *rs;
12144 struct cmd_list_element *cmd;
12145 const char *cmd_name;
12147 /* architecture specific data */
12148 remote_gdbarch_data_handle =
12149 gdbarch_data_register_post_init (init_remote_state);
12150 remote_g_packet_data_handle =
12151 gdbarch_data_register_pre_init (remote_g_packet_data_init);
12153 /* Initialize the per-target state. At the moment there is only one
12154 of these, not one per target. Only one target is active at a
12156 remote_state = new_remote_state ();
12158 init_remote_ops ();
12159 add_target (&remote_ops);
12161 init_extended_remote_ops ();
12162 add_target (&extended_remote_ops);
12164 /* Hook into new objfile notification. */
12165 observer_attach_new_objfile (remote_new_objfile);
12166 /* We're no longer interested in notification events of an inferior
12168 observer_attach_inferior_exit (discard_pending_stop_replies);
12170 /* Set up signal handlers. */
12171 async_sigint_remote_token =
12172 create_async_signal_handler (async_remote_interrupt, NULL);
12173 async_sigint_remote_twice_token =
12174 create_async_signal_handler (async_remote_interrupt_twice, NULL);
12177 init_remote_threadtests ();
12180 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
12181 /* set/show remote ... */
12183 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
12184 Remote protocol specific variables\n\
12185 Configure various remote-protocol specific variables such as\n\
12186 the packets being used"),
12187 &remote_set_cmdlist, "set remote ",
12188 0 /* allow-unknown */, &setlist);
12189 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
12190 Remote protocol specific variables\n\
12191 Configure various remote-protocol specific variables such as\n\
12192 the packets being used"),
12193 &remote_show_cmdlist, "show remote ",
12194 0 /* allow-unknown */, &showlist);
12196 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
12197 Compare section data on target to the exec file.\n\
12198 Argument is a single section name (default: all loaded sections).\n\
12199 To compare only read-only loaded sections, specify the -r option."),
12202 add_cmd ("packet", class_maintenance, packet_command, _("\
12203 Send an arbitrary packet to a remote target.\n\
12204 maintenance packet TEXT\n\
12205 If GDB is talking to an inferior via the GDB serial protocol, then\n\
12206 this command sends the string TEXT to the inferior, and displays the\n\
12207 response packet. GDB supplies the initial `$' character, and the\n\
12208 terminating `#' character and checksum."),
12211 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
12212 Set whether to send break if interrupted."), _("\
12213 Show whether to send break if interrupted."), _("\
12214 If set, a break, instead of a cntrl-c, is sent to the remote target."),
12215 set_remotebreak, show_remotebreak,
12216 &setlist, &showlist);
12217 cmd_name = "remotebreak";
12218 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
12219 deprecate_cmd (cmd, "set remote interrupt-sequence");
12220 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
12221 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
12222 deprecate_cmd (cmd, "show remote interrupt-sequence");
12224 add_setshow_enum_cmd ("interrupt-sequence", class_support,
12225 interrupt_sequence_modes, &interrupt_sequence_mode,
12227 Set interrupt sequence to remote target."), _("\
12228 Show interrupt sequence to remote target."), _("\
12229 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
12230 NULL, show_interrupt_sequence,
12231 &remote_set_cmdlist,
12232 &remote_show_cmdlist);
12234 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
12235 &interrupt_on_connect, _("\
12236 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
12237 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
12238 If set, interrupt sequence is sent to remote target."),
12240 &remote_set_cmdlist, &remote_show_cmdlist);
12242 /* Install commands for configuring memory read/write packets. */
12244 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
12245 Set the maximum number of bytes per memory write packet (deprecated)."),
12247 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
12248 Show the maximum number of bytes per memory write packet (deprecated)."),
12250 add_cmd ("memory-write-packet-size", no_class,
12251 set_memory_write_packet_size, _("\
12252 Set the maximum number of bytes per memory-write packet.\n\
12253 Specify the number of bytes in a packet or 0 (zero) for the\n\
12254 default packet size. The actual limit is further reduced\n\
12255 dependent on the target. Specify ``fixed'' to disable the\n\
12256 further restriction and ``limit'' to enable that restriction."),
12257 &remote_set_cmdlist);
12258 add_cmd ("memory-read-packet-size", no_class,
12259 set_memory_read_packet_size, _("\
12260 Set the maximum number of bytes per memory-read packet.\n\
12261 Specify the number of bytes in a packet or 0 (zero) for the\n\
12262 default packet size. The actual limit is further reduced\n\
12263 dependent on the target. Specify ``fixed'' to disable the\n\
12264 further restriction and ``limit'' to enable that restriction."),
12265 &remote_set_cmdlist);
12266 add_cmd ("memory-write-packet-size", no_class,
12267 show_memory_write_packet_size,
12268 _("Show the maximum number of bytes per memory-write packet."),
12269 &remote_show_cmdlist);
12270 add_cmd ("memory-read-packet-size", no_class,
12271 show_memory_read_packet_size,
12272 _("Show the maximum number of bytes per memory-read packet."),
12273 &remote_show_cmdlist);
12275 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
12276 &remote_hw_watchpoint_limit, _("\
12277 Set the maximum number of target hardware watchpoints."), _("\
12278 Show the maximum number of target hardware watchpoints."), _("\
12279 Specify a negative limit for unlimited."),
12280 NULL, NULL, /* FIXME: i18n: The maximum
12281 number of target hardware
12282 watchpoints is %s. */
12283 &remote_set_cmdlist, &remote_show_cmdlist);
12284 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
12285 &remote_hw_watchpoint_length_limit, _("\
12286 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
12287 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
12288 Specify a negative limit for unlimited."),
12289 NULL, NULL, /* FIXME: i18n: The maximum
12290 length (in bytes) of a target
12291 hardware watchpoint is %s. */
12292 &remote_set_cmdlist, &remote_show_cmdlist);
12293 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
12294 &remote_hw_breakpoint_limit, _("\
12295 Set the maximum number of target hardware breakpoints."), _("\
12296 Show the maximum number of target hardware breakpoints."), _("\
12297 Specify a negative limit for unlimited."),
12298 NULL, NULL, /* FIXME: i18n: The maximum
12299 number of target hardware
12300 breakpoints is %s. */
12301 &remote_set_cmdlist, &remote_show_cmdlist);
12303 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
12304 &remote_address_size, _("\
12305 Set the maximum size of the address (in bits) in a memory packet."), _("\
12306 Show the maximum size of the address (in bits) in a memory packet."), NULL,
12308 NULL, /* FIXME: i18n: */
12309 &setlist, &showlist);
12311 init_all_packet_configs ();
12313 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
12314 "X", "binary-download", 1);
12316 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
12317 "vCont", "verbose-resume", 0);
12319 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
12320 "QPassSignals", "pass-signals", 0);
12322 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
12323 "QProgramSignals", "program-signals", 0);
12325 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
12326 "qSymbol", "symbol-lookup", 0);
12328 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
12329 "P", "set-register", 1);
12331 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
12332 "p", "fetch-register", 1);
12334 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
12335 "Z0", "software-breakpoint", 0);
12337 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
12338 "Z1", "hardware-breakpoint", 0);
12340 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
12341 "Z2", "write-watchpoint", 0);
12343 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
12344 "Z3", "read-watchpoint", 0);
12346 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
12347 "Z4", "access-watchpoint", 0);
12349 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
12350 "qXfer:auxv:read", "read-aux-vector", 0);
12352 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
12353 "qXfer:features:read", "target-features", 0);
12355 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
12356 "qXfer:libraries:read", "library-info", 0);
12358 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
12359 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
12361 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
12362 "qXfer:memory-map:read", "memory-map", 0);
12364 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
12365 "qXfer:spu:read", "read-spu-object", 0);
12367 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
12368 "qXfer:spu:write", "write-spu-object", 0);
12370 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
12371 "qXfer:osdata:read", "osdata", 0);
12373 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
12374 "qXfer:threads:read", "threads", 0);
12376 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
12377 "qXfer:siginfo:read", "read-siginfo-object", 0);
12379 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
12380 "qXfer:siginfo:write", "write-siginfo-object", 0);
12382 add_packet_config_cmd
12383 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
12384 "qXfer:traceframe-info:read", "traceframe-info", 0);
12386 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
12387 "qXfer:uib:read", "unwind-info-block", 0);
12389 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
12390 "qGetTLSAddr", "get-thread-local-storage-address",
12393 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
12394 "qGetTIBAddr", "get-thread-information-block-address",
12397 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
12398 "bc", "reverse-continue", 0);
12400 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
12401 "bs", "reverse-step", 0);
12403 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
12404 "qSupported", "supported-packets", 0);
12406 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
12407 "qSearch:memory", "search-memory", 0);
12409 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
12410 "qTStatus", "trace-status", 0);
12412 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
12413 "vFile:open", "hostio-open", 0);
12415 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
12416 "vFile:pread", "hostio-pread", 0);
12418 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
12419 "vFile:pwrite", "hostio-pwrite", 0);
12421 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
12422 "vFile:close", "hostio-close", 0);
12424 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
12425 "vFile:unlink", "hostio-unlink", 0);
12427 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
12428 "vFile:readlink", "hostio-readlink", 0);
12430 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
12431 "vFile:fstat", "hostio-fstat", 0);
12433 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
12434 "vAttach", "attach", 0);
12436 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
12439 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
12440 "QStartNoAckMode", "noack", 0);
12442 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
12443 "vKill", "kill", 0);
12445 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
12446 "qAttached", "query-attached", 0);
12448 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
12449 "ConditionalTracepoints",
12450 "conditional-tracepoints", 0);
12452 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
12453 "ConditionalBreakpoints",
12454 "conditional-breakpoints", 0);
12456 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
12457 "BreakpointCommands",
12458 "breakpoint-commands", 0);
12460 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
12461 "FastTracepoints", "fast-tracepoints", 0);
12463 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
12464 "TracepointSource", "TracepointSource", 0);
12466 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
12467 "QAllow", "allow", 0);
12469 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
12470 "StaticTracepoints", "static-tracepoints", 0);
12472 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
12473 "InstallInTrace", "install-in-trace", 0);
12475 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
12476 "qXfer:statictrace:read", "read-sdata-object", 0);
12478 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
12479 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
12481 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
12482 "QDisableRandomization", "disable-randomization", 0);
12484 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
12485 "QAgent", "agent", 0);
12487 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
12488 "QTBuffer:size", "trace-buffer-size", 0);
12490 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
12491 "Qbtrace:off", "disable-btrace", 0);
12493 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
12494 "Qbtrace:bts", "enable-btrace", 0);
12496 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
12497 "qXfer:btrace", "read-btrace", 0);
12499 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
12500 "qXfer:btrace-conf", "read-btrace-conf", 0);
12502 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
12503 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
12505 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
12506 "swbreak-feature", "swbreak-feature", 0);
12508 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
12509 "hwbreak-feature", "hwbreak-feature", 0);
12511 /* Assert that we've registered commands for all packet configs. */
12515 for (i = 0; i < PACKET_MAX; i++)
12517 /* Ideally all configs would have a command associated. Some
12518 still don't though. */
12523 case PACKET_QNonStop:
12524 case PACKET_multiprocess_feature:
12525 case PACKET_EnableDisableTracepoints_feature:
12526 case PACKET_tracenz_feature:
12527 case PACKET_DisconnectedTracing_feature:
12528 case PACKET_augmented_libraries_svr4_read_feature:
12530 /* Additions to this list need to be well justified:
12531 pre-existing packets are OK; new packets are not. */
12539 /* This catches both forgetting to add a config command, and
12540 forgetting to remove a packet from the exception list. */
12541 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
12545 /* Keep the old ``set remote Z-packet ...'' working. Each individual
12546 Z sub-packet has its own set and show commands, but users may
12547 have sets to this variable in their .gdbinit files (or in their
12549 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
12550 &remote_Z_packet_detect, _("\
12551 Set use of remote protocol `Z' packets"), _("\
12552 Show use of remote protocol `Z' packets "), _("\
12553 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
12555 set_remote_protocol_Z_packet_cmd,
12556 show_remote_protocol_Z_packet_cmd,
12557 /* FIXME: i18n: Use of remote protocol
12558 `Z' packets is %s. */
12559 &remote_set_cmdlist, &remote_show_cmdlist);
12561 add_prefix_cmd ("remote", class_files, remote_command, _("\
12562 Manipulate files on the remote system\n\
12563 Transfer files to and from the remote target system."),
12564 &remote_cmdlist, "remote ",
12565 0 /* allow-unknown */, &cmdlist);
12567 add_cmd ("put", class_files, remote_put_command,
12568 _("Copy a local file to the remote system."),
12571 add_cmd ("get", class_files, remote_get_command,
12572 _("Copy a remote file to the local system."),
12575 add_cmd ("delete", class_files, remote_delete_command,
12576 _("Delete a remote file."),
12579 remote_exec_file = xstrdup ("");
12580 add_setshow_string_noescape_cmd ("exec-file", class_files,
12581 &remote_exec_file, _("\
12582 Set the remote pathname for \"run\""), _("\
12583 Show the remote pathname for \"run\""), NULL, NULL, NULL,
12584 &remote_set_cmdlist, &remote_show_cmdlist);
12586 add_setshow_boolean_cmd ("range-stepping", class_run,
12587 &use_range_stepping, _("\
12588 Enable or disable range stepping."), _("\
12589 Show whether target-assisted range stepping is enabled."), _("\
12590 If on, and the target supports it, when stepping a source line, GDB\n\
12591 tells the target to step the corresponding range of addresses itself instead\n\
12592 of issuing multiple single-steps. This speeds up source level\n\
12593 stepping. If off, GDB always issues single-steps, even if range\n\
12594 stepping is supported by the target. The default is on."),
12595 set_range_stepping,
12596 show_range_stepping,
12600 /* Eventually initialize fileio. See fileio.c */
12601 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
12603 /* Take advantage of the fact that the TID field is not used, to tag
12604 special ptids with it set to != 0. */
12605 magic_null_ptid = ptid_build (42000, -1, 1);
12606 not_sent_ptid = ptid_build (42000, -2, 1);
12607 any_thread_ptid = ptid_build (42000, 0, 1);
12609 target_buf_size = 2048;
12610 target_buf = xmalloc (target_buf_size);