1 /* Remote target communications for serial-line targets in custom GDB protocol
3 Copyright (C) 1988-2018 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"
39 #include "observable.h"
41 #include "cli/cli-decode.h"
42 #include "cli/cli-setshow.h"
43 #include "target-descriptions.h"
45 #include "filestuff.h"
50 #include "gdb_sys_time.h"
52 #include "event-loop.h"
53 #include "event-top.h"
59 #include "gdbcore.h" /* for exec_bfd */
61 #include "remote-fileio.h"
62 #include "gdb/fileio.h"
64 #include "xml-support.h"
66 #include "memory-map.h"
68 #include "tracepoint.h"
73 #include "record-btrace.h"
75 #include "common/scoped_restore.h"
77 #include "common/byte-vector.h"
79 /* The remote target. */
81 class remote_target : public target_ops
86 to_stratum = process_stratum;
89 const char *shortname () override
92 const char *longname () override
93 { return _("Remote serial target in gdb-specific protocol"); }
95 const char *doc () override
98 Use a remote computer via a serial line, using a gdb-specific protocol.\n\
99 Specify the serial device it is connected to\n\
100 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).");
103 thread_control_capabilities get_thread_control_capabilities () override
104 { return tc_schedlock; }
106 void open (const char *, int) override;
107 void close () override;
109 void detach (inferior *, int) override;
110 void disconnect (const char *, int) override;
112 void commit_resume () override;
113 void resume (ptid_t, int, enum gdb_signal) override;
114 ptid_t wait (ptid_t, struct target_waitstatus *, int) override;
116 void fetch_registers (struct regcache *, int) override;
117 void store_registers (struct regcache *, int) override;
118 void prepare_to_store (struct regcache *) override;
120 void files_info () override;
122 int insert_breakpoint (struct gdbarch *, struct bp_target_info *) override;
124 int remove_breakpoint (struct gdbarch *, struct bp_target_info *,
125 enum remove_bp_reason) override;
128 int stopped_by_sw_breakpoint () override;
129 int supports_stopped_by_sw_breakpoint () override;
131 int stopped_by_hw_breakpoint () override;
133 int supports_stopped_by_hw_breakpoint () override;
135 int stopped_by_watchpoint () override;
137 int stopped_data_address (CORE_ADDR *) override;
139 int watchpoint_addr_within_range (CORE_ADDR, CORE_ADDR, int) override;
141 int can_use_hw_breakpoint (enum bptype, int, int) override;
143 int insert_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
145 int remove_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
147 int region_ok_for_hw_watchpoint (CORE_ADDR, int) override;
149 int insert_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
150 struct expression *) override;
152 int remove_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
153 struct expression *) override;
155 void kill () override;
157 void load (const char *, int) override;
159 void mourn_inferior () override;
161 void pass_signals (int, unsigned char *) override;
163 int set_syscall_catchpoint (int, bool, int,
164 gdb::array_view<const int>) override;
166 void program_signals (int, unsigned char *) override;
168 int thread_alive (ptid_t ptid) override;
170 const char *thread_name (struct thread_info *) override;
172 void update_thread_list () override;
174 const char *pid_to_str (ptid_t) override;
176 const char *extra_thread_info (struct thread_info *) override;
178 ptid_t get_ada_task_ptid (long lwp, long thread) override;
180 thread_info *thread_handle_to_thread_info (const gdb_byte *thread_handle,
182 inferior *inf) override;
184 void stop (ptid_t) override;
186 void interrupt () override;
188 void pass_ctrlc () override;
190 enum target_xfer_status xfer_partial (enum target_object object,
193 const gdb_byte *writebuf,
194 ULONGEST offset, ULONGEST len,
195 ULONGEST *xfered_len) override;
197 ULONGEST get_memory_xfer_limit () override;
199 void rcmd (const char *command, struct ui_file *output) override;
201 char *pid_to_exec_file (int pid) override;
203 void log_command (const char *cmd) override
205 serial_log_command (this, cmd);
208 CORE_ADDR get_thread_local_address (ptid_t ptid,
209 CORE_ADDR load_module_addr,
210 CORE_ADDR offset) override;
212 int has_all_memory () override { return default_child_has_all_memory (); }
213 int has_memory () override { return default_child_has_memory (); }
214 int has_stack () override { return default_child_has_stack (); }
215 int has_registers () override { return default_child_has_registers (); }
216 int has_execution (ptid_t ptid) override { return default_child_has_execution (ptid); }
218 int can_execute_reverse () override;
220 std::vector<mem_region> memory_map () override;
222 void flash_erase (ULONGEST address, LONGEST length) override;
224 void flash_done () override;
226 const struct target_desc *read_description () override;
228 int search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
229 const gdb_byte *pattern, ULONGEST pattern_len,
230 CORE_ADDR *found_addrp) override;
232 int can_async_p () override;
234 int is_async_p () override;
236 void async (int) override;
238 void thread_events (int) override;
240 int can_do_single_step () override;
242 void terminal_inferior () override;
244 void terminal_ours () override;
246 int supports_non_stop () override;
248 int supports_multi_process () override;
250 int supports_disable_randomization () override;
252 int filesystem_is_local () override;
255 int fileio_open (struct inferior *inf, const char *filename,
256 int flags, int mode, int warn_if_slow,
257 int *target_errno) override;
259 int fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
260 ULONGEST offset, int *target_errno) override;
262 int fileio_pread (int fd, gdb_byte *read_buf, int len,
263 ULONGEST offset, int *target_errno) override;
265 int fileio_fstat (int fd, struct stat *sb, int *target_errno) override;
267 int fileio_close (int fd, int *target_errno) override;
269 int fileio_unlink (struct inferior *inf,
270 const char *filename,
271 int *target_errno) override;
273 gdb::optional<std::string>
274 fileio_readlink (struct inferior *inf,
275 const char *filename,
276 int *target_errno) override;
278 int supports_enable_disable_tracepoint () override;
280 int supports_string_tracing () override;
282 int supports_evaluation_of_breakpoint_conditions () override;
284 int can_run_breakpoint_commands () override;
286 void trace_init () override;
288 void download_tracepoint (struct bp_location *location) override;
290 int can_download_tracepoint () override;
292 void download_trace_state_variable (const trace_state_variable &tsv) override;
294 void enable_tracepoint (struct bp_location *location) override;
296 void disable_tracepoint (struct bp_location *location) override;
298 void trace_set_readonly_regions () override;
300 void trace_start () override;
302 int get_trace_status (struct trace_status *ts) override;
304 void get_tracepoint_status (struct breakpoint *tp, struct uploaded_tp *utp)
307 void trace_stop () override;
309 int trace_find (enum trace_find_type type, int num,
310 CORE_ADDR addr1, CORE_ADDR addr2, int *tpp) override;
312 int get_trace_state_variable_value (int tsv, LONGEST *val) override;
314 int save_trace_data (const char *filename) override;
316 int upload_tracepoints (struct uploaded_tp **utpp) override;
318 int upload_trace_state_variables (struct uploaded_tsv **utsvp) override;
320 LONGEST get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len) override;
322 int get_min_fast_tracepoint_insn_len () override;
324 void set_disconnected_tracing (int val) override;
326 void set_circular_trace_buffer (int val) override;
328 void set_trace_buffer_size (LONGEST val) override;
330 int set_trace_notes (const char *user, const char *notes,
331 const char *stopnotes) override;
333 int core_of_thread (ptid_t ptid) override;
335 int verify_memory (const gdb_byte *data,
336 CORE_ADDR memaddr, ULONGEST size) override;
339 int get_tib_address (ptid_t ptid, CORE_ADDR *addr) override;
341 void set_permissions () override;
343 bool static_tracepoint_marker_at (CORE_ADDR,
344 struct static_tracepoint_marker *marker)
347 std::vector<static_tracepoint_marker>
348 static_tracepoint_markers_by_strid (const char *id) override;
350 traceframe_info_up traceframe_info () override;
352 int use_agent (int use) override;
353 int can_use_agent () override;
355 struct btrace_target_info *enable_btrace (ptid_t ptid,
356 const struct btrace_config *conf) override;
358 void disable_btrace (struct btrace_target_info *tinfo) override;
360 void teardown_btrace (struct btrace_target_info *tinfo) override;
362 enum btrace_error read_btrace (struct btrace_data *data,
363 struct btrace_target_info *btinfo,
364 enum btrace_read_type type) override;
366 const struct btrace_config *btrace_conf (const struct btrace_target_info *) override;
367 int augmented_libraries_svr4_read () override;
368 int follow_fork (int, int) override;
369 void follow_exec (struct inferior *, char *) override;
370 int insert_fork_catchpoint (int) override;
371 int remove_fork_catchpoint (int) override;
372 int insert_vfork_catchpoint (int) override;
373 int remove_vfork_catchpoint (int) override;
374 int insert_exec_catchpoint (int) override;
375 int remove_exec_catchpoint (int) override;
376 enum exec_direction_kind execution_direction () override;
379 void open_1 (const char *name, int from_tty, int extended_p);
380 void start_remote (int from_tty, int extended_p);
383 /* Set up the extended remote target by extending the standard remote
384 target and adding to it. */
386 class extended_remote_target final : public remote_target
389 const char *shortname () override
390 { return "extended-remote"; }
392 const char *longname () override
393 { return _("Extended remote serial target in gdb-specific protocol"); }
395 void open (const char *, int) override;
397 bool can_create_inferior () override { return true; }
398 void create_inferior (const char *, const std::string &,
399 char **, int) override;
401 void detach (inferior *, int) override;
403 bool can_attach () override { return true; }
404 void attach (const char *, int) override;
406 void post_attach (int) override;
407 int supports_disable_randomization () override;
410 /* Per-program-space data key. */
411 static const struct program_space_data *remote_pspace_data;
413 /* The variable registered as the control variable used by the
414 remote exec-file commands. While the remote exec-file setting is
415 per-program-space, the set/show machinery uses this as the
416 location of the remote exec-file value. */
417 static char *remote_exec_file_var;
419 /* The size to align memory write packets, when practical. The protocol
420 does not guarantee any alignment, and gdb will generate short
421 writes and unaligned writes, but even as a best-effort attempt this
422 can improve bulk transfers. For instance, if a write is misaligned
423 relative to the target's data bus, the stub may need to make an extra
424 round trip fetching data from the target. This doesn't make a
425 huge difference, but it's easy to do, so we try to be helpful.
427 The alignment chosen is arbitrary; usually data bus width is
428 important here, not the possibly larger cache line size. */
429 enum { REMOTE_ALIGN_WRITES = 16 };
431 /* Prototypes for local functions. */
432 static int getpkt_sane (char **buf, long *sizeof_buf, int forever);
433 static int getpkt_or_notif_sane (char **buf, long *sizeof_buf,
434 int forever, int *is_notif);
438 static int remote_vkill (int pid, struct remote_state *rs);
440 static void remote_kill_k (void);
442 static int readchar (int timeout);
444 static void remote_serial_write (const char *str, int len);
446 static void interrupt_query (void);
448 static void set_general_thread (ptid_t ptid);
449 static void set_continue_thread (ptid_t ptid);
451 static void get_offsets (void);
453 static void skip_frame (void);
455 static long read_frame (char **buf_p, long *sizeof_buf);
457 static int hexnumlen (ULONGEST num);
459 static int stubhex (int ch);
461 static int hexnumstr (char *, ULONGEST);
463 static int hexnumnstr (char *, ULONGEST, int);
465 static CORE_ADDR remote_address_masked (CORE_ADDR);
467 static void print_packet (const char *);
469 static int stub_unpack_int (char *buff, int fieldlength);
471 static ptid_t remote_current_thread (ptid_t oldptid);
473 static int putpkt_binary (const char *buf, int cnt);
475 static void check_binary_download (CORE_ADDR addr);
477 struct packet_config;
479 static void show_packet_config_cmd (struct packet_config *config);
481 static void show_remote_protocol_packet_cmd (struct ui_file *file,
483 struct cmd_list_element *c,
486 static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
487 static ptid_t read_ptid (const char *buf, const char **obuf);
489 static void remote_query_supported (void);
491 static void remote_check_symbols (void);
494 static void stop_reply_xfree (struct stop_reply *);
495 static void remote_parse_stop_reply (char *, struct stop_reply *);
496 static void push_stop_reply (struct stop_reply *);
497 static void discard_pending_stop_replies_in_queue (struct remote_state *);
498 static int peek_stop_reply (ptid_t ptid);
500 struct threads_listing_context;
501 static void remove_new_fork_children (struct threads_listing_context *);
503 static void remote_async_inferior_event_handler (gdb_client_data);
505 static int remote_read_description_p (struct target_ops *target);
507 static void remote_console_output (char *msg);
509 static void remote_btrace_reset (void);
511 static void remote_btrace_maybe_reopen (void);
513 static int stop_reply_queue_length (void);
515 static void readahead_cache_invalidate (void);
517 static void remote_unpush_and_throw (void);
519 static struct remote_state *get_remote_state (void);
523 static struct cmd_list_element *remote_cmdlist;
525 /* For "set remote" and "show remote". */
527 static struct cmd_list_element *remote_set_cmdlist;
528 static struct cmd_list_element *remote_show_cmdlist;
530 /* Stub vCont actions support.
532 Each field is a boolean flag indicating whether the stub reports
533 support for the corresponding action. */
535 struct vCont_action_support
550 /* Controls whether GDB is willing to use range stepping. */
552 static int use_range_stepping = 1;
554 #define OPAQUETHREADBYTES 8
556 /* a 64 bit opaque identifier */
557 typedef unsigned char threadref[OPAQUETHREADBYTES];
559 /* About this many threadisds fit in a packet. */
561 #define MAXTHREADLISTRESULTS 32
563 /* The max number of chars in debug output. The rest of chars are
566 #define REMOTE_DEBUG_MAX_CHAR 512
568 /* Data for the vFile:pread readahead cache. */
570 struct readahead_cache
572 /* The file descriptor for the file that is being cached. -1 if the
576 /* The offset into the file that the cache buffer corresponds
580 /* The buffer holding the cache contents. */
582 /* The buffer's size. We try to read as much as fits into a packet
586 /* Cache hit and miss counters. */
591 /* Description of the remote protocol state for the currently
592 connected target. This is per-target state, and independent of the
593 selected architecture. */
597 /* A buffer to use for incoming packets, and its current size. The
598 buffer is grown dynamically for larger incoming packets.
599 Outgoing packets may also be constructed in this buffer.
600 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
601 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
606 /* True if we're going through initial connection setup (finding out
607 about the remote side's threads, relocating symbols, etc.). */
610 /* If we negotiated packet size explicitly (and thus can bypass
611 heuristics for the largest packet size that will not overflow
612 a buffer in the stub), this will be set to that packet size.
613 Otherwise zero, meaning to use the guessed size. */
614 long explicit_packet_size;
616 /* remote_wait is normally called when the target is running and
617 waits for a stop reply packet. But sometimes we need to call it
618 when the target is already stopped. We can send a "?" packet
619 and have remote_wait read the response. Or, if we already have
620 the response, we can stash it in BUF and tell remote_wait to
621 skip calling getpkt. This flag is set when BUF contains a
622 stop reply packet and the target is not waiting. */
623 int cached_wait_status;
625 /* True, if in no ack mode. That is, neither GDB nor the stub will
626 expect acks from each other. The connection is assumed to be
630 /* True if we're connected in extended remote mode. */
633 /* True if we resumed the target and we're waiting for the target to
634 stop. In the mean time, we can't start another command/query.
635 The remote server wouldn't be ready to process it, so we'd
636 timeout waiting for a reply that would never come and eventually
637 we'd close the connection. This can happen in asynchronous mode
638 because we allow GDB commands while the target is running. */
639 int waiting_for_stop_reply;
641 /* The status of the stub support for the various vCont actions. */
642 struct vCont_action_support supports_vCont;
644 /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
645 responded to that. */
648 /* True if we saw a Ctrl-C while reading or writing from/to the
649 remote descriptor. At that point it is not safe to send a remote
650 interrupt packet, so we instead remember we saw the Ctrl-C and
651 process it once we're done with sending/receiving the current
652 packet, which should be shortly. If however that takes too long,
653 and the user presses Ctrl-C again, we offer to disconnect. */
654 int got_ctrlc_during_io;
656 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
657 remote_open knows that we don't have a file open when the program
659 struct serial *remote_desc;
661 /* These are the threads which we last sent to the remote system. The
662 TID member will be -1 for all or -2 for not sent yet. */
663 ptid_t general_thread;
664 ptid_t continue_thread;
666 /* This is the traceframe which we last selected on the remote system.
667 It will be -1 if no traceframe is selected. */
668 int remote_traceframe_number;
670 char *last_pass_packet;
672 /* The last QProgramSignals packet sent to the target. We bypass
673 sending a new program signals list down to the target if the new
674 packet is exactly the same as the last we sent. IOW, we only let
675 the target know about program signals list changes. */
676 char *last_program_signals_packet;
678 enum gdb_signal last_sent_signal;
682 /* The execution direction of the last resume we got. */
683 enum exec_direction_kind last_resume_exec_dir;
685 char *finished_object;
686 char *finished_annex;
687 ULONGEST finished_offset;
689 /* Should we try the 'ThreadInfo' query packet?
691 This variable (NOT available to the user: auto-detect only!)
692 determines whether GDB will use the new, simpler "ThreadInfo"
693 query or the older, more complex syntax for thread queries.
694 This is an auto-detect variable (set to true at each connect,
695 and set to false when the target fails to recognize it). */
696 int use_threadinfo_query;
697 int use_threadextra_query;
699 threadref echo_nextthread;
700 threadref nextthread;
701 threadref resultthreadlist[MAXTHREADLISTRESULTS];
703 /* The state of remote notification. */
704 struct remote_notif_state *notif_state;
706 /* The branch trace configuration. */
707 struct btrace_config btrace_config;
709 /* The argument to the last "vFile:setfs:" packet we sent, used
710 to avoid sending repeated unnecessary "vFile:setfs:" packets.
711 Initialized to -1 to indicate that no "vFile:setfs:" packet
712 has yet been sent. */
715 /* A readahead cache for vFile:pread. Often, reading a binary
716 involves a sequence of small reads. E.g., when parsing an ELF
717 file. A readahead cache helps mostly the case of remote
718 debugging on a connection with higher latency, due to the
719 request/reply nature of the RSP. We only cache data for a single
720 file descriptor at a time. */
721 struct readahead_cache readahead_cache;
724 /* Private data that we'll store in (struct thread_info)->priv. */
725 struct remote_thread_info : public private_thread_info
731 /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
732 sequence of bytes. */
733 gdb::byte_vector thread_handle;
735 /* Whether the target stopped for a breakpoint/watchpoint. */
736 enum target_stop_reason stop_reason = TARGET_STOPPED_BY_NO_REASON;
738 /* This is set to the data address of the access causing the target
739 to stop for a watchpoint. */
740 CORE_ADDR watch_data_address = 0;
742 /* Fields used by the vCont action coalescing implemented in
743 remote_resume / remote_commit_resume. remote_resume stores each
744 thread's last resume request in these fields, so that a later
745 remote_commit_resume knows which is the proper action for this
746 thread to include in the vCont packet. */
748 /* True if the last target_resume call for this thread was a step
749 request, false if a continue request. */
750 int last_resume_step = 0;
752 /* The signal specified in the last target_resume call for this
754 gdb_signal last_resume_sig = GDB_SIGNAL_0;
756 /* Whether this thread was already vCont-resumed on the remote
758 int vcont_resumed = 0;
761 /* This data could be associated with a target, but we do not always
762 have access to the current target when we need it, so for now it is
763 static. This will be fine for as long as only one target is in use
765 static struct remote_state *remote_state;
767 static struct remote_state *
768 get_remote_state_raw (void)
773 /* Allocate a new struct remote_state with xmalloc, initialize it, and
776 static struct remote_state *
777 new_remote_state (void)
779 struct remote_state *result = XCNEW (struct remote_state);
781 /* The default buffer size is unimportant; it will be expanded
782 whenever a larger buffer is needed. */
783 result->buf_size = 400;
784 result->buf = (char *) xmalloc (result->buf_size);
785 result->remote_traceframe_number = -1;
786 result->last_sent_signal = GDB_SIGNAL_0;
787 result->last_resume_exec_dir = EXEC_FORWARD;
793 /* Description of the remote protocol for a given architecture. */
797 long offset; /* Offset into G packet. */
798 long regnum; /* GDB's internal register number. */
799 LONGEST pnum; /* Remote protocol register number. */
800 int in_g_packet; /* Always part of G packet. */
801 /* long size in bytes; == register_size (target_gdbarch (), regnum);
803 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
807 struct remote_arch_state
809 /* Description of the remote protocol registers. */
810 long sizeof_g_packet;
812 /* Description of the remote protocol registers indexed by REGNUM
813 (making an array gdbarch_num_regs in size). */
814 struct packet_reg *regs;
816 /* This is the size (in chars) of the first response to the ``g''
817 packet. It is used as a heuristic when determining the maximum
818 size of memory-read and memory-write packets. A target will
819 typically only reserve a buffer large enough to hold the ``g''
820 packet. The size does not include packet overhead (headers and
822 long actual_register_packet_size;
824 /* This is the maximum size (in chars) of a non read/write packet.
825 It is also used as a cap on the size of read/write packets. */
826 long remote_packet_size;
829 /* Utility: generate error from an incoming stub packet. */
831 trace_error (char *buf)
834 return; /* not an error msg */
837 case '1': /* malformed packet error */
838 if (*++buf == '0') /* general case: */
839 error (_("remote.c: error in outgoing packet."));
841 error (_("remote.c: error in outgoing packet at field #%ld."),
842 strtol (buf, NULL, 16));
844 error (_("Target returns error code '%s'."), buf);
848 /* Utility: wait for reply from stub, while accepting "O" packets. */
851 remote_get_noisy_reply ()
853 struct remote_state *rs = get_remote_state ();
855 do /* Loop on reply from remote stub. */
859 QUIT; /* Allow user to bail out with ^C. */
860 getpkt (&rs->buf, &rs->buf_size, 0);
864 else if (startswith (buf, "qRelocInsn:"))
867 CORE_ADDR from, to, org_to;
869 int adjusted_size = 0;
872 p = buf + strlen ("qRelocInsn:");
873 pp = unpack_varlen_hex (p, &ul);
875 error (_("invalid qRelocInsn packet: %s"), buf);
879 unpack_varlen_hex (p, &ul);
886 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
889 CATCH (ex, RETURN_MASK_ALL)
891 if (ex.error == MEMORY_ERROR)
893 /* Propagate memory errors silently back to the
894 target. The stub may have limited the range of
895 addresses we can write to, for example. */
899 /* Something unexpectedly bad happened. Be verbose
900 so we can tell what, and propagate the error back
901 to the stub, so it doesn't get stuck waiting for
903 exception_fprintf (gdb_stderr, ex,
904 _("warning: relocating instruction: "));
912 adjusted_size = to - org_to;
914 xsnprintf (buf, rs->buf_size, "qRelocInsn:%x", adjusted_size);
918 else if (buf[0] == 'O' && buf[1] != 'K')
919 remote_console_output (buf + 1); /* 'O' message from stub */
921 return buf; /* Here's the actual reply. */
926 /* Handle for retreving the remote protocol data from gdbarch. */
927 static struct gdbarch_data *remote_gdbarch_data_handle;
929 static struct remote_arch_state *
930 get_remote_arch_state (struct gdbarch *gdbarch)
932 gdb_assert (gdbarch != NULL);
933 return ((struct remote_arch_state *)
934 gdbarch_data (gdbarch, remote_gdbarch_data_handle));
937 /* Fetch the global remote target state. */
939 static struct remote_state *
940 get_remote_state (void)
942 /* Make sure that the remote architecture state has been
943 initialized, because doing so might reallocate rs->buf. Any
944 function which calls getpkt also needs to be mindful of changes
945 to rs->buf, but this call limits the number of places which run
947 get_remote_arch_state (target_gdbarch ());
949 return get_remote_state_raw ();
952 /* Cleanup routine for the remote module's pspace data. */
955 remote_pspace_data_cleanup (struct program_space *pspace, void *arg)
957 char *remote_exec_file = (char *) arg;
959 xfree (remote_exec_file);
962 /* Fetch the remote exec-file from the current program space. */
965 get_remote_exec_file (void)
967 char *remote_exec_file;
970 = (char *) program_space_data (current_program_space,
972 if (remote_exec_file == NULL)
975 return remote_exec_file;
978 /* Set the remote exec file for PSPACE. */
981 set_pspace_remote_exec_file (struct program_space *pspace,
982 char *remote_exec_file)
984 char *old_file = (char *) program_space_data (pspace, remote_pspace_data);
987 set_program_space_data (pspace, remote_pspace_data,
988 xstrdup (remote_exec_file));
991 /* The "set/show remote exec-file" set command hook. */
994 set_remote_exec_file (const char *ignored, int from_tty,
995 struct cmd_list_element *c)
997 gdb_assert (remote_exec_file_var != NULL);
998 set_pspace_remote_exec_file (current_program_space, remote_exec_file_var);
1001 /* The "set/show remote exec-file" show command hook. */
1004 show_remote_exec_file (struct ui_file *file, int from_tty,
1005 struct cmd_list_element *cmd, const char *value)
1007 fprintf_filtered (file, "%s\n", remote_exec_file_var);
1011 compare_pnums (const void *lhs_, const void *rhs_)
1013 const struct packet_reg * const *lhs
1014 = (const struct packet_reg * const *) lhs_;
1015 const struct packet_reg * const *rhs
1016 = (const struct packet_reg * const *) rhs_;
1018 if ((*lhs)->pnum < (*rhs)->pnum)
1020 else if ((*lhs)->pnum == (*rhs)->pnum)
1027 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
1029 int regnum, num_remote_regs, offset;
1030 struct packet_reg **remote_regs;
1032 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
1034 struct packet_reg *r = ®s[regnum];
1036 if (register_size (gdbarch, regnum) == 0)
1037 /* Do not try to fetch zero-sized (placeholder) registers. */
1040 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
1045 /* Define the g/G packet format as the contents of each register
1046 with a remote protocol number, in order of ascending protocol
1049 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
1050 for (num_remote_regs = 0, regnum = 0;
1051 regnum < gdbarch_num_regs (gdbarch);
1053 if (regs[regnum].pnum != -1)
1054 remote_regs[num_remote_regs++] = ®s[regnum];
1056 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
1059 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
1061 remote_regs[regnum]->in_g_packet = 1;
1062 remote_regs[regnum]->offset = offset;
1063 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
1069 /* Given the architecture described by GDBARCH, return the remote
1070 protocol register's number and the register's offset in the g/G
1071 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
1072 If the target does not have a mapping for REGNUM, return false,
1073 otherwise, return true. */
1076 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
1077 int *pnum, int *poffset)
1079 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
1081 std::vector<packet_reg> regs (gdbarch_num_regs (gdbarch));
1083 map_regcache_remote_table (gdbarch, regs.data ());
1085 *pnum = regs[regnum].pnum;
1086 *poffset = regs[regnum].offset;
1092 init_remote_state (struct gdbarch *gdbarch)
1094 struct remote_state *rs = get_remote_state_raw ();
1095 struct remote_arch_state *rsa;
1097 rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
1099 /* Use the architecture to build a regnum<->pnum table, which will be
1100 1:1 unless a feature set specifies otherwise. */
1101 rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
1102 gdbarch_num_regs (gdbarch),
1105 /* Record the maximum possible size of the g packet - it may turn out
1107 rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
1109 /* Default maximum number of characters in a packet body. Many
1110 remote stubs have a hardwired buffer size of 400 bytes
1111 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
1112 as the maximum packet-size to ensure that the packet and an extra
1113 NUL character can always fit in the buffer. This stops GDB
1114 trashing stubs that try to squeeze an extra NUL into what is
1115 already a full buffer (As of 1999-12-04 that was most stubs). */
1116 rsa->remote_packet_size = 400 - 1;
1118 /* This one is filled in when a ``g'' packet is received. */
1119 rsa->actual_register_packet_size = 0;
1121 /* Should rsa->sizeof_g_packet needs more space than the
1122 default, adjust the size accordingly. Remember that each byte is
1123 encoded as two characters. 32 is the overhead for the packet
1124 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
1125 (``$NN:G...#NN'') is a better guess, the below has been padded a
1127 if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
1128 rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
1130 /* Make sure that the packet buffer is plenty big enough for
1131 this architecture. */
1132 if (rs->buf_size < rsa->remote_packet_size)
1134 rs->buf_size = 2 * rsa->remote_packet_size;
1135 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
1141 /* Return the current allowed size of a remote packet. This is
1142 inferred from the current architecture, and should be used to
1143 limit the length of outgoing packets. */
1145 get_remote_packet_size (void)
1147 struct remote_state *rs = get_remote_state ();
1148 remote_arch_state *rsa = get_remote_arch_state (target_gdbarch ());
1150 if (rs->explicit_packet_size)
1151 return rs->explicit_packet_size;
1153 return rsa->remote_packet_size;
1156 static struct packet_reg *
1157 packet_reg_from_regnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1160 if (regnum < 0 && regnum >= gdbarch_num_regs (gdbarch))
1164 struct packet_reg *r = &rsa->regs[regnum];
1166 gdb_assert (r->regnum == regnum);
1171 static struct packet_reg *
1172 packet_reg_from_pnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1177 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
1179 struct packet_reg *r = &rsa->regs[i];
1181 if (r->pnum == pnum)
1187 static remote_target remote_ops;
1189 static extended_remote_target extended_remote_ops;
1191 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
1192 ``forever'' still use the normal timeout mechanism. This is
1193 currently used by the ASYNC code to guarentee that target reads
1194 during the initial connect always time-out. Once getpkt has been
1195 modified to return a timeout indication and, in turn
1196 remote_wait()/wait_for_inferior() have gained a timeout parameter
1197 this can go away. */
1198 static int wait_forever_enabled_p = 1;
1200 /* Allow the user to specify what sequence to send to the remote
1201 when he requests a program interruption: Although ^C is usually
1202 what remote systems expect (this is the default, here), it is
1203 sometimes preferable to send a break. On other systems such
1204 as the Linux kernel, a break followed by g, which is Magic SysRq g
1205 is required in order to interrupt the execution. */
1206 const char interrupt_sequence_control_c[] = "Ctrl-C";
1207 const char interrupt_sequence_break[] = "BREAK";
1208 const char interrupt_sequence_break_g[] = "BREAK-g";
1209 static const char *const interrupt_sequence_modes[] =
1211 interrupt_sequence_control_c,
1212 interrupt_sequence_break,
1213 interrupt_sequence_break_g,
1216 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
1219 show_interrupt_sequence (struct ui_file *file, int from_tty,
1220 struct cmd_list_element *c,
1223 if (interrupt_sequence_mode == interrupt_sequence_control_c)
1224 fprintf_filtered (file,
1225 _("Send the ASCII ETX character (Ctrl-c) "
1226 "to the remote target to interrupt the "
1227 "execution of the program.\n"));
1228 else if (interrupt_sequence_mode == interrupt_sequence_break)
1229 fprintf_filtered (file,
1230 _("send a break signal to the remote target "
1231 "to interrupt the execution of the program.\n"));
1232 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
1233 fprintf_filtered (file,
1234 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
1235 "the remote target to interrupt the execution "
1236 "of Linux kernel.\n"));
1238 internal_error (__FILE__, __LINE__,
1239 _("Invalid value for interrupt_sequence_mode: %s."),
1240 interrupt_sequence_mode);
1243 /* This boolean variable specifies whether interrupt_sequence is sent
1244 to the remote target when gdb connects to it.
1245 This is mostly needed when you debug the Linux kernel: The Linux kernel
1246 expects BREAK g which is Magic SysRq g for connecting gdb. */
1247 static int interrupt_on_connect = 0;
1249 /* This variable is used to implement the "set/show remotebreak" commands.
1250 Since these commands are now deprecated in favor of "set/show remote
1251 interrupt-sequence", it no longer has any effect on the code. */
1252 static int remote_break;
1255 set_remotebreak (const char *args, int from_tty, struct cmd_list_element *c)
1258 interrupt_sequence_mode = interrupt_sequence_break;
1260 interrupt_sequence_mode = interrupt_sequence_control_c;
1264 show_remotebreak (struct ui_file *file, int from_tty,
1265 struct cmd_list_element *c,
1270 /* This variable sets the number of bits in an address that are to be
1271 sent in a memory ("M" or "m") packet. Normally, after stripping
1272 leading zeros, the entire address would be sent. This variable
1273 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
1274 initial implementation of remote.c restricted the address sent in
1275 memory packets to ``host::sizeof long'' bytes - (typically 32
1276 bits). Consequently, for 64 bit targets, the upper 32 bits of an
1277 address was never sent. Since fixing this bug may cause a break in
1278 some remote targets this variable is principly provided to
1279 facilitate backward compatibility. */
1281 static unsigned int remote_address_size;
1284 /* User configurable variables for the number of characters in a
1285 memory read/write packet. MIN (rsa->remote_packet_size,
1286 rsa->sizeof_g_packet) is the default. Some targets need smaller
1287 values (fifo overruns, et.al.) and some users need larger values
1288 (speed up transfers). The variables ``preferred_*'' (the user
1289 request), ``current_*'' (what was actually set) and ``forced_*''
1290 (Positive - a soft limit, negative - a hard limit). */
1292 struct memory_packet_config
1299 /* The default max memory-write-packet-size. The 16k is historical.
1300 (It came from older GDB's using alloca for buffers and the
1301 knowledge (folklore?) that some hosts don't cope very well with
1302 large alloca calls.) */
1303 #define DEFAULT_MAX_MEMORY_PACKET_SIZE 16384
1305 /* The minimum remote packet size for memory transfers. Ensures we
1306 can write at least one byte. */
1307 #define MIN_MEMORY_PACKET_SIZE 20
1309 /* Compute the current size of a read/write packet. Since this makes
1310 use of ``actual_register_packet_size'' the computation is dynamic. */
1313 get_memory_packet_size (struct memory_packet_config *config)
1315 struct remote_state *rs = get_remote_state ();
1316 remote_arch_state *rsa = get_remote_arch_state (target_gdbarch ());
1319 if (config->fixed_p)
1321 if (config->size <= 0)
1322 what_they_get = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1324 what_they_get = config->size;
1328 what_they_get = get_remote_packet_size ();
1329 /* Limit the packet to the size specified by the user. */
1330 if (config->size > 0
1331 && what_they_get > config->size)
1332 what_they_get = config->size;
1334 /* Limit it to the size of the targets ``g'' response unless we have
1335 permission from the stub to use a larger packet size. */
1336 if (rs->explicit_packet_size == 0
1337 && rsa->actual_register_packet_size > 0
1338 && what_they_get > rsa->actual_register_packet_size)
1339 what_they_get = rsa->actual_register_packet_size;
1341 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1342 what_they_get = MIN_MEMORY_PACKET_SIZE;
1344 /* Make sure there is room in the global buffer for this packet
1345 (including its trailing NUL byte). */
1346 if (rs->buf_size < what_they_get + 1)
1348 rs->buf_size = 2 * what_they_get;
1349 rs->buf = (char *) xrealloc (rs->buf, 2 * what_they_get);
1352 return what_they_get;
1355 /* Update the size of a read/write packet. If they user wants
1356 something really big then do a sanity check. */
1359 set_memory_packet_size (const char *args, struct memory_packet_config *config)
1361 int fixed_p = config->fixed_p;
1362 long size = config->size;
1365 error (_("Argument required (integer, `fixed' or `limited')."));
1366 else if (strcmp (args, "hard") == 0
1367 || strcmp (args, "fixed") == 0)
1369 else if (strcmp (args, "soft") == 0
1370 || strcmp (args, "limit") == 0)
1376 size = strtoul (args, &end, 0);
1378 error (_("Invalid %s (bad syntax)."), config->name);
1380 /* Instead of explicitly capping the size of a packet to or
1381 disallowing it, the user is allowed to set the size to
1382 something arbitrarily large. */
1385 /* So that the query shows the correct value. */
1387 size = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1390 if (fixed_p && !config->fixed_p)
1392 if (! query (_("The target may not be able to correctly handle a %s\n"
1393 "of %ld bytes. Change the packet size? "),
1394 config->name, size))
1395 error (_("Packet size not changed."));
1397 /* Update the config. */
1398 config->fixed_p = fixed_p;
1399 config->size = size;
1403 show_memory_packet_size (struct memory_packet_config *config)
1405 printf_filtered (_("The %s is %ld. "), config->name, config->size);
1406 if (config->fixed_p)
1407 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
1408 get_memory_packet_size (config));
1410 printf_filtered (_("Packets are limited to %ld bytes.\n"),
1411 get_memory_packet_size (config));
1414 static struct memory_packet_config memory_write_packet_config =
1416 "memory-write-packet-size",
1420 set_memory_write_packet_size (const char *args, int from_tty)
1422 set_memory_packet_size (args, &memory_write_packet_config);
1426 show_memory_write_packet_size (const char *args, int from_tty)
1428 show_memory_packet_size (&memory_write_packet_config);
1432 get_memory_write_packet_size (void)
1434 return get_memory_packet_size (&memory_write_packet_config);
1437 static struct memory_packet_config memory_read_packet_config =
1439 "memory-read-packet-size",
1443 set_memory_read_packet_size (const char *args, int from_tty)
1445 set_memory_packet_size (args, &memory_read_packet_config);
1449 show_memory_read_packet_size (const char *args, int from_tty)
1451 show_memory_packet_size (&memory_read_packet_config);
1455 get_memory_read_packet_size (void)
1457 long size = get_memory_packet_size (&memory_read_packet_config);
1459 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1460 extra buffer size argument before the memory read size can be
1461 increased beyond this. */
1462 if (size > get_remote_packet_size ())
1463 size = get_remote_packet_size ();
1468 /* Generic configuration support for packets the stub optionally
1469 supports. Allows the user to specify the use of the packet as well
1470 as allowing GDB to auto-detect support in the remote stub. */
1474 PACKET_SUPPORT_UNKNOWN = 0,
1479 struct packet_config
1484 /* If auto, GDB auto-detects support for this packet or feature,
1485 either through qSupported, or by trying the packet and looking
1486 at the response. If true, GDB assumes the target supports this
1487 packet. If false, the packet is disabled. Configs that don't
1488 have an associated command always have this set to auto. */
1489 enum auto_boolean detect;
1491 /* Does the target support this packet? */
1492 enum packet_support support;
1495 /* Analyze a packet's return value and update the packet config
1505 static enum packet_support packet_config_support (struct packet_config *config);
1506 static enum packet_support packet_support (int packet);
1509 show_packet_config_cmd (struct packet_config *config)
1511 const char *support = "internal-error";
1513 switch (packet_config_support (config))
1516 support = "enabled";
1518 case PACKET_DISABLE:
1519 support = "disabled";
1521 case PACKET_SUPPORT_UNKNOWN:
1522 support = "unknown";
1525 switch (config->detect)
1527 case AUTO_BOOLEAN_AUTO:
1528 printf_filtered (_("Support for the `%s' packet "
1529 "is auto-detected, currently %s.\n"),
1530 config->name, support);
1532 case AUTO_BOOLEAN_TRUE:
1533 case AUTO_BOOLEAN_FALSE:
1534 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1535 config->name, support);
1541 add_packet_config_cmd (struct packet_config *config, const char *name,
1542 const char *title, int legacy)
1548 config->name = name;
1549 config->title = title;
1550 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1552 show_doc = xstrprintf ("Show current use of remote "
1553 "protocol `%s' (%s) packet",
1555 /* set/show TITLE-packet {auto,on,off} */
1556 cmd_name = xstrprintf ("%s-packet", title);
1557 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
1558 &config->detect, set_doc,
1559 show_doc, NULL, /* help_doc */
1561 show_remote_protocol_packet_cmd,
1562 &remote_set_cmdlist, &remote_show_cmdlist);
1563 /* The command code copies the documentation strings. */
1566 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
1571 legacy_name = xstrprintf ("%s-packet", name);
1572 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1573 &remote_set_cmdlist);
1574 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1575 &remote_show_cmdlist);
1579 static enum packet_result
1580 packet_check_result (const char *buf)
1584 /* The stub recognized the packet request. Check that the
1585 operation succeeded. */
1587 && isxdigit (buf[1]) && isxdigit (buf[2])
1589 /* "Enn" - definitly an error. */
1590 return PACKET_ERROR;
1592 /* Always treat "E." as an error. This will be used for
1593 more verbose error messages, such as E.memtypes. */
1594 if (buf[0] == 'E' && buf[1] == '.')
1595 return PACKET_ERROR;
1597 /* The packet may or may not be OK. Just assume it is. */
1601 /* The stub does not support the packet. */
1602 return PACKET_UNKNOWN;
1605 static enum packet_result
1606 packet_ok (const char *buf, struct packet_config *config)
1608 enum packet_result result;
1610 if (config->detect != AUTO_BOOLEAN_TRUE
1611 && config->support == PACKET_DISABLE)
1612 internal_error (__FILE__, __LINE__,
1613 _("packet_ok: attempt to use a disabled packet"));
1615 result = packet_check_result (buf);
1620 /* The stub recognized the packet request. */
1621 if (config->support == PACKET_SUPPORT_UNKNOWN)
1624 fprintf_unfiltered (gdb_stdlog,
1625 "Packet %s (%s) is supported\n",
1626 config->name, config->title);
1627 config->support = PACKET_ENABLE;
1630 case PACKET_UNKNOWN:
1631 /* The stub does not support the packet. */
1632 if (config->detect == AUTO_BOOLEAN_AUTO
1633 && config->support == PACKET_ENABLE)
1635 /* If the stub previously indicated that the packet was
1636 supported then there is a protocol error. */
1637 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1638 config->name, config->title);
1640 else if (config->detect == AUTO_BOOLEAN_TRUE)
1642 /* The user set it wrong. */
1643 error (_("Enabled packet %s (%s) not recognized by stub"),
1644 config->name, config->title);
1648 fprintf_unfiltered (gdb_stdlog,
1649 "Packet %s (%s) is NOT supported\n",
1650 config->name, config->title);
1651 config->support = PACKET_DISABLE;
1672 PACKET_vFile_pwrite,
1674 PACKET_vFile_unlink,
1675 PACKET_vFile_readlink,
1678 PACKET_qXfer_features,
1679 PACKET_qXfer_exec_file,
1680 PACKET_qXfer_libraries,
1681 PACKET_qXfer_libraries_svr4,
1682 PACKET_qXfer_memory_map,
1683 PACKET_qXfer_spu_read,
1684 PACKET_qXfer_spu_write,
1685 PACKET_qXfer_osdata,
1686 PACKET_qXfer_threads,
1687 PACKET_qXfer_statictrace_read,
1688 PACKET_qXfer_traceframe_info,
1694 PACKET_QPassSignals,
1695 PACKET_QCatchSyscalls,
1696 PACKET_QProgramSignals,
1697 PACKET_QSetWorkingDir,
1698 PACKET_QStartupWithShell,
1699 PACKET_QEnvironmentHexEncoded,
1700 PACKET_QEnvironmentReset,
1701 PACKET_QEnvironmentUnset,
1703 PACKET_qSearch_memory,
1706 PACKET_QStartNoAckMode,
1708 PACKET_qXfer_siginfo_read,
1709 PACKET_qXfer_siginfo_write,
1712 /* Support for conditional tracepoints. */
1713 PACKET_ConditionalTracepoints,
1715 /* Support for target-side breakpoint conditions. */
1716 PACKET_ConditionalBreakpoints,
1718 /* Support for target-side breakpoint commands. */
1719 PACKET_BreakpointCommands,
1721 /* Support for fast tracepoints. */
1722 PACKET_FastTracepoints,
1724 /* Support for static tracepoints. */
1725 PACKET_StaticTracepoints,
1727 /* Support for installing tracepoints while a trace experiment is
1729 PACKET_InstallInTrace,
1733 PACKET_TracepointSource,
1736 PACKET_QDisableRandomization,
1738 PACKET_QTBuffer_size,
1742 PACKET_qXfer_btrace,
1744 /* Support for the QNonStop packet. */
1747 /* Support for the QThreadEvents packet. */
1748 PACKET_QThreadEvents,
1750 /* Support for multi-process extensions. */
1751 PACKET_multiprocess_feature,
1753 /* Support for enabling and disabling tracepoints while a trace
1754 experiment is running. */
1755 PACKET_EnableDisableTracepoints_feature,
1757 /* Support for collecting strings using the tracenz bytecode. */
1758 PACKET_tracenz_feature,
1760 /* Support for continuing to run a trace experiment while GDB is
1762 PACKET_DisconnectedTracing_feature,
1764 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
1765 PACKET_augmented_libraries_svr4_read_feature,
1767 /* Support for the qXfer:btrace-conf:read packet. */
1768 PACKET_qXfer_btrace_conf,
1770 /* Support for the Qbtrace-conf:bts:size packet. */
1771 PACKET_Qbtrace_conf_bts_size,
1773 /* Support for swbreak+ feature. */
1774 PACKET_swbreak_feature,
1776 /* Support for hwbreak+ feature. */
1777 PACKET_hwbreak_feature,
1779 /* Support for fork events. */
1780 PACKET_fork_event_feature,
1782 /* Support for vfork events. */
1783 PACKET_vfork_event_feature,
1785 /* Support for the Qbtrace-conf:pt:size packet. */
1786 PACKET_Qbtrace_conf_pt_size,
1788 /* Support for exec events. */
1789 PACKET_exec_event_feature,
1791 /* Support for query supported vCont actions. */
1792 PACKET_vContSupported,
1794 /* Support remote CTRL-C. */
1797 /* Support TARGET_WAITKIND_NO_RESUMED. */
1803 static struct packet_config remote_protocol_packets[PACKET_MAX];
1805 /* Returns the packet's corresponding "set remote foo-packet" command
1806 state. See struct packet_config for more details. */
1808 static enum auto_boolean
1809 packet_set_cmd_state (int packet)
1811 return remote_protocol_packets[packet].detect;
1814 /* Returns whether a given packet or feature is supported. This takes
1815 into account the state of the corresponding "set remote foo-packet"
1816 command, which may be used to bypass auto-detection. */
1818 static enum packet_support
1819 packet_config_support (struct packet_config *config)
1821 switch (config->detect)
1823 case AUTO_BOOLEAN_TRUE:
1824 return PACKET_ENABLE;
1825 case AUTO_BOOLEAN_FALSE:
1826 return PACKET_DISABLE;
1827 case AUTO_BOOLEAN_AUTO:
1828 return config->support;
1830 gdb_assert_not_reached (_("bad switch"));
1834 /* Same as packet_config_support, but takes the packet's enum value as
1837 static enum packet_support
1838 packet_support (int packet)
1840 struct packet_config *config = &remote_protocol_packets[packet];
1842 return packet_config_support (config);
1846 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1847 struct cmd_list_element *c,
1850 struct packet_config *packet;
1852 for (packet = remote_protocol_packets;
1853 packet < &remote_protocol_packets[PACKET_MAX];
1856 if (&packet->detect == c->var)
1858 show_packet_config_cmd (packet);
1862 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
1866 /* Should we try one of the 'Z' requests? */
1870 Z_PACKET_SOFTWARE_BP,
1871 Z_PACKET_HARDWARE_BP,
1878 /* For compatibility with older distributions. Provide a ``set remote
1879 Z-packet ...'' command that updates all the Z packet types. */
1881 static enum auto_boolean remote_Z_packet_detect;
1884 set_remote_protocol_Z_packet_cmd (const char *args, int from_tty,
1885 struct cmd_list_element *c)
1889 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1890 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
1894 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1895 struct cmd_list_element *c,
1900 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1902 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
1906 /* Returns true if the multi-process extensions are in effect. */
1909 remote_multi_process_p (struct remote_state *rs)
1911 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
1914 /* Returns true if fork events are supported. */
1917 remote_fork_event_p (struct remote_state *rs)
1919 return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
1922 /* Returns true if vfork events are supported. */
1925 remote_vfork_event_p (struct remote_state *rs)
1927 return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
1930 /* Returns true if exec events are supported. */
1933 remote_exec_event_p (struct remote_state *rs)
1935 return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
1938 /* Insert fork catchpoint target routine. If fork events are enabled
1939 then return success, nothing more to do. */
1942 remote_target::insert_fork_catchpoint (int pid)
1944 struct remote_state *rs = get_remote_state ();
1946 return !remote_fork_event_p (rs);
1949 /* Remove fork catchpoint target routine. Nothing to do, just
1953 remote_target::remove_fork_catchpoint (int pid)
1958 /* Insert vfork catchpoint target routine. If vfork events are enabled
1959 then return success, nothing more to do. */
1962 remote_target::insert_vfork_catchpoint (int pid)
1964 struct remote_state *rs = get_remote_state ();
1966 return !remote_vfork_event_p (rs);
1969 /* Remove vfork catchpoint target routine. Nothing to do, just
1973 remote_target::remove_vfork_catchpoint (int pid)
1978 /* Insert exec catchpoint target routine. If exec events are
1979 enabled, just return success. */
1982 remote_target::insert_exec_catchpoint (int pid)
1984 struct remote_state *rs = get_remote_state ();
1986 return !remote_exec_event_p (rs);
1989 /* Remove exec catchpoint target routine. Nothing to do, just
1993 remote_target::remove_exec_catchpoint (int pid)
1999 /* Asynchronous signal handle registered as event loop source for
2000 when we have pending events ready to be passed to the core. */
2002 static struct async_event_handler *remote_async_inferior_event_token;
2006 static ptid_t magic_null_ptid;
2007 static ptid_t not_sent_ptid;
2008 static ptid_t any_thread_ptid;
2010 /* Find out if the stub attached to PID (and hence GDB should offer to
2011 detach instead of killing it when bailing out). */
2014 remote_query_attached (int pid)
2016 struct remote_state *rs = get_remote_state ();
2017 size_t size = get_remote_packet_size ();
2019 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
2022 if (remote_multi_process_p (rs))
2023 xsnprintf (rs->buf, size, "qAttached:%x", pid);
2025 xsnprintf (rs->buf, size, "qAttached");
2028 getpkt (&rs->buf, &rs->buf_size, 0);
2030 switch (packet_ok (rs->buf,
2031 &remote_protocol_packets[PACKET_qAttached]))
2034 if (strcmp (rs->buf, "1") == 0)
2038 warning (_("Remote failure reply: %s"), rs->buf);
2040 case PACKET_UNKNOWN:
2047 /* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
2048 has been invented by GDB, instead of reported by the target. Since
2049 we can be connected to a remote system before before knowing about
2050 any inferior, mark the target with execution when we find the first
2051 inferior. If ATTACHED is 1, then we had just attached to this
2052 inferior. If it is 0, then we just created this inferior. If it
2053 is -1, then try querying the remote stub to find out if it had
2054 attached to the inferior or not. If TRY_OPEN_EXEC is true then
2055 attempt to open this inferior's executable as the main executable
2056 if no main executable is open already. */
2058 static struct inferior *
2059 remote_add_inferior (int fake_pid_p, int pid, int attached,
2062 struct inferior *inf;
2064 /* Check whether this process we're learning about is to be
2065 considered attached, or if is to be considered to have been
2066 spawned by the stub. */
2068 attached = remote_query_attached (pid);
2070 if (gdbarch_has_global_solist (target_gdbarch ()))
2072 /* If the target shares code across all inferiors, then every
2073 attach adds a new inferior. */
2074 inf = add_inferior (pid);
2076 /* ... and every inferior is bound to the same program space.
2077 However, each inferior may still have its own address
2079 inf->aspace = maybe_new_address_space ();
2080 inf->pspace = current_program_space;
2084 /* In the traditional debugging scenario, there's a 1-1 match
2085 between program/address spaces. We simply bind the inferior
2086 to the program space's address space. */
2087 inf = current_inferior ();
2088 inferior_appeared (inf, pid);
2091 inf->attach_flag = attached;
2092 inf->fake_pid_p = fake_pid_p;
2094 /* If no main executable is currently open then attempt to
2095 open the file that was executed to create this inferior. */
2096 if (try_open_exec && get_exec_file (0) == NULL)
2097 exec_file_locate_attach (pid, 0, 1);
2102 static remote_thread_info *get_remote_thread_info (thread_info *thread);
2104 /* Add thread PTID to GDB's thread list. Tag it as executing/running
2105 according to RUNNING. */
2108 remote_add_thread (ptid_t ptid, int running, int executing)
2110 struct remote_state *rs = get_remote_state ();
2111 struct thread_info *thread;
2113 /* GDB historically didn't pull threads in the initial connection
2114 setup. If the remote target doesn't even have a concept of
2115 threads (e.g., a bare-metal target), even if internally we
2116 consider that a single-threaded target, mentioning a new thread
2117 might be confusing to the user. Be silent then, preserving the
2118 age old behavior. */
2119 if (rs->starting_up)
2120 thread = add_thread_silent (ptid);
2122 thread = add_thread (ptid);
2124 get_remote_thread_info (thread)->vcont_resumed = executing;
2125 set_executing (ptid, executing);
2126 set_running (ptid, running);
2129 /* Come here when we learn about a thread id from the remote target.
2130 It may be the first time we hear about such thread, so take the
2131 opportunity to add it to GDB's thread list. In case this is the
2132 first time we're noticing its corresponding inferior, add it to
2133 GDB's inferior list as well. EXECUTING indicates whether the
2134 thread is (internally) executing or stopped. */
2137 remote_notice_new_inferior (ptid_t currthread, int executing)
2139 /* In non-stop mode, we assume new found threads are (externally)
2140 running until proven otherwise with a stop reply. In all-stop,
2141 we can only get here if all threads are stopped. */
2142 int running = target_is_non_stop_p () ? 1 : 0;
2144 /* If this is a new thread, add it to GDB's thread list.
2145 If we leave it up to WFI to do this, bad things will happen. */
2147 if (in_thread_list (currthread) && is_exited (currthread))
2149 /* We're seeing an event on a thread id we knew had exited.
2150 This has to be a new thread reusing the old id. Add it. */
2151 remote_add_thread (currthread, running, executing);
2155 if (!in_thread_list (currthread))
2157 struct inferior *inf = NULL;
2158 int pid = ptid_get_pid (currthread);
2160 if (ptid_is_pid (inferior_ptid)
2161 && pid == ptid_get_pid (inferior_ptid))
2163 /* inferior_ptid has no thread member yet. This can happen
2164 with the vAttach -> remote_wait,"TAAthread:" path if the
2165 stub doesn't support qC. This is the first stop reported
2166 after an attach, so this is the main thread. Update the
2167 ptid in the thread list. */
2168 if (in_thread_list (pid_to_ptid (pid)))
2169 thread_change_ptid (inferior_ptid, currthread);
2172 remote_add_thread (currthread, running, executing);
2173 inferior_ptid = currthread;
2178 if (ptid_equal (magic_null_ptid, inferior_ptid))
2180 /* inferior_ptid is not set yet. This can happen with the
2181 vRun -> remote_wait,"TAAthread:" path if the stub
2182 doesn't support qC. This is the first stop reported
2183 after an attach, so this is the main thread. Update the
2184 ptid in the thread list. */
2185 thread_change_ptid (inferior_ptid, currthread);
2189 /* When connecting to a target remote, or to a target
2190 extended-remote which already was debugging an inferior, we
2191 may not know about it yet. Add it before adding its child
2192 thread, so notifications are emitted in a sensible order. */
2193 if (!in_inferior_list (ptid_get_pid (currthread)))
2195 struct remote_state *rs = get_remote_state ();
2196 int fake_pid_p = !remote_multi_process_p (rs);
2198 inf = remote_add_inferior (fake_pid_p,
2199 ptid_get_pid (currthread), -1, 1);
2202 /* This is really a new thread. Add it. */
2203 remote_add_thread (currthread, running, executing);
2205 /* If we found a new inferior, let the common code do whatever
2206 it needs to with it (e.g., read shared libraries, insert
2207 breakpoints), unless we're just setting up an all-stop
2211 struct remote_state *rs = get_remote_state ();
2213 if (!rs->starting_up)
2214 notice_new_inferior (currthread, executing, 0);
2219 /* Return THREAD's private thread data, creating it if necessary. */
2221 static remote_thread_info *
2222 get_remote_thread_info (thread_info *thread)
2224 gdb_assert (thread != NULL);
2226 if (thread->priv == NULL)
2227 thread->priv.reset (new remote_thread_info);
2229 return static_cast<remote_thread_info *> (thread->priv.get ());
2232 /* Return PTID's private thread data, creating it if necessary. */
2234 static remote_thread_info *
2235 get_remote_thread_info (ptid_t ptid)
2237 struct thread_info *info = find_thread_ptid (ptid);
2239 return get_remote_thread_info (info);
2242 /* Call this function as a result of
2243 1) A halt indication (T packet) containing a thread id
2244 2) A direct query of currthread
2245 3) Successful execution of set thread */
2248 record_currthread (struct remote_state *rs, ptid_t currthread)
2250 rs->general_thread = currthread;
2253 /* If 'QPassSignals' is supported, tell the remote stub what signals
2254 it can simply pass through to the inferior without reporting. */
2257 remote_target::pass_signals (int numsigs, unsigned char *pass_signals)
2259 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
2261 char *pass_packet, *p;
2263 struct remote_state *rs = get_remote_state ();
2265 gdb_assert (numsigs < 256);
2266 for (i = 0; i < numsigs; i++)
2268 if (pass_signals[i])
2271 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
2272 strcpy (pass_packet, "QPassSignals:");
2273 p = pass_packet + strlen (pass_packet);
2274 for (i = 0; i < numsigs; i++)
2276 if (pass_signals[i])
2279 *p++ = tohex (i >> 4);
2280 *p++ = tohex (i & 15);
2289 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
2291 putpkt (pass_packet);
2292 getpkt (&rs->buf, &rs->buf_size, 0);
2293 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
2294 if (rs->last_pass_packet)
2295 xfree (rs->last_pass_packet);
2296 rs->last_pass_packet = pass_packet;
2299 xfree (pass_packet);
2303 /* If 'QCatchSyscalls' is supported, tell the remote stub
2304 to report syscalls to GDB. */
2307 remote_target::set_syscall_catchpoint (int pid, bool needed, int any_count,
2308 gdb::array_view<const int> syscall_counts)
2310 const char *catch_packet;
2311 enum packet_result result;
2314 if (packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2316 /* Not supported. */
2320 if (needed && any_count == 0)
2322 /* Count how many syscalls are to be caught. */
2323 for (size_t i = 0; i < syscall_counts.size (); i++)
2325 if (syscall_counts[i] != 0)
2332 fprintf_unfiltered (gdb_stdlog,
2333 "remote_set_syscall_catchpoint "
2334 "pid %d needed %d any_count %d n_sysno %d\n",
2335 pid, needed, any_count, n_sysno);
2338 std::string built_packet;
2341 /* Prepare a packet with the sysno list, assuming max 8+1
2342 characters for a sysno. If the resulting packet size is too
2343 big, fallback on the non-selective packet. */
2344 const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
2345 built_packet.reserve (maxpktsz);
2346 built_packet = "QCatchSyscalls:1";
2349 /* Add in each syscall to be caught. */
2350 for (size_t i = 0; i < syscall_counts.size (); i++)
2352 if (syscall_counts[i] != 0)
2353 string_appendf (built_packet, ";%zx", i);
2356 if (built_packet.size () > get_remote_packet_size ())
2358 /* catch_packet too big. Fallback to less efficient
2359 non selective mode, with GDB doing the filtering. */
2360 catch_packet = "QCatchSyscalls:1";
2363 catch_packet = built_packet.c_str ();
2366 catch_packet = "QCatchSyscalls:0";
2368 struct remote_state *rs = get_remote_state ();
2370 putpkt (catch_packet);
2371 getpkt (&rs->buf, &rs->buf_size, 0);
2372 result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_QCatchSyscalls]);
2373 if (result == PACKET_OK)
2379 /* If 'QProgramSignals' is supported, tell the remote stub what
2380 signals it should pass through to the inferior when detaching. */
2383 remote_target::program_signals (int numsigs, unsigned char *signals)
2385 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
2389 struct remote_state *rs = get_remote_state ();
2391 gdb_assert (numsigs < 256);
2392 for (i = 0; i < numsigs; i++)
2397 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
2398 strcpy (packet, "QProgramSignals:");
2399 p = packet + strlen (packet);
2400 for (i = 0; i < numsigs; i++)
2402 if (signal_pass_state (i))
2405 *p++ = tohex (i >> 4);
2406 *p++ = tohex (i & 15);
2415 if (!rs->last_program_signals_packet
2416 || strcmp (rs->last_program_signals_packet, packet) != 0)
2419 getpkt (&rs->buf, &rs->buf_size, 0);
2420 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
2421 xfree (rs->last_program_signals_packet);
2422 rs->last_program_signals_packet = packet;
2429 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
2430 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2431 thread. If GEN is set, set the general thread, if not, then set
2432 the step/continue thread. */
2434 set_thread (ptid_t ptid, int gen)
2436 struct remote_state *rs = get_remote_state ();
2437 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
2438 char *buf = rs->buf;
2439 char *endbuf = rs->buf + get_remote_packet_size ();
2441 if (ptid_equal (state, ptid))
2445 *buf++ = gen ? 'g' : 'c';
2446 if (ptid_equal (ptid, magic_null_ptid))
2447 xsnprintf (buf, endbuf - buf, "0");
2448 else if (ptid_equal (ptid, any_thread_ptid))
2449 xsnprintf (buf, endbuf - buf, "0");
2450 else if (ptid_equal (ptid, minus_one_ptid))
2451 xsnprintf (buf, endbuf - buf, "-1");
2453 write_ptid (buf, endbuf, ptid);
2455 getpkt (&rs->buf, &rs->buf_size, 0);
2457 rs->general_thread = ptid;
2459 rs->continue_thread = ptid;
2463 set_general_thread (ptid_t ptid)
2465 set_thread (ptid, 1);
2469 set_continue_thread (ptid_t ptid)
2471 set_thread (ptid, 0);
2474 /* Change the remote current process. Which thread within the process
2475 ends up selected isn't important, as long as it is the same process
2476 as what INFERIOR_PTID points to.
2478 This comes from that fact that there is no explicit notion of
2479 "selected process" in the protocol. The selected process for
2480 general operations is the process the selected general thread
2484 set_general_process (void)
2486 struct remote_state *rs = get_remote_state ();
2488 /* If the remote can't handle multiple processes, don't bother. */
2489 if (!remote_multi_process_p (rs))
2492 /* We only need to change the remote current thread if it's pointing
2493 at some other process. */
2494 if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
2495 set_general_thread (inferior_ptid);
2499 /* Return nonzero if this is the main thread that we made up ourselves
2500 to model non-threaded targets as single-threaded. */
2503 remote_thread_always_alive (ptid_t ptid)
2505 if (ptid_equal (ptid, magic_null_ptid))
2506 /* The main thread is always alive. */
2509 if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
2510 /* The main thread is always alive. This can happen after a
2511 vAttach, if the remote side doesn't support
2518 /* Return nonzero if the thread PTID is still alive on the remote
2522 remote_target::thread_alive (ptid_t ptid)
2524 struct remote_state *rs = get_remote_state ();
2527 /* Check if this is a thread that we made up ourselves to model
2528 non-threaded targets as single-threaded. */
2529 if (remote_thread_always_alive (ptid))
2533 endp = rs->buf + get_remote_packet_size ();
2536 write_ptid (p, endp, ptid);
2539 getpkt (&rs->buf, &rs->buf_size, 0);
2540 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
2543 /* Return a pointer to a thread name if we know it and NULL otherwise.
2544 The thread_info object owns the memory for the name. */
2547 remote_target::thread_name (struct thread_info *info)
2549 if (info->priv != NULL)
2551 const std::string &name = get_remote_thread_info (info)->name;
2552 return !name.empty () ? name.c_str () : NULL;
2558 /* About these extended threadlist and threadinfo packets. They are
2559 variable length packets but, the fields within them are often fixed
2560 length. They are redundent enough to send over UDP as is the
2561 remote protocol in general. There is a matching unit test module
2564 /* WARNING: This threadref data structure comes from the remote O.S.,
2565 libstub protocol encoding, and remote.c. It is not particularly
2568 /* Right now, the internal structure is int. We want it to be bigger.
2569 Plan to fix this. */
2571 typedef int gdb_threadref; /* Internal GDB thread reference. */
2573 /* gdb_ext_thread_info is an internal GDB data structure which is
2574 equivalent to the reply of the remote threadinfo packet. */
2576 struct gdb_ext_thread_info
2578 threadref threadid; /* External form of thread reference. */
2579 int active; /* Has state interesting to GDB?
2581 char display[256]; /* Brief state display, name,
2582 blocked/suspended. */
2583 char shortname[32]; /* To be used to name threads. */
2584 char more_display[256]; /* Long info, statistics, queue depth,
2588 /* The volume of remote transfers can be limited by submitting
2589 a mask containing bits specifying the desired information.
2590 Use a union of these values as the 'selection' parameter to
2591 get_thread_info. FIXME: Make these TAG names more thread specific. */
2593 #define TAG_THREADID 1
2594 #define TAG_EXISTS 2
2595 #define TAG_DISPLAY 4
2596 #define TAG_THREADNAME 8
2597 #define TAG_MOREDISPLAY 16
2599 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
2601 static char *unpack_nibble (char *buf, int *val);
2603 static char *unpack_byte (char *buf, int *value);
2605 static char *pack_int (char *buf, int value);
2607 static char *unpack_int (char *buf, int *value);
2609 static char *unpack_string (char *src, char *dest, int length);
2611 static char *pack_threadid (char *pkt, threadref *id);
2613 static char *unpack_threadid (char *inbuf, threadref *id);
2615 void int_to_threadref (threadref *id, int value);
2617 static int threadref_to_int (threadref *ref);
2619 static void copy_threadref (threadref *dest, threadref *src);
2621 static int threadmatch (threadref *dest, threadref *src);
2623 static char *pack_threadinfo_request (char *pkt, int mode,
2626 static int remote_unpack_thread_info_response (char *pkt,
2627 threadref *expectedref,
2628 struct gdb_ext_thread_info
2632 static int remote_get_threadinfo (threadref *threadid,
2633 int fieldset, /*TAG mask */
2634 struct gdb_ext_thread_info *info);
2636 static char *pack_threadlist_request (char *pkt, int startflag,
2638 threadref *nextthread);
2640 static int parse_threadlist_response (char *pkt,
2642 threadref *original_echo,
2643 threadref *resultlist,
2646 static int remote_get_threadlist (int startflag,
2647 threadref *nextthread,
2651 threadref *threadlist);
2653 typedef int (*rmt_thread_action) (threadref *ref, void *context);
2655 static int remote_threadlist_iterator (rmt_thread_action stepfunction,
2656 void *context, int looplimit);
2658 static int remote_newthread_step (threadref *ref, void *context);
2661 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
2662 buffer we're allowed to write to. Returns
2663 BUF+CHARACTERS_WRITTEN. */
2666 write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2669 struct remote_state *rs = get_remote_state ();
2671 if (remote_multi_process_p (rs))
2673 pid = ptid_get_pid (ptid);
2675 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2677 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2679 tid = ptid_get_lwp (ptid);
2681 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2683 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2688 /* Extract a PTID from BUF. If non-null, OBUF is set to one past the
2689 last parsed char. Returns null_ptid if no thread id is found, and
2690 throws an error if the thread id has an invalid format. */
2693 read_ptid (const char *buf, const char **obuf)
2695 const char *p = buf;
2697 ULONGEST pid = 0, tid = 0;
2701 /* Multi-process ptid. */
2702 pp = unpack_varlen_hex (p + 1, &pid);
2704 error (_("invalid remote ptid: %s"), p);
2707 pp = unpack_varlen_hex (p + 1, &tid);
2710 return ptid_build (pid, tid, 0);
2713 /* No multi-process. Just a tid. */
2714 pp = unpack_varlen_hex (p, &tid);
2716 /* Return null_ptid when no thread id is found. */
2724 /* Since the stub is not sending a process id, then default to
2725 what's in inferior_ptid, unless it's null at this point. If so,
2726 then since there's no way to know the pid of the reported
2727 threads, use the magic number. */
2728 if (ptid_equal (inferior_ptid, null_ptid))
2729 pid = ptid_get_pid (magic_null_ptid);
2731 pid = ptid_get_pid (inferior_ptid);
2735 return ptid_build (pid, tid, 0);
2741 if (ch >= 'a' && ch <= 'f')
2742 return ch - 'a' + 10;
2743 if (ch >= '0' && ch <= '9')
2745 if (ch >= 'A' && ch <= 'F')
2746 return ch - 'A' + 10;
2751 stub_unpack_int (char *buff, int fieldlength)
2758 nibble = stubhex (*buff++);
2762 retval = retval << 4;
2768 unpack_nibble (char *buf, int *val)
2770 *val = fromhex (*buf++);
2775 unpack_byte (char *buf, int *value)
2777 *value = stub_unpack_int (buf, 2);
2782 pack_int (char *buf, int value)
2784 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2785 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2786 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2787 buf = pack_hex_byte (buf, (value & 0xff));
2792 unpack_int (char *buf, int *value)
2794 *value = stub_unpack_int (buf, 8);
2798 #if 0 /* Currently unused, uncomment when needed. */
2799 static char *pack_string (char *pkt, char *string);
2802 pack_string (char *pkt, char *string)
2807 len = strlen (string);
2809 len = 200; /* Bigger than most GDB packets, junk??? */
2810 pkt = pack_hex_byte (pkt, len);
2814 if ((ch == '\0') || (ch == '#'))
2815 ch = '*'; /* Protect encapsulation. */
2820 #endif /* 0 (unused) */
2823 unpack_string (char *src, char *dest, int length)
2832 pack_threadid (char *pkt, threadref *id)
2835 unsigned char *altid;
2837 altid = (unsigned char *) id;
2838 limit = pkt + BUF_THREAD_ID_SIZE;
2840 pkt = pack_hex_byte (pkt, *altid++);
2846 unpack_threadid (char *inbuf, threadref *id)
2849 char *limit = inbuf + BUF_THREAD_ID_SIZE;
2852 altref = (char *) id;
2854 while (inbuf < limit)
2856 x = stubhex (*inbuf++);
2857 y = stubhex (*inbuf++);
2858 *altref++ = (x << 4) | y;
2863 /* Externally, threadrefs are 64 bits but internally, they are still
2864 ints. This is due to a mismatch of specifications. We would like
2865 to use 64bit thread references internally. This is an adapter
2869 int_to_threadref (threadref *id, int value)
2871 unsigned char *scan;
2873 scan = (unsigned char *) id;
2879 *scan++ = (value >> 24) & 0xff;
2880 *scan++ = (value >> 16) & 0xff;
2881 *scan++ = (value >> 8) & 0xff;
2882 *scan++ = (value & 0xff);
2886 threadref_to_int (threadref *ref)
2889 unsigned char *scan;
2895 value = (value << 8) | ((*scan++) & 0xff);
2900 copy_threadref (threadref *dest, threadref *src)
2903 unsigned char *csrc, *cdest;
2905 csrc = (unsigned char *) src;
2906 cdest = (unsigned char *) dest;
2913 threadmatch (threadref *dest, threadref *src)
2915 /* Things are broken right now, so just assume we got a match. */
2917 unsigned char *srcp, *destp;
2919 srcp = (char *) src;
2920 destp = (char *) dest;
2924 result &= (*srcp++ == *destp++) ? 1 : 0;
2931 threadid:1, # always request threadid
2938 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
2941 pack_threadinfo_request (char *pkt, int mode, threadref *id)
2943 *pkt++ = 'q'; /* Info Query */
2944 *pkt++ = 'P'; /* process or thread info */
2945 pkt = pack_int (pkt, mode); /* mode */
2946 pkt = pack_threadid (pkt, id); /* threadid */
2947 *pkt = '\0'; /* terminate */
2951 /* These values tag the fields in a thread info response packet. */
2952 /* Tagging the fields allows us to request specific fields and to
2953 add more fields as time goes by. */
2955 #define TAG_THREADID 1 /* Echo the thread identifier. */
2956 #define TAG_EXISTS 2 /* Is this process defined enough to
2957 fetch registers and its stack? */
2958 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
2959 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
2960 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
2964 remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2965 struct gdb_ext_thread_info *info)
2967 struct remote_state *rs = get_remote_state ();
2971 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
2974 /* info->threadid = 0; FIXME: implement zero_threadref. */
2976 info->display[0] = '\0';
2977 info->shortname[0] = '\0';
2978 info->more_display[0] = '\0';
2980 /* Assume the characters indicating the packet type have been
2982 pkt = unpack_int (pkt, &mask); /* arg mask */
2983 pkt = unpack_threadid (pkt, &ref);
2986 warning (_("Incomplete response to threadinfo request."));
2987 if (!threadmatch (&ref, expectedref))
2988 { /* This is an answer to a different request. */
2989 warning (_("ERROR RMT Thread info mismatch."));
2992 copy_threadref (&info->threadid, &ref);
2994 /* Loop on tagged fields , try to bail if somthing goes wrong. */
2996 /* Packets are terminated with nulls. */
2997 while ((pkt < limit) && mask && *pkt)
2999 pkt = unpack_int (pkt, &tag); /* tag */
3000 pkt = unpack_byte (pkt, &length); /* length */
3001 if (!(tag & mask)) /* Tags out of synch with mask. */
3003 warning (_("ERROR RMT: threadinfo tag mismatch."));
3007 if (tag == TAG_THREADID)
3011 warning (_("ERROR RMT: length of threadid is not 16."));
3015 pkt = unpack_threadid (pkt, &ref);
3016 mask = mask & ~TAG_THREADID;
3019 if (tag == TAG_EXISTS)
3021 info->active = stub_unpack_int (pkt, length);
3023 mask = mask & ~(TAG_EXISTS);
3026 warning (_("ERROR RMT: 'exists' length too long."));
3032 if (tag == TAG_THREADNAME)
3034 pkt = unpack_string (pkt, &info->shortname[0], length);
3035 mask = mask & ~TAG_THREADNAME;
3038 if (tag == TAG_DISPLAY)
3040 pkt = unpack_string (pkt, &info->display[0], length);
3041 mask = mask & ~TAG_DISPLAY;
3044 if (tag == TAG_MOREDISPLAY)
3046 pkt = unpack_string (pkt, &info->more_display[0], length);
3047 mask = mask & ~TAG_MOREDISPLAY;
3050 warning (_("ERROR RMT: unknown thread info tag."));
3051 break; /* Not a tag we know about. */
3057 remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
3058 struct gdb_ext_thread_info *info)
3060 struct remote_state *rs = get_remote_state ();
3063 pack_threadinfo_request (rs->buf, fieldset, threadid);
3065 getpkt (&rs->buf, &rs->buf_size, 0);
3067 if (rs->buf[0] == '\0')
3070 result = remote_unpack_thread_info_response (rs->buf + 2,
3075 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
3078 pack_threadlist_request (char *pkt, int startflag, int threadcount,
3079 threadref *nextthread)
3081 *pkt++ = 'q'; /* info query packet */
3082 *pkt++ = 'L'; /* Process LIST or threadLIST request */
3083 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
3084 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
3085 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
3090 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
3093 parse_threadlist_response (char *pkt, int result_limit,
3094 threadref *original_echo, threadref *resultlist,
3097 struct remote_state *rs = get_remote_state ();
3099 int count, resultcount, done;
3102 /* Assume the 'q' and 'M chars have been stripped. */
3103 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
3104 /* done parse past here */
3105 pkt = unpack_byte (pkt, &count); /* count field */
3106 pkt = unpack_nibble (pkt, &done);
3107 /* The first threadid is the argument threadid. */
3108 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
3109 while ((count-- > 0) && (pkt < limit))
3111 pkt = unpack_threadid (pkt, resultlist++);
3112 if (resultcount++ >= result_limit)
3120 /* Fetch the next batch of threads from the remote. Returns -1 if the
3121 qL packet is not supported, 0 on error and 1 on success. */
3124 remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
3125 int *done, int *result_count, threadref *threadlist)
3127 struct remote_state *rs = get_remote_state ();
3130 /* Trancate result limit to be smaller than the packet size. */
3131 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
3132 >= get_remote_packet_size ())
3133 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
3135 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
3137 getpkt (&rs->buf, &rs->buf_size, 0);
3138 if (*rs->buf == '\0')
3140 /* Packet not supported. */
3145 parse_threadlist_response (rs->buf + 2, result_limit,
3146 &rs->echo_nextthread, threadlist, done);
3148 if (!threadmatch (&rs->echo_nextthread, nextthread))
3150 /* FIXME: This is a good reason to drop the packet. */
3151 /* Possably, there is a duplicate response. */
3153 retransmit immediatly - race conditions
3154 retransmit after timeout - yes
3156 wait for packet, then exit
3158 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
3159 return 0; /* I choose simply exiting. */
3161 if (*result_count <= 0)
3165 warning (_("RMT ERROR : failed to get remote thread list."));
3168 return result; /* break; */
3170 if (*result_count > result_limit)
3173 warning (_("RMT ERROR: threadlist response longer than requested."));
3179 /* Fetch the list of remote threads, with the qL packet, and call
3180 STEPFUNCTION for each thread found. Stops iterating and returns 1
3181 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
3182 STEPFUNCTION returns false. If the packet is not supported,
3186 remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
3189 struct remote_state *rs = get_remote_state ();
3190 int done, i, result_count;
3198 if (loopcount++ > looplimit)
3201 warning (_("Remote fetch threadlist -infinite loop-."));
3204 result = remote_get_threadlist (startflag, &rs->nextthread,
3205 MAXTHREADLISTRESULTS,
3206 &done, &result_count,
3207 rs->resultthreadlist);
3210 /* Clear for later iterations. */
3212 /* Setup to resume next batch of thread references, set nextthread. */
3213 if (result_count >= 1)
3214 copy_threadref (&rs->nextthread,
3215 &rs->resultthreadlist[result_count - 1]);
3217 while (result_count--)
3219 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
3229 /* A thread found on the remote target. */
3233 explicit thread_item (ptid_t ptid_)
3237 thread_item (thread_item &&other) = default;
3238 thread_item &operator= (thread_item &&other) = default;
3240 DISABLE_COPY_AND_ASSIGN (thread_item);
3242 /* The thread's PTID. */
3245 /* The thread's extra info. */
3248 /* The thread's name. */
3251 /* The core the thread was running on. -1 if not known. */
3254 /* The thread handle associated with the thread. */
3255 gdb::byte_vector thread_handle;
3258 /* Context passed around to the various methods listing remote
3259 threads. As new threads are found, they're added to the ITEMS
3262 struct threads_listing_context
3264 /* Return true if this object contains an entry for a thread with ptid
3267 bool contains_thread (ptid_t ptid) const
3269 auto match_ptid = [&] (const thread_item &item)
3271 return item.ptid == ptid;
3274 auto it = std::find_if (this->items.begin (),
3278 return it != this->items.end ();
3281 /* Remove the thread with ptid PTID. */
3283 void remove_thread (ptid_t ptid)
3285 auto match_ptid = [&] (const thread_item &item)
3287 return item.ptid == ptid;
3290 auto it = std::remove_if (this->items.begin (),
3294 if (it != this->items.end ())
3295 this->items.erase (it);
3298 /* The threads found on the remote target. */
3299 std::vector<thread_item> items;
3303 remote_newthread_step (threadref *ref, void *data)
3305 struct threads_listing_context *context
3306 = (struct threads_listing_context *) data;
3307 int pid = inferior_ptid.pid ();
3308 int lwp = threadref_to_int (ref);
3309 ptid_t ptid (pid, lwp);
3311 context->items.emplace_back (ptid);
3313 return 1; /* continue iterator */
3316 #define CRAZY_MAX_THREADS 1000
3319 remote_current_thread (ptid_t oldpid)
3321 struct remote_state *rs = get_remote_state ();
3324 getpkt (&rs->buf, &rs->buf_size, 0);
3325 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
3330 result = read_ptid (&rs->buf[2], &obuf);
3331 if (*obuf != '\0' && remote_debug)
3332 fprintf_unfiltered (gdb_stdlog,
3333 "warning: garbage in qC reply\n");
3341 /* List remote threads using the deprecated qL packet. */
3344 remote_get_threads_with_ql (struct target_ops *ops,
3345 struct threads_listing_context *context)
3347 if (remote_threadlist_iterator (remote_newthread_step, context,
3348 CRAZY_MAX_THREADS) >= 0)
3354 #if defined(HAVE_LIBEXPAT)
3357 start_thread (struct gdb_xml_parser *parser,
3358 const struct gdb_xml_element *element,
3360 std::vector<gdb_xml_value> &attributes)
3362 struct threads_listing_context *data
3363 = (struct threads_listing_context *) user_data;
3364 struct gdb_xml_value *attr;
3366 char *id = (char *) xml_find_attribute (attributes, "id")->value.get ();
3367 ptid_t ptid = read_ptid (id, NULL);
3369 data->items.emplace_back (ptid);
3370 thread_item &item = data->items.back ();
3372 attr = xml_find_attribute (attributes, "core");
3374 item.core = *(ULONGEST *) attr->value.get ();
3376 attr = xml_find_attribute (attributes, "name");
3378 item.name = (const char *) attr->value.get ();
3380 attr = xml_find_attribute (attributes, "handle");
3382 item.thread_handle = hex2bin ((const char *) attr->value.get ());
3386 end_thread (struct gdb_xml_parser *parser,
3387 const struct gdb_xml_element *element,
3388 void *user_data, const char *body_text)
3390 struct threads_listing_context *data
3391 = (struct threads_listing_context *) user_data;
3393 if (body_text != NULL && *body_text != '\0')
3394 data->items.back ().extra = body_text;
3397 const struct gdb_xml_attribute thread_attributes[] = {
3398 { "id", GDB_XML_AF_NONE, NULL, NULL },
3399 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
3400 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
3401 { "handle", GDB_XML_AF_OPTIONAL, NULL, NULL },
3402 { NULL, GDB_XML_AF_NONE, NULL, NULL }
3405 const struct gdb_xml_element thread_children[] = {
3406 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3409 const struct gdb_xml_element threads_children[] = {
3410 { "thread", thread_attributes, thread_children,
3411 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3412 start_thread, end_thread },
3413 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3416 const struct gdb_xml_element threads_elements[] = {
3417 { "threads", NULL, threads_children,
3418 GDB_XML_EF_NONE, NULL, NULL },
3419 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3424 /* List remote threads using qXfer:threads:read. */
3427 remote_get_threads_with_qxfer (struct target_ops *ops,
3428 struct threads_listing_context *context)
3430 #if defined(HAVE_LIBEXPAT)
3431 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3433 gdb::optional<gdb::char_vector> xml
3434 = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
3436 if (xml && (*xml)[0] != '\0')
3438 gdb_xml_parse_quick (_("threads"), "threads.dtd",
3439 threads_elements, xml->data (), context);
3449 /* List remote threads using qfThreadInfo/qsThreadInfo. */
3452 remote_get_threads_with_qthreadinfo (struct target_ops *ops,
3453 struct threads_listing_context *context)
3455 struct remote_state *rs = get_remote_state ();
3457 if (rs->use_threadinfo_query)
3461 putpkt ("qfThreadInfo");
3462 getpkt (&rs->buf, &rs->buf_size, 0);
3464 if (bufp[0] != '\0') /* q packet recognized */
3466 while (*bufp++ == 'm') /* reply contains one or more TID */
3470 ptid_t ptid = read_ptid (bufp, &bufp);
3471 context->items.emplace_back (ptid);
3473 while (*bufp++ == ','); /* comma-separated list */
3474 putpkt ("qsThreadInfo");
3475 getpkt (&rs->buf, &rs->buf_size, 0);
3482 /* Packet not recognized. */
3483 rs->use_threadinfo_query = 0;
3490 /* Implement the to_update_thread_list function for the remote
3494 remote_target::update_thread_list ()
3496 struct threads_listing_context context;
3499 /* We have a few different mechanisms to fetch the thread list. Try
3500 them all, starting with the most preferred one first, falling
3501 back to older methods. */
3502 if (remote_get_threads_with_qxfer (this, &context)
3503 || remote_get_threads_with_qthreadinfo (this, &context)
3504 || remote_get_threads_with_ql (this, &context))
3506 struct thread_info *tp, *tmp;
3510 if (context.items.empty ()
3511 && remote_thread_always_alive (inferior_ptid))
3513 /* Some targets don't really support threads, but still
3514 reply an (empty) thread list in response to the thread
3515 listing packets, instead of replying "packet not
3516 supported". Exit early so we don't delete the main
3521 /* CONTEXT now holds the current thread list on the remote
3522 target end. Delete GDB-side threads no longer found on the
3524 ALL_THREADS_SAFE (tp, tmp)
3526 if (!context.contains_thread (tp->ptid))
3529 delete_thread (tp->ptid);
3533 /* Remove any unreported fork child threads from CONTEXT so
3534 that we don't interfere with follow fork, which is where
3535 creation of such threads is handled. */
3536 remove_new_fork_children (&context);
3538 /* And now add threads we don't know about yet to our list. */
3539 for (thread_item &item : context.items)
3541 if (item.ptid != null_ptid)
3543 /* In non-stop mode, we assume new found threads are
3544 executing until proven otherwise with a stop reply.
3545 In all-stop, we can only get here if all threads are
3547 int executing = target_is_non_stop_p () ? 1 : 0;
3549 remote_notice_new_inferior (item.ptid, executing);
3551 remote_thread_info *info = get_remote_thread_info (item.ptid);
3552 info->core = item.core;
3553 info->extra = std::move (item.extra);
3554 info->name = std::move (item.name);
3555 info->thread_handle = std::move (item.thread_handle);
3562 /* If no thread listing method is supported, then query whether
3563 each known thread is alive, one by one, with the T packet.
3564 If the target doesn't support threads at all, then this is a
3565 no-op. See remote_thread_alive. */
3571 * Collect a descriptive string about the given thread.
3572 * The target may say anything it wants to about the thread
3573 * (typically info about its blocked / runnable state, name, etc.).
3574 * This string will appear in the info threads display.
3576 * Optional: targets are not required to implement this function.
3580 remote_target::extra_thread_info (thread_info *tp)
3582 struct remote_state *rs = get_remote_state ();
3586 struct gdb_ext_thread_info threadinfo;
3587 static char display_buf[100]; /* arbitrary... */
3588 int n = 0; /* position in display_buf */
3590 if (rs->remote_desc == 0) /* paranoia */
3591 internal_error (__FILE__, __LINE__,
3592 _("remote_threads_extra_info"));
3594 if (ptid_equal (tp->ptid, magic_null_ptid)
3595 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
3596 /* This is the main thread which was added by GDB. The remote
3597 server doesn't know about it. */
3600 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3602 struct thread_info *info = find_thread_ptid (tp->ptid);
3604 if (info != NULL && info->priv != NULL)
3606 const std::string &extra = get_remote_thread_info (info)->extra;
3607 return !extra.empty () ? extra.c_str () : NULL;
3613 if (rs->use_threadextra_query)
3616 char *endb = rs->buf + get_remote_packet_size ();
3618 xsnprintf (b, endb - b, "qThreadExtraInfo,");
3620 write_ptid (b, endb, tp->ptid);
3623 getpkt (&rs->buf, &rs->buf_size, 0);
3624 if (rs->buf[0] != 0)
3626 n = std::min (strlen (rs->buf) / 2, sizeof (display_buf));
3627 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
3628 display_buf [result] = '\0';
3633 /* If the above query fails, fall back to the old method. */
3634 rs->use_threadextra_query = 0;
3635 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3636 | TAG_MOREDISPLAY | TAG_DISPLAY;
3637 int_to_threadref (&id, ptid_get_lwp (tp->ptid));
3638 if (remote_get_threadinfo (&id, set, &threadinfo))
3639 if (threadinfo.active)
3641 if (*threadinfo.shortname)
3642 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
3643 " Name: %s,", threadinfo.shortname);
3644 if (*threadinfo.display)
3645 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3646 " State: %s,", threadinfo.display);
3647 if (*threadinfo.more_display)
3648 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3649 " Priority: %s", threadinfo.more_display);
3653 /* For purely cosmetic reasons, clear up trailing commas. */
3654 if (',' == display_buf[n-1])
3655 display_buf[n-1] = ' ';
3664 remote_target::static_tracepoint_marker_at (CORE_ADDR addr,
3665 struct static_tracepoint_marker *marker)
3667 struct remote_state *rs = get_remote_state ();
3670 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
3672 p += hexnumstr (p, addr);
3674 getpkt (&rs->buf, &rs->buf_size, 0);
3678 error (_("Remote failure reply: %s"), p);
3682 parse_static_tracepoint_marker_definition (p, NULL, marker);
3689 std::vector<static_tracepoint_marker>
3690 remote_target::static_tracepoint_markers_by_strid (const char *strid)
3692 struct remote_state *rs = get_remote_state ();
3693 std::vector<static_tracepoint_marker> markers;
3695 static_tracepoint_marker marker;
3697 /* Ask for a first packet of static tracepoint marker
3700 getpkt (&rs->buf, &rs->buf_size, 0);
3703 error (_("Remote failure reply: %s"), p);
3709 parse_static_tracepoint_marker_definition (p, &p, &marker);
3711 if (strid == NULL || marker.str_id == strid)
3712 markers.push_back (std::move (marker));
3714 while (*p++ == ','); /* comma-separated list */
3715 /* Ask for another packet of static tracepoint definition. */
3717 getpkt (&rs->buf, &rs->buf_size, 0);
3725 /* Implement the to_get_ada_task_ptid function for the remote targets. */
3728 remote_target::get_ada_task_ptid (long lwp, long thread)
3730 return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
3734 /* Restart the remote side; this is an extended protocol operation. */
3737 extended_remote_restart (void)
3739 struct remote_state *rs = get_remote_state ();
3741 /* Send the restart command; for reasons I don't understand the
3742 remote side really expects a number after the "R". */
3743 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
3746 remote_fileio_reset ();
3749 /* Clean up connection to a remote debugger. */
3752 remote_target::close ()
3754 struct remote_state *rs = get_remote_state ();
3756 if (rs->remote_desc == NULL)
3757 return; /* already closed */
3759 /* Make sure we leave stdin registered in the event loop. */
3762 serial_close (rs->remote_desc);
3763 rs->remote_desc = NULL;
3765 /* We don't have a connection to the remote stub anymore. Get rid
3766 of all the inferiors and their threads we were controlling.
3767 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3768 will be unable to find the thread corresponding to (pid, 0, 0). */
3769 inferior_ptid = null_ptid;
3770 discard_all_inferiors ();
3772 /* We are closing the remote target, so we should discard
3773 everything of this target. */
3774 discard_pending_stop_replies_in_queue (rs);
3776 if (remote_async_inferior_event_token)
3777 delete_async_event_handler (&remote_async_inferior_event_token);
3779 remote_notif_state_xfree (rs->notif_state);
3781 trace_reset_local_state ();
3784 /* Query the remote side for the text, data and bss offsets. */
3789 struct remote_state *rs = get_remote_state ();
3792 int lose, num_segments = 0, do_sections, do_segments;
3793 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
3794 struct section_offsets *offs;
3795 struct symfile_segment_data *data;
3797 if (symfile_objfile == NULL)
3800 putpkt ("qOffsets");
3801 getpkt (&rs->buf, &rs->buf_size, 0);
3804 if (buf[0] == '\000')
3805 return; /* Return silently. Stub doesn't support
3809 warning (_("Remote failure reply: %s"), buf);
3813 /* Pick up each field in turn. This used to be done with scanf, but
3814 scanf will make trouble if CORE_ADDR size doesn't match
3815 conversion directives correctly. The following code will work
3816 with any size of CORE_ADDR. */
3817 text_addr = data_addr = bss_addr = 0;
3821 if (startswith (ptr, "Text="))
3824 /* Don't use strtol, could lose on big values. */
3825 while (*ptr && *ptr != ';')
3826 text_addr = (text_addr << 4) + fromhex (*ptr++);
3828 if (startswith (ptr, ";Data="))
3831 while (*ptr && *ptr != ';')
3832 data_addr = (data_addr << 4) + fromhex (*ptr++);
3837 if (!lose && startswith (ptr, ";Bss="))
3840 while (*ptr && *ptr != ';')
3841 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
3843 if (bss_addr != data_addr)
3844 warning (_("Target reported unsupported offsets: %s"), buf);
3849 else if (startswith (ptr, "TextSeg="))
3852 /* Don't use strtol, could lose on big values. */
3853 while (*ptr && *ptr != ';')
3854 text_addr = (text_addr << 4) + fromhex (*ptr++);
3857 if (startswith (ptr, ";DataSeg="))
3860 while (*ptr && *ptr != ';')
3861 data_addr = (data_addr << 4) + fromhex (*ptr++);
3869 error (_("Malformed response to offset query, %s"), buf);
3870 else if (*ptr != '\0')
3871 warning (_("Target reported unsupported offsets: %s"), buf);
3873 offs = ((struct section_offsets *)
3874 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
3875 memcpy (offs, symfile_objfile->section_offsets,
3876 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
3878 data = get_symfile_segment_data (symfile_objfile->obfd);
3879 do_segments = (data != NULL);
3880 do_sections = num_segments == 0;
3882 if (num_segments > 0)
3884 segments[0] = text_addr;
3885 segments[1] = data_addr;
3887 /* If we have two segments, we can still try to relocate everything
3888 by assuming that the .text and .data offsets apply to the whole
3889 text and data segments. Convert the offsets given in the packet
3890 to base addresses for symfile_map_offsets_to_segments. */
3891 else if (data && data->num_segments == 2)
3893 segments[0] = data->segment_bases[0] + text_addr;
3894 segments[1] = data->segment_bases[1] + data_addr;
3897 /* If the object file has only one segment, assume that it is text
3898 rather than data; main programs with no writable data are rare,
3899 but programs with no code are useless. Of course the code might
3900 have ended up in the data segment... to detect that we would need
3901 the permissions here. */
3902 else if (data && data->num_segments == 1)
3904 segments[0] = data->segment_bases[0] + text_addr;
3907 /* There's no way to relocate by segment. */
3913 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3914 offs, num_segments, segments);
3916 if (ret == 0 && !do_sections)
3917 error (_("Can not handle qOffsets TextSeg "
3918 "response with this symbol file"));
3925 free_symfile_segment_data (data);
3929 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3931 /* This is a temporary kludge to force data and bss to use the
3932 same offsets because that's what nlmconv does now. The real
3933 solution requires changes to the stub and remote.c that I
3934 don't have time to do right now. */
3936 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3937 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3940 objfile_relocate (symfile_objfile, offs);
3943 /* Send interrupt_sequence to remote target. */
3945 send_interrupt_sequence (void)
3947 struct remote_state *rs = get_remote_state ();
3949 if (interrupt_sequence_mode == interrupt_sequence_control_c)
3950 remote_serial_write ("\x03", 1);
3951 else if (interrupt_sequence_mode == interrupt_sequence_break)
3952 serial_send_break (rs->remote_desc);
3953 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3955 serial_send_break (rs->remote_desc);
3956 remote_serial_write ("g", 1);
3959 internal_error (__FILE__, __LINE__,
3960 _("Invalid value for interrupt_sequence_mode: %s."),
3961 interrupt_sequence_mode);
3965 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
3966 and extract the PTID. Returns NULL_PTID if not found. */
3969 stop_reply_extract_thread (char *stop_reply)
3971 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3975 /* Txx r:val ; r:val (...) */
3978 /* Look for "register" named "thread". */
3983 p1 = strchr (p, ':');
3987 if (strncmp (p, "thread", p1 - p) == 0)
3988 return read_ptid (++p1, &p);
3990 p1 = strchr (p, ';');
4002 /* Determine the remote side's current thread. If we have a stop
4003 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
4004 "thread" register we can extract the current thread from. If not,
4005 ask the remote which is the current thread with qC. The former
4006 method avoids a roundtrip. */
4009 get_current_thread (char *wait_status)
4011 ptid_t ptid = null_ptid;
4013 /* Note we don't use remote_parse_stop_reply as that makes use of
4014 the target architecture, which we haven't yet fully determined at
4016 if (wait_status != NULL)
4017 ptid = stop_reply_extract_thread (wait_status);
4018 if (ptid_equal (ptid, null_ptid))
4019 ptid = remote_current_thread (inferior_ptid);
4024 /* Query the remote target for which is the current thread/process,
4025 add it to our tables, and update INFERIOR_PTID. The caller is
4026 responsible for setting the state such that the remote end is ready
4027 to return the current thread.
4029 This function is called after handling the '?' or 'vRun' packets,
4030 whose response is a stop reply from which we can also try
4031 extracting the thread. If the target doesn't support the explicit
4032 qC query, we infer the current thread from that stop reply, passed
4033 in in WAIT_STATUS, which may be NULL. */
4036 add_current_inferior_and_thread (char *wait_status)
4038 struct remote_state *rs = get_remote_state ();
4041 inferior_ptid = null_ptid;
4043 /* Now, if we have thread information, update inferior_ptid. */
4044 ptid_t curr_ptid = get_current_thread (wait_status);
4046 if (curr_ptid != null_ptid)
4048 if (!remote_multi_process_p (rs))
4053 /* Without this, some commands which require an active target
4054 (such as kill) won't work. This variable serves (at least)
4055 double duty as both the pid of the target process (if it has
4056 such), and as a flag indicating that a target is active. */
4057 curr_ptid = magic_null_ptid;
4061 remote_add_inferior (fake_pid_p, ptid_get_pid (curr_ptid), -1, 1);
4063 /* Add the main thread and switch to it. Don't try reading
4064 registers yet, since we haven't fetched the target description
4066 thread_info *tp = add_thread_silent (curr_ptid);
4067 switch_to_thread_no_regs (tp);
4070 /* Print info about a thread that was found already stopped on
4074 print_one_stopped_thread (struct thread_info *thread)
4076 struct target_waitstatus *ws = &thread->suspend.waitstatus;
4078 switch_to_thread (thread->ptid);
4079 stop_pc = get_frame_pc (get_current_frame ());
4080 set_current_sal_from_frame (get_current_frame ());
4082 thread->suspend.waitstatus_pending_p = 0;
4084 if (ws->kind == TARGET_WAITKIND_STOPPED)
4086 enum gdb_signal sig = ws->value.sig;
4088 if (signal_print_state (sig))
4089 gdb::observers::signal_received.notify (sig);
4091 gdb::observers::normal_stop.notify (NULL, 1);
4094 /* Process all initial stop replies the remote side sent in response
4095 to the ? packet. These indicate threads that were already stopped
4096 on initial connection. We mark these threads as stopped and print
4097 their current frame before giving the user the prompt. */
4100 process_initial_stop_replies (int from_tty)
4102 int pending_stop_replies = stop_reply_queue_length ();
4103 struct inferior *inf;
4104 struct thread_info *thread;
4105 struct thread_info *selected = NULL;
4106 struct thread_info *lowest_stopped = NULL;
4107 struct thread_info *first = NULL;
4109 /* Consume the initial pending events. */
4110 while (pending_stop_replies-- > 0)
4112 ptid_t waiton_ptid = minus_one_ptid;
4114 struct target_waitstatus ws;
4115 int ignore_event = 0;
4116 struct thread_info *thread;
4118 memset (&ws, 0, sizeof (ws));
4119 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
4121 print_target_wait_results (waiton_ptid, event_ptid, &ws);
4125 case TARGET_WAITKIND_IGNORE:
4126 case TARGET_WAITKIND_NO_RESUMED:
4127 case TARGET_WAITKIND_SIGNALLED:
4128 case TARGET_WAITKIND_EXITED:
4129 /* We shouldn't see these, but if we do, just ignore. */
4131 fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
4135 case TARGET_WAITKIND_EXECD:
4136 xfree (ws.value.execd_pathname);
4145 thread = find_thread_ptid (event_ptid);
4147 if (ws.kind == TARGET_WAITKIND_STOPPED)
4149 enum gdb_signal sig = ws.value.sig;
4151 /* Stubs traditionally report SIGTRAP as initial signal,
4152 instead of signal 0. Suppress it. */
4153 if (sig == GDB_SIGNAL_TRAP)
4155 thread->suspend.stop_signal = sig;
4159 thread->suspend.waitstatus = ws;
4161 if (ws.kind != TARGET_WAITKIND_STOPPED
4162 || ws.value.sig != GDB_SIGNAL_0)
4163 thread->suspend.waitstatus_pending_p = 1;
4165 set_executing (event_ptid, 0);
4166 set_running (event_ptid, 0);
4167 get_remote_thread_info (thread)->vcont_resumed = 0;
4170 /* "Notice" the new inferiors before anything related to
4171 registers/memory. */
4177 inf->needs_setup = 1;
4181 thread = any_live_thread_of_process (inf->pid);
4182 notice_new_inferior (thread->ptid,
4183 thread->state == THREAD_RUNNING,
4188 /* If all-stop on top of non-stop, pause all threads. Note this
4189 records the threads' stop pc, so must be done after "noticing"
4193 stop_all_threads ();
4195 /* If all threads of an inferior were already stopped, we
4196 haven't setup the inferior yet. */
4202 if (inf->needs_setup)
4204 thread = any_live_thread_of_process (inf->pid);
4205 switch_to_thread_no_regs (thread);
4211 /* Now go over all threads that are stopped, and print their current
4212 frame. If all-stop, then if there's a signalled thread, pick
4214 ALL_NON_EXITED_THREADS (thread)
4220 set_running (thread->ptid, 0);
4221 else if (thread->state != THREAD_STOPPED)
4224 if (selected == NULL
4225 && thread->suspend.waitstatus_pending_p)
4228 if (lowest_stopped == NULL
4229 || thread->inf->num < lowest_stopped->inf->num
4230 || thread->per_inf_num < lowest_stopped->per_inf_num)
4231 lowest_stopped = thread;
4234 print_one_stopped_thread (thread);
4237 /* In all-stop, we only print the status of one thread, and leave
4238 others with their status pending. */
4243 thread = lowest_stopped;
4247 print_one_stopped_thread (thread);
4250 /* For "info program". */
4251 thread = inferior_thread ();
4252 if (thread->state == THREAD_STOPPED)
4253 set_last_target_status (inferior_ptid, thread->suspend.waitstatus);
4256 /* Start the remote connection and sync state. */
4259 remote_target::start_remote (int from_tty, int extended_p)
4261 struct remote_state *rs = get_remote_state ();
4262 struct packet_config *noack_config;
4263 char *wait_status = NULL;
4265 /* Signal other parts that we're going through the initial setup,
4266 and so things may not be stable yet. E.g., we don't try to
4267 install tracepoints until we've relocated symbols. Also, a
4268 Ctrl-C before we're connected and synced up can't interrupt the
4269 target. Instead, it offers to drop the (potentially wedged)
4271 rs->starting_up = 1;
4275 if (interrupt_on_connect)
4276 send_interrupt_sequence ();
4278 /* Ack any packet which the remote side has already sent. */
4279 remote_serial_write ("+", 1);
4281 /* The first packet we send to the target is the optional "supported
4282 packets" request. If the target can answer this, it will tell us
4283 which later probes to skip. */
4284 remote_query_supported ();
4286 /* If the stub wants to get a QAllow, compose one and send it. */
4287 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
4290 /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
4291 unknown 'v' packet with string "OK". "OK" gets interpreted by GDB
4292 as a reply to known packet. For packet "vFile:setfs:" it is an
4293 invalid reply and GDB would return error in
4294 remote_hostio_set_filesystem, making remote files access impossible.
4295 Disable "vFile:setfs:" in such case. Do not disable other 'v' packets as
4296 other "vFile" packets get correctly detected even on gdbserver < 7.7. */
4298 const char v_mustreplyempty[] = "vMustReplyEmpty";
4300 putpkt (v_mustreplyempty);
4301 getpkt (&rs->buf, &rs->buf_size, 0);
4302 if (strcmp (rs->buf, "OK") == 0)
4303 remote_protocol_packets[PACKET_vFile_setfs].support = PACKET_DISABLE;
4304 else if (strcmp (rs->buf, "") != 0)
4305 error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
4309 /* Next, we possibly activate noack mode.
4311 If the QStartNoAckMode packet configuration is set to AUTO,
4312 enable noack mode if the stub reported a wish for it with
4315 If set to TRUE, then enable noack mode even if the stub didn't
4316 report it in qSupported. If the stub doesn't reply OK, the
4317 session ends with an error.
4319 If FALSE, then don't activate noack mode, regardless of what the
4320 stub claimed should be the default with qSupported. */
4322 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4323 if (packet_config_support (noack_config) != PACKET_DISABLE)
4325 putpkt ("QStartNoAckMode");
4326 getpkt (&rs->buf, &rs->buf_size, 0);
4327 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
4333 /* Tell the remote that we are using the extended protocol. */
4335 getpkt (&rs->buf, &rs->buf_size, 0);
4338 /* Let the target know which signals it is allowed to pass down to
4340 update_signals_program_target ();
4342 /* Next, if the target can specify a description, read it. We do
4343 this before anything involving memory or registers. */
4344 target_find_description ();
4346 /* Next, now that we know something about the target, update the
4347 address spaces in the program spaces. */
4348 update_address_spaces ();
4350 /* On OSs where the list of libraries is global to all
4351 processes, we fetch them early. */
4352 if (gdbarch_has_global_solist (target_gdbarch ()))
4353 solib_add (NULL, from_tty, auto_solib_add);
4355 if (target_is_non_stop_p ())
4357 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
4358 error (_("Non-stop mode requested, but remote "
4359 "does not support non-stop"));
4361 putpkt ("QNonStop:1");
4362 getpkt (&rs->buf, &rs->buf_size, 0);
4364 if (strcmp (rs->buf, "OK") != 0)
4365 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
4367 /* Find about threads and processes the stub is already
4368 controlling. We default to adding them in the running state.
4369 The '?' query below will then tell us about which threads are
4371 this->update_thread_list ();
4373 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
4375 /* Don't assume that the stub can operate in all-stop mode.
4376 Request it explicitly. */
4377 putpkt ("QNonStop:0");
4378 getpkt (&rs->buf, &rs->buf_size, 0);
4380 if (strcmp (rs->buf, "OK") != 0)
4381 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
4384 /* Upload TSVs regardless of whether the target is running or not. The
4385 remote stub, such as GDBserver, may have some predefined or builtin
4386 TSVs, even if the target is not running. */
4387 if (get_trace_status (current_trace_status ()) != -1)
4389 struct uploaded_tsv *uploaded_tsvs = NULL;
4391 upload_trace_state_variables (&uploaded_tsvs);
4392 merge_uploaded_trace_state_variables (&uploaded_tsvs);
4395 /* Check whether the target is running now. */
4397 getpkt (&rs->buf, &rs->buf_size, 0);
4399 if (!target_is_non_stop_p ())
4401 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
4404 error (_("The target is not running (try extended-remote?)"));
4406 /* We're connected, but not running. Drop out before we
4407 call start_remote. */
4408 rs->starting_up = 0;
4413 /* Save the reply for later. */
4414 wait_status = (char *) alloca (strlen (rs->buf) + 1);
4415 strcpy (wait_status, rs->buf);
4418 /* Fetch thread list. */
4419 target_update_thread_list ();
4421 /* Let the stub know that we want it to return the thread. */
4422 set_continue_thread (minus_one_ptid);
4424 if (thread_count () == 0)
4426 /* Target has no concept of threads at all. GDB treats
4427 non-threaded target as single-threaded; add a main
4429 add_current_inferior_and_thread (wait_status);
4433 /* We have thread information; select the thread the target
4434 says should be current. If we're reconnecting to a
4435 multi-threaded program, this will ideally be the thread
4436 that last reported an event before GDB disconnected. */
4437 inferior_ptid = get_current_thread (wait_status);
4438 if (ptid_equal (inferior_ptid, null_ptid))
4440 /* Odd... The target was able to list threads, but not
4441 tell us which thread was current (no "thread"
4442 register in T stop reply?). Just pick the first
4443 thread in the thread list then. */
4446 fprintf_unfiltered (gdb_stdlog,
4447 "warning: couldn't determine remote "
4448 "current thread; picking first in list.\n");
4450 inferior_ptid = thread_list->ptid;
4454 /* init_wait_for_inferior should be called before get_offsets in order
4455 to manage `inserted' flag in bp loc in a correct state.
4456 breakpoint_init_inferior, called from init_wait_for_inferior, set
4457 `inserted' flag to 0, while before breakpoint_re_set, called from
4458 start_remote, set `inserted' flag to 1. In the initialization of
4459 inferior, breakpoint_init_inferior should be called first, and then
4460 breakpoint_re_set can be called. If this order is broken, state of
4461 `inserted' flag is wrong, and cause some problems on breakpoint
4463 init_wait_for_inferior ();
4465 get_offsets (); /* Get text, data & bss offsets. */
4467 /* If we could not find a description using qXfer, and we know
4468 how to do it some other way, try again. This is not
4469 supported for non-stop; it could be, but it is tricky if
4470 there are no stopped threads when we connect. */
4471 if (remote_read_description_p (this)
4472 && gdbarch_target_desc (target_gdbarch ()) == NULL)
4474 target_clear_description ();
4475 target_find_description ();
4478 /* Use the previously fetched status. */
4479 gdb_assert (wait_status != NULL);
4480 strcpy (rs->buf, wait_status);
4481 rs->cached_wait_status = 1;
4483 ::start_remote (from_tty); /* Initialize gdb process mechanisms. */
4487 /* Clear WFI global state. Do this before finding about new
4488 threads and inferiors, and setting the current inferior.
4489 Otherwise we would clear the proceed status of the current
4490 inferior when we want its stop_soon state to be preserved
4491 (see notice_new_inferior). */
4492 init_wait_for_inferior ();
4494 /* In non-stop, we will either get an "OK", meaning that there
4495 are no stopped threads at this time; or, a regular stop
4496 reply. In the latter case, there may be more than one thread
4497 stopped --- we pull them all out using the vStopped
4499 if (strcmp (rs->buf, "OK") != 0)
4501 struct notif_client *notif = ¬if_client_stop;
4503 /* remote_notif_get_pending_replies acks this one, and gets
4505 rs->notif_state->pending_event[notif_client_stop.id]
4506 = remote_notif_parse (notif, rs->buf);
4507 remote_notif_get_pending_events (notif);
4510 if (thread_count () == 0)
4513 error (_("The target is not running (try extended-remote?)"));
4515 /* We're connected, but not running. Drop out before we
4516 call start_remote. */
4517 rs->starting_up = 0;
4521 /* In non-stop mode, any cached wait status will be stored in
4522 the stop reply queue. */
4523 gdb_assert (wait_status == NULL);
4525 /* Report all signals during attach/startup. */
4526 pass_signals (0, NULL);
4528 /* If there are already stopped threads, mark them stopped and
4529 report their stops before giving the prompt to the user. */
4530 process_initial_stop_replies (from_tty);
4532 if (target_can_async_p ())
4536 /* If we connected to a live target, do some additional setup. */
4537 if (target_has_execution)
4539 if (symfile_objfile) /* No use without a symbol-file. */
4540 remote_check_symbols ();
4543 /* Possibly the target has been engaged in a trace run started
4544 previously; find out where things are at. */
4545 if (get_trace_status (current_trace_status ()) != -1)
4547 struct uploaded_tp *uploaded_tps = NULL;
4549 if (current_trace_status ()->running)
4550 printf_filtered (_("Trace is already running on the target.\n"));
4552 upload_tracepoints (&uploaded_tps);
4554 merge_uploaded_tracepoints (&uploaded_tps);
4557 /* Possibly the target has been engaged in a btrace record started
4558 previously; find out where things are at. */
4559 remote_btrace_maybe_reopen ();
4561 /* The thread and inferior lists are now synchronized with the
4562 target, our symbols have been relocated, and we're merged the
4563 target's tracepoints with ours. We're done with basic start
4565 rs->starting_up = 0;
4567 /* Maybe breakpoints are global and need to be inserted now. */
4568 if (breakpoints_should_be_inserted_now ())
4569 insert_breakpoints ();
4572 /* Open a connection to a remote debugger.
4573 NAME is the filename used for communication. */
4576 remote_target::open (const char *name, int from_tty)
4578 open_1 (name, from_tty, 0);
4581 /* Open a connection to a remote debugger using the extended
4582 remote gdb protocol. NAME is the filename used for communication. */
4585 extended_remote_target::open (const char *name, int from_tty)
4587 open_1 (name, from_tty, 1 /*extended_p */);
4590 /* Reset all packets back to "unknown support". Called when opening a
4591 new connection to a remote target. */
4594 reset_all_packet_configs_support (void)
4598 for (i = 0; i < PACKET_MAX; i++)
4599 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4602 /* Initialize all packet configs. */
4605 init_all_packet_configs (void)
4609 for (i = 0; i < PACKET_MAX; i++)
4611 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
4612 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4616 /* Symbol look-up. */
4619 remote_check_symbols (void)
4621 char *msg, *reply, *tmp;
4624 struct cleanup *old_chain;
4626 /* The remote side has no concept of inferiors that aren't running
4627 yet, it only knows about running processes. If we're connected
4628 but our current inferior is not running, we should not invite the
4629 remote target to request symbol lookups related to its
4630 (unrelated) current process. */
4631 if (!target_has_execution)
4634 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
4637 /* Make sure the remote is pointing at the right process. Note
4638 there's no way to select "no process". */
4639 set_general_process ();
4641 /* Allocate a message buffer. We can't reuse the input buffer in RS,
4642 because we need both at the same time. */
4643 msg = (char *) xmalloc (get_remote_packet_size ());
4644 old_chain = make_cleanup (xfree, msg);
4645 reply = (char *) xmalloc (get_remote_packet_size ());
4646 make_cleanup (free_current_contents, &reply);
4647 reply_size = get_remote_packet_size ();
4649 /* Invite target to request symbol lookups. */
4651 putpkt ("qSymbol::");
4652 getpkt (&reply, &reply_size, 0);
4653 packet_ok (reply, &remote_protocol_packets[PACKET_qSymbol]);
4655 while (startswith (reply, "qSymbol:"))
4657 struct bound_minimal_symbol sym;
4660 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
4662 sym = lookup_minimal_symbol (msg, NULL, NULL);
4663 if (sym.minsym == NULL)
4664 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
4667 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4668 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
4670 /* If this is a function address, return the start of code
4671 instead of any data function descriptor. */
4672 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
4676 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
4677 phex_nz (sym_addr, addr_size), &reply[8]);
4681 getpkt (&reply, &reply_size, 0);
4684 do_cleanups (old_chain);
4687 static struct serial *
4688 remote_serial_open (const char *name)
4690 static int udp_warning = 0;
4692 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
4693 of in ser-tcp.c, because it is the remote protocol assuming that the
4694 serial connection is reliable and not the serial connection promising
4696 if (!udp_warning && startswith (name, "udp:"))
4698 warning (_("The remote protocol may be unreliable over UDP.\n"
4699 "Some events may be lost, rendering further debugging "
4704 return serial_open (name);
4707 /* Inform the target of our permission settings. The permission flags
4708 work without this, but if the target knows the settings, it can do
4709 a couple things. First, it can add its own check, to catch cases
4710 that somehow manage to get by the permissions checks in target
4711 methods. Second, if the target is wired to disallow particular
4712 settings (for instance, a system in the field that is not set up to
4713 be able to stop at a breakpoint), it can object to any unavailable
4717 remote_target::set_permissions ()
4719 struct remote_state *rs = get_remote_state ();
4721 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
4722 "WriteReg:%x;WriteMem:%x;"
4723 "InsertBreak:%x;InsertTrace:%x;"
4724 "InsertFastTrace:%x;Stop:%x",
4725 may_write_registers, may_write_memory,
4726 may_insert_breakpoints, may_insert_tracepoints,
4727 may_insert_fast_tracepoints, may_stop);
4729 getpkt (&rs->buf, &rs->buf_size, 0);
4731 /* If the target didn't like the packet, warn the user. Do not try
4732 to undo the user's settings, that would just be maddening. */
4733 if (strcmp (rs->buf, "OK") != 0)
4734 warning (_("Remote refused setting permissions with: %s"), rs->buf);
4737 /* This type describes each known response to the qSupported
4739 struct protocol_feature
4741 /* The name of this protocol feature. */
4744 /* The default for this protocol feature. */
4745 enum packet_support default_support;
4747 /* The function to call when this feature is reported, or after
4748 qSupported processing if the feature is not supported.
4749 The first argument points to this structure. The second
4750 argument indicates whether the packet requested support be
4751 enabled, disabled, or probed (or the default, if this function
4752 is being called at the end of processing and this feature was
4753 not reported). The third argument may be NULL; if not NULL, it
4754 is a NUL-terminated string taken from the packet following
4755 this feature's name and an equals sign. */
4756 void (*func) (const struct protocol_feature *, enum packet_support,
4759 /* The corresponding packet for this feature. Only used if
4760 FUNC is remote_supported_packet. */
4765 remote_supported_packet (const struct protocol_feature *feature,
4766 enum packet_support support,
4767 const char *argument)
4771 warning (_("Remote qSupported response supplied an unexpected value for"
4772 " \"%s\"."), feature->name);
4776 remote_protocol_packets[feature->packet].support = support;
4780 remote_packet_size (const struct protocol_feature *feature,
4781 enum packet_support support, const char *value)
4783 struct remote_state *rs = get_remote_state ();
4788 if (support != PACKET_ENABLE)
4791 if (value == NULL || *value == '\0')
4793 warning (_("Remote target reported \"%s\" without a size."),
4799 packet_size = strtol (value, &value_end, 16);
4800 if (errno != 0 || *value_end != '\0' || packet_size < 0)
4802 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
4803 feature->name, value);
4807 /* Record the new maximum packet size. */
4808 rs->explicit_packet_size = packet_size;
4811 static const struct protocol_feature remote_protocol_features[] = {
4812 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
4813 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
4814 PACKET_qXfer_auxv },
4815 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
4816 PACKET_qXfer_exec_file },
4817 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
4818 PACKET_qXfer_features },
4819 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
4820 PACKET_qXfer_libraries },
4821 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
4822 PACKET_qXfer_libraries_svr4 },
4823 { "augmented-libraries-svr4-read", PACKET_DISABLE,
4824 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
4825 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
4826 PACKET_qXfer_memory_map },
4827 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
4828 PACKET_qXfer_spu_read },
4829 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
4830 PACKET_qXfer_spu_write },
4831 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
4832 PACKET_qXfer_osdata },
4833 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
4834 PACKET_qXfer_threads },
4835 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
4836 PACKET_qXfer_traceframe_info },
4837 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
4838 PACKET_QPassSignals },
4839 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
4840 PACKET_QCatchSyscalls },
4841 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
4842 PACKET_QProgramSignals },
4843 { "QSetWorkingDir", PACKET_DISABLE, remote_supported_packet,
4844 PACKET_QSetWorkingDir },
4845 { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
4846 PACKET_QStartupWithShell },
4847 { "QEnvironmentHexEncoded", PACKET_DISABLE, remote_supported_packet,
4848 PACKET_QEnvironmentHexEncoded },
4849 { "QEnvironmentReset", PACKET_DISABLE, remote_supported_packet,
4850 PACKET_QEnvironmentReset },
4851 { "QEnvironmentUnset", PACKET_DISABLE, remote_supported_packet,
4852 PACKET_QEnvironmentUnset },
4853 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
4854 PACKET_QStartNoAckMode },
4855 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
4856 PACKET_multiprocess_feature },
4857 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4858 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
4859 PACKET_qXfer_siginfo_read },
4860 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4861 PACKET_qXfer_siginfo_write },
4862 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
4863 PACKET_ConditionalTracepoints },
4864 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
4865 PACKET_ConditionalBreakpoints },
4866 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
4867 PACKET_BreakpointCommands },
4868 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
4869 PACKET_FastTracepoints },
4870 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
4871 PACKET_StaticTracepoints },
4872 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
4873 PACKET_InstallInTrace},
4874 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
4875 PACKET_DisconnectedTracing_feature },
4876 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4878 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4880 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4881 PACKET_TracepointSource },
4882 { "QAllow", PACKET_DISABLE, remote_supported_packet,
4884 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
4885 PACKET_EnableDisableTracepoints_feature },
4886 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4887 PACKET_qXfer_fdpic },
4888 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4890 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4891 PACKET_QDisableRandomization },
4892 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
4893 { "QTBuffer:size", PACKET_DISABLE,
4894 remote_supported_packet, PACKET_QTBuffer_size},
4895 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
4896 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4897 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
4898 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
4899 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
4900 PACKET_qXfer_btrace },
4901 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
4902 PACKET_qXfer_btrace_conf },
4903 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
4904 PACKET_Qbtrace_conf_bts_size },
4905 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
4906 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
4907 { "fork-events", PACKET_DISABLE, remote_supported_packet,
4908 PACKET_fork_event_feature },
4909 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
4910 PACKET_vfork_event_feature },
4911 { "exec-events", PACKET_DISABLE, remote_supported_packet,
4912 PACKET_exec_event_feature },
4913 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
4914 PACKET_Qbtrace_conf_pt_size },
4915 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
4916 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
4917 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
4920 static char *remote_support_xml;
4922 /* Register string appended to "xmlRegisters=" in qSupported query. */
4925 register_remote_support_xml (const char *xml)
4927 #if defined(HAVE_LIBEXPAT)
4928 if (remote_support_xml == NULL)
4929 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
4932 char *copy = xstrdup (remote_support_xml + 13);
4933 char *p = strtok (copy, ",");
4937 if (strcmp (p, xml) == 0)
4944 while ((p = strtok (NULL, ",")) != NULL);
4947 remote_support_xml = reconcat (remote_support_xml,
4948 remote_support_xml, ",", xml,
4955 remote_query_supported_append (char *msg, const char *append)
4958 return reconcat (msg, msg, ";", append, (char *) NULL);
4960 return xstrdup (append);
4964 remote_query_supported (void)
4966 struct remote_state *rs = get_remote_state ();
4969 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4971 /* The packet support flags are handled differently for this packet
4972 than for most others. We treat an error, a disabled packet, and
4973 an empty response identically: any features which must be reported
4974 to be used will be automatically disabled. An empty buffer
4975 accomplishes this, since that is also the representation for a list
4976 containing no features. */
4979 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
4982 struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
4984 if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
4985 q = remote_query_supported_append (q, "multiprocess+");
4987 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
4988 q = remote_query_supported_append (q, "swbreak+");
4989 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
4990 q = remote_query_supported_append (q, "hwbreak+");
4992 q = remote_query_supported_append (q, "qRelocInsn+");
4994 if (packet_set_cmd_state (PACKET_fork_event_feature)
4995 != AUTO_BOOLEAN_FALSE)
4996 q = remote_query_supported_append (q, "fork-events+");
4997 if (packet_set_cmd_state (PACKET_vfork_event_feature)
4998 != AUTO_BOOLEAN_FALSE)
4999 q = remote_query_supported_append (q, "vfork-events+");
5000 if (packet_set_cmd_state (PACKET_exec_event_feature)
5001 != AUTO_BOOLEAN_FALSE)
5002 q = remote_query_supported_append (q, "exec-events+");
5004 if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
5005 q = remote_query_supported_append (q, "vContSupported+");
5007 if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
5008 q = remote_query_supported_append (q, "QThreadEvents+");
5010 if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
5011 q = remote_query_supported_append (q, "no-resumed+");
5013 /* Keep this one last to work around a gdbserver <= 7.10 bug in
5014 the qSupported:xmlRegisters=i386 handling. */
5015 if (remote_support_xml != NULL
5016 && packet_support (PACKET_qXfer_features) != PACKET_DISABLE)
5017 q = remote_query_supported_append (q, remote_support_xml);
5019 q = reconcat (q, "qSupported:", q, (char *) NULL);
5022 do_cleanups (old_chain);
5024 getpkt (&rs->buf, &rs->buf_size, 0);
5026 /* If an error occured, warn, but do not return - just reset the
5027 buffer to empty and go on to disable features. */
5028 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
5031 warning (_("Remote failure reply: %s"), rs->buf);
5036 memset (seen, 0, sizeof (seen));
5041 enum packet_support is_supported;
5042 char *p, *end, *name_end, *value;
5044 /* First separate out this item from the rest of the packet. If
5045 there's another item after this, we overwrite the separator
5046 (terminated strings are much easier to work with). */
5048 end = strchr (p, ';');
5051 end = p + strlen (p);
5061 warning (_("empty item in \"qSupported\" response"));
5066 name_end = strchr (p, '=');
5069 /* This is a name=value entry. */
5070 is_supported = PACKET_ENABLE;
5071 value = name_end + 1;
5080 is_supported = PACKET_ENABLE;
5084 is_supported = PACKET_DISABLE;
5088 is_supported = PACKET_SUPPORT_UNKNOWN;
5092 warning (_("unrecognized item \"%s\" "
5093 "in \"qSupported\" response"), p);
5099 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5100 if (strcmp (remote_protocol_features[i].name, p) == 0)
5102 const struct protocol_feature *feature;
5105 feature = &remote_protocol_features[i];
5106 feature->func (feature, is_supported, value);
5111 /* If we increased the packet size, make sure to increase the global
5112 buffer size also. We delay this until after parsing the entire
5113 qSupported packet, because this is the same buffer we were
5115 if (rs->buf_size < rs->explicit_packet_size)
5117 rs->buf_size = rs->explicit_packet_size;
5118 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
5121 /* Handle the defaults for unmentioned features. */
5122 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5125 const struct protocol_feature *feature;
5127 feature = &remote_protocol_features[i];
5128 feature->func (feature, feature->default_support, NULL);
5132 /* Serial QUIT handler for the remote serial descriptor.
5134 Defers handling a Ctrl-C until we're done with the current
5135 command/response packet sequence, unless:
5137 - We're setting up the connection. Don't send a remote interrupt
5138 request, as we're not fully synced yet. Quit immediately
5141 - The target has been resumed in the foreground
5142 (target_terminal::is_ours is false) with a synchronous resume
5143 packet, and we're blocked waiting for the stop reply, thus a
5144 Ctrl-C should be immediately sent to the target.
5146 - We get a second Ctrl-C while still within the same serial read or
5147 write. In that case the serial is seemingly wedged --- offer to
5150 - We see a second Ctrl-C without target response, after having
5151 previously interrupted the target. In that case the target/stub
5152 is probably wedged --- offer to quit/disconnect.
5156 remote_serial_quit_handler (void)
5158 struct remote_state *rs = get_remote_state ();
5160 if (check_quit_flag ())
5162 /* If we're starting up, we're not fully synced yet. Quit
5164 if (rs->starting_up)
5166 else if (rs->got_ctrlc_during_io)
5168 if (query (_("The target is not responding to GDB commands.\n"
5169 "Stop debugging it? ")))
5170 remote_unpush_and_throw ();
5172 /* If ^C has already been sent once, offer to disconnect. */
5173 else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
5175 /* All-stop protocol, and blocked waiting for stop reply. Send
5176 an interrupt request. */
5177 else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
5178 target_interrupt ();
5180 rs->got_ctrlc_during_io = 1;
5184 /* Remove any of the remote.c targets from target stack. Upper targets depend
5185 on it so remove them first. */
5188 remote_unpush_target (void)
5190 pop_all_targets_at_and_above (process_stratum);
5194 remote_unpush_and_throw (void)
5196 remote_unpush_target ();
5197 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5201 remote_target::open_1 (const char *name, int from_tty, int extended_p)
5203 struct remote_state *rs = get_remote_state ();
5206 error (_("To open a remote debug connection, you need to specify what\n"
5207 "serial device is attached to the remote system\n"
5208 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
5210 /* See FIXME above. */
5211 if (!target_async_permitted)
5212 wait_forever_enabled_p = 1;
5214 /* If we're connected to a running target, target_preopen will kill it.
5215 Ask this question first, before target_preopen has a chance to kill
5217 if (rs->remote_desc != NULL && !have_inferiors ())
5220 && !query (_("Already connected to a remote target. Disconnect? ")))
5221 error (_("Still connected."));
5224 /* Here the possibly existing remote target gets unpushed. */
5225 target_preopen (from_tty);
5227 /* Make sure we send the passed signals list the next time we resume. */
5228 xfree (rs->last_pass_packet);
5229 rs->last_pass_packet = NULL;
5231 /* Make sure we send the program signals list the next time we
5233 xfree (rs->last_program_signals_packet);
5234 rs->last_program_signals_packet = NULL;
5236 remote_fileio_reset ();
5237 reopen_exec_file ();
5240 rs->remote_desc = remote_serial_open (name);
5241 if (!rs->remote_desc)
5242 perror_with_name (name);
5244 if (baud_rate != -1)
5246 if (serial_setbaudrate (rs->remote_desc, baud_rate))
5248 /* The requested speed could not be set. Error out to
5249 top level after closing remote_desc. Take care to
5250 set remote_desc to NULL to avoid closing remote_desc
5252 serial_close (rs->remote_desc);
5253 rs->remote_desc = NULL;
5254 perror_with_name (name);
5258 serial_setparity (rs->remote_desc, serial_parity);
5259 serial_raw (rs->remote_desc);
5261 /* If there is something sitting in the buffer we might take it as a
5262 response to a command, which would be bad. */
5263 serial_flush_input (rs->remote_desc);
5267 puts_filtered ("Remote debugging using ");
5268 puts_filtered (name);
5269 puts_filtered ("\n");
5271 push_target (this); /* Switch to using remote target now. */
5273 /* Register extra event sources in the event loop. */
5274 remote_async_inferior_event_token
5275 = create_async_event_handler (remote_async_inferior_event_handler,
5277 rs->notif_state = remote_notif_state_allocate ();
5279 /* Reset the target state; these things will be queried either by
5280 remote_query_supported or as they are needed. */
5281 reset_all_packet_configs_support ();
5282 rs->cached_wait_status = 0;
5283 rs->explicit_packet_size = 0;
5285 rs->extended = extended_p;
5286 rs->waiting_for_stop_reply = 0;
5287 rs->ctrlc_pending_p = 0;
5288 rs->got_ctrlc_during_io = 0;
5290 rs->general_thread = not_sent_ptid;
5291 rs->continue_thread = not_sent_ptid;
5292 rs->remote_traceframe_number = -1;
5294 rs->last_resume_exec_dir = EXEC_FORWARD;
5296 /* Probe for ability to use "ThreadInfo" query, as required. */
5297 rs->use_threadinfo_query = 1;
5298 rs->use_threadextra_query = 1;
5300 readahead_cache_invalidate ();
5302 if (target_async_permitted)
5304 /* FIXME: cagney/1999-09-23: During the initial connection it is
5305 assumed that the target is already ready and able to respond to
5306 requests. Unfortunately remote_start_remote() eventually calls
5307 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
5308 around this. Eventually a mechanism that allows
5309 wait_for_inferior() to expect/get timeouts will be
5311 wait_forever_enabled_p = 0;
5314 /* First delete any symbols previously loaded from shared libraries. */
5315 no_shared_libraries (NULL, 0);
5318 init_thread_list ();
5320 /* Start the remote connection. If error() or QUIT, discard this
5321 target (we'd otherwise be in an inconsistent state) and then
5322 propogate the error on up the exception chain. This ensures that
5323 the caller doesn't stumble along blindly assuming that the
5324 function succeeded. The CLI doesn't have this problem but other
5325 UI's, such as MI do.
5327 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
5328 this function should return an error indication letting the
5329 caller restore the previous state. Unfortunately the command
5330 ``target remote'' is directly wired to this function making that
5331 impossible. On a positive note, the CLI side of this problem has
5332 been fixed - the function set_cmd_context() makes it possible for
5333 all the ``target ....'' commands to share a common callback
5334 function. See cli-dump.c. */
5339 start_remote (from_tty, extended_p);
5341 CATCH (ex, RETURN_MASK_ALL)
5343 /* Pop the partially set up target - unless something else did
5344 already before throwing the exception. */
5345 if (rs->remote_desc != NULL)
5346 remote_unpush_target ();
5347 if (target_async_permitted)
5348 wait_forever_enabled_p = 1;
5349 throw_exception (ex);
5354 remote_btrace_reset ();
5356 if (target_async_permitted)
5357 wait_forever_enabled_p = 1;
5360 /* Detach the specified process. */
5363 remote_detach_pid (int pid)
5365 struct remote_state *rs = get_remote_state ();
5367 if (remote_multi_process_p (rs))
5368 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
5370 strcpy (rs->buf, "D");
5373 getpkt (&rs->buf, &rs->buf_size, 0);
5375 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
5377 else if (rs->buf[0] == '\0')
5378 error (_("Remote doesn't know how to detach"));
5380 error (_("Can't detach process."));
5383 /* This detaches a program to which we previously attached, using
5384 inferior_ptid to identify the process. After this is done, GDB
5385 can be used to debug some other program. We better not have left
5386 any breakpoints in the target program or it'll die when it hits
5390 remote_detach_1 (int from_tty, inferior *inf)
5392 int pid = ptid_get_pid (inferior_ptid);
5393 struct remote_state *rs = get_remote_state ();
5394 struct thread_info *tp = find_thread_ptid (inferior_ptid);
5397 if (!target_has_execution)
5398 error (_("No process to detach from."));
5400 target_announce_detach (from_tty);
5402 /* Tell the remote target to detach. */
5403 remote_detach_pid (pid);
5405 /* Exit only if this is the only active inferior. */
5406 if (from_tty && !rs->extended && number_of_live_inferiors () == 1)
5407 puts_filtered (_("Ending remote debugging.\n"));
5409 /* Check to see if we are detaching a fork parent. Note that if we
5410 are detaching a fork child, tp == NULL. */
5411 is_fork_parent = (tp != NULL
5412 && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
5414 /* If doing detach-on-fork, we don't mourn, because that will delete
5415 breakpoints that should be available for the followed inferior. */
5416 if (!is_fork_parent)
5418 /* Save the pid as a string before mourning, since that will
5419 unpush the remote target, and we need the string after. */
5420 std::string infpid = target_pid_to_str (pid_to_ptid (pid));
5422 target_mourn_inferior (inferior_ptid);
5423 if (print_inferior_events)
5424 printf_unfiltered (_("[Inferior %d (%s) detached]\n"),
5425 inf->num, infpid.c_str ());
5429 inferior_ptid = null_ptid;
5430 detach_inferior (pid);
5435 remote_target::detach (inferior *inf, int from_tty)
5437 remote_detach_1 (from_tty, inf);
5441 extended_remote_target::detach (inferior *inf, int from_tty)
5443 remote_detach_1 (from_tty, inf);
5446 /* Target follow-fork function for remote targets. On entry, and
5447 at return, the current inferior is the fork parent.
5449 Note that although this is currently only used for extended-remote,
5450 it is named remote_follow_fork in anticipation of using it for the
5451 remote target as well. */
5454 remote_target::follow_fork (int follow_child, int detach_fork)
5456 struct remote_state *rs = get_remote_state ();
5457 enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
5459 if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
5460 || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
5462 /* When following the parent and detaching the child, we detach
5463 the child here. For the case of following the child and
5464 detaching the parent, the detach is done in the target-
5465 independent follow fork code in infrun.c. We can't use
5466 target_detach when detaching an unfollowed child because
5467 the client side doesn't know anything about the child. */
5468 if (detach_fork && !follow_child)
5470 /* Detach the fork child. */
5474 child_ptid = inferior_thread ()->pending_follow.value.related_pid;
5475 child_pid = ptid_get_pid (child_ptid);
5477 remote_detach_pid (child_pid);
5483 /* Target follow-exec function for remote targets. Save EXECD_PATHNAME
5484 in the program space of the new inferior. On entry and at return the
5485 current inferior is the exec'ing inferior. INF is the new exec'd
5486 inferior, which may be the same as the exec'ing inferior unless
5487 follow-exec-mode is "new". */
5490 remote_target::follow_exec (struct inferior *inf, char *execd_pathname)
5492 /* We know that this is a target file name, so if it has the "target:"
5493 prefix we strip it off before saving it in the program space. */
5494 if (is_target_filename (execd_pathname))
5495 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
5497 set_pspace_remote_exec_file (inf->pspace, execd_pathname);
5500 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
5503 remote_target::disconnect (const char *args, int from_tty)
5506 error (_("Argument given to \"disconnect\" when remotely debugging."));
5508 /* Make sure we unpush even the extended remote targets. Calling
5509 target_mourn_inferior won't unpush, and remote_mourn won't
5510 unpush if there is more than one inferior left. */
5511 unpush_target (this);
5512 generic_mourn_inferior ();
5515 puts_filtered ("Ending remote debugging.\n");
5518 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
5519 be chatty about it. */
5522 extended_remote_target::attach (const char *args, int from_tty)
5524 struct remote_state *rs = get_remote_state ();
5526 char *wait_status = NULL;
5528 pid = parse_pid_to_attach (args);
5530 /* Remote PID can be freely equal to getpid, do not check it here the same
5531 way as in other targets. */
5533 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
5534 error (_("This target does not support attaching to a process"));
5538 char *exec_file = get_exec_file (0);
5541 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
5542 target_pid_to_str (pid_to_ptid (pid)));
5544 printf_unfiltered (_("Attaching to %s\n"),
5545 target_pid_to_str (pid_to_ptid (pid)));
5547 gdb_flush (gdb_stdout);
5550 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
5552 getpkt (&rs->buf, &rs->buf_size, 0);
5554 switch (packet_ok (rs->buf,
5555 &remote_protocol_packets[PACKET_vAttach]))
5558 if (!target_is_non_stop_p ())
5560 /* Save the reply for later. */
5561 wait_status = (char *) alloca (strlen (rs->buf) + 1);
5562 strcpy (wait_status, rs->buf);
5564 else if (strcmp (rs->buf, "OK") != 0)
5565 error (_("Attaching to %s failed with: %s"),
5566 target_pid_to_str (pid_to_ptid (pid)),
5569 case PACKET_UNKNOWN:
5570 error (_("This target does not support attaching to a process"));
5572 error (_("Attaching to %s failed"),
5573 target_pid_to_str (pid_to_ptid (pid)));
5576 set_current_inferior (remote_add_inferior (0, pid, 1, 0));
5578 inferior_ptid = pid_to_ptid (pid);
5580 if (target_is_non_stop_p ())
5582 struct thread_info *thread;
5584 /* Get list of threads. */
5585 update_thread_list ();
5587 thread = first_thread_of_process (pid);
5589 inferior_ptid = thread->ptid;
5591 inferior_ptid = pid_to_ptid (pid);
5593 /* Invalidate our notion of the remote current thread. */
5594 record_currthread (rs, minus_one_ptid);
5598 /* Now, if we have thread information, update inferior_ptid. */
5599 inferior_ptid = remote_current_thread (inferior_ptid);
5601 /* Add the main thread to the thread list. */
5602 thread_info *thr = add_thread_silent (inferior_ptid);
5603 /* Don't consider the thread stopped until we've processed the
5604 saved stop reply. */
5605 set_executing (thr->ptid, true);
5608 /* Next, if the target can specify a description, read it. We do
5609 this before anything involving memory or registers. */
5610 target_find_description ();
5612 if (!target_is_non_stop_p ())
5614 /* Use the previously fetched status. */
5615 gdb_assert (wait_status != NULL);
5617 if (target_can_async_p ())
5619 struct notif_event *reply
5620 = remote_notif_parse (¬if_client_stop, wait_status);
5622 push_stop_reply ((struct stop_reply *) reply);
5628 gdb_assert (wait_status != NULL);
5629 strcpy (rs->buf, wait_status);
5630 rs->cached_wait_status = 1;
5634 gdb_assert (wait_status == NULL);
5637 /* Implementation of the to_post_attach method. */
5640 extended_remote_target::post_attach (int pid)
5642 /* Get text, data & bss offsets. */
5645 /* In certain cases GDB might not have had the chance to start
5646 symbol lookup up until now. This could happen if the debugged
5647 binary is not using shared libraries, the vsyscall page is not
5648 present (on Linux) and the binary itself hadn't changed since the
5649 debugging process was started. */
5650 if (symfile_objfile != NULL)
5651 remote_check_symbols();
5655 /* Check for the availability of vCont. This function should also check
5659 remote_vcont_probe (struct remote_state *rs)
5663 strcpy (rs->buf, "vCont?");
5665 getpkt (&rs->buf, &rs->buf_size, 0);
5668 /* Make sure that the features we assume are supported. */
5669 if (startswith (buf, "vCont"))
5672 int support_c, support_C;
5674 rs->supports_vCont.s = 0;
5675 rs->supports_vCont.S = 0;
5678 rs->supports_vCont.t = 0;
5679 rs->supports_vCont.r = 0;
5680 while (p && *p == ';')
5683 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
5684 rs->supports_vCont.s = 1;
5685 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
5686 rs->supports_vCont.S = 1;
5687 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
5689 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
5691 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
5692 rs->supports_vCont.t = 1;
5693 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
5694 rs->supports_vCont.r = 1;
5696 p = strchr (p, ';');
5699 /* If c, and C are not all supported, we can't use vCont. Clearing
5700 BUF will make packet_ok disable the packet. */
5701 if (!support_c || !support_C)
5705 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
5708 /* Helper function for building "vCont" resumptions. Write a
5709 resumption to P. ENDP points to one-passed-the-end of the buffer
5710 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
5711 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
5712 resumed thread should be single-stepped and/or signalled. If PTID
5713 equals minus_one_ptid, then all threads are resumed; if PTID
5714 represents a process, then all threads of the process are resumed;
5715 the thread to be stepped and/or signalled is given in the global
5719 append_resumption (char *p, char *endp,
5720 ptid_t ptid, int step, enum gdb_signal siggnal)
5722 struct remote_state *rs = get_remote_state ();
5724 if (step && siggnal != GDB_SIGNAL_0)
5725 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
5727 /* GDB is willing to range step. */
5728 && use_range_stepping
5729 /* Target supports range stepping. */
5730 && rs->supports_vCont.r
5731 /* We don't currently support range stepping multiple
5732 threads with a wildcard (though the protocol allows it,
5733 so stubs shouldn't make an active effort to forbid
5735 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5737 struct thread_info *tp;
5739 if (ptid_equal (ptid, minus_one_ptid))
5741 /* If we don't know about the target thread's tid, then
5742 we're resuming magic_null_ptid (see caller). */
5743 tp = find_thread_ptid (magic_null_ptid);
5746 tp = find_thread_ptid (ptid);
5747 gdb_assert (tp != NULL);
5749 if (tp->control.may_range_step)
5751 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5753 p += xsnprintf (p, endp - p, ";r%s,%s",
5754 phex_nz (tp->control.step_range_start,
5756 phex_nz (tp->control.step_range_end,
5760 p += xsnprintf (p, endp - p, ";s");
5763 p += xsnprintf (p, endp - p, ";s");
5764 else if (siggnal != GDB_SIGNAL_0)
5765 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
5767 p += xsnprintf (p, endp - p, ";c");
5769 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
5773 /* All (-1) threads of process. */
5774 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
5776 p += xsnprintf (p, endp - p, ":");
5777 p = write_ptid (p, endp, nptid);
5779 else if (!ptid_equal (ptid, minus_one_ptid))
5781 p += xsnprintf (p, endp - p, ":");
5782 p = write_ptid (p, endp, ptid);
5788 /* Clear the thread's private info on resume. */
5791 resume_clear_thread_private_info (struct thread_info *thread)
5793 if (thread->priv != NULL)
5795 remote_thread_info *priv = get_remote_thread_info (thread);
5797 priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
5798 priv->watch_data_address = 0;
5802 /* Append a vCont continue-with-signal action for threads that have a
5803 non-zero stop signal. */
5806 append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
5808 struct thread_info *thread;
5810 ALL_NON_EXITED_THREADS (thread)
5811 if (ptid_match (thread->ptid, ptid)
5812 && !ptid_equal (inferior_ptid, thread->ptid)
5813 && thread->suspend.stop_signal != GDB_SIGNAL_0)
5815 p = append_resumption (p, endp, thread->ptid,
5816 0, thread->suspend.stop_signal);
5817 thread->suspend.stop_signal = GDB_SIGNAL_0;
5818 resume_clear_thread_private_info (thread);
5824 /* Set the target running, using the packets that use Hc
5828 remote_resume_with_hc (struct target_ops *ops,
5829 ptid_t ptid, int step, enum gdb_signal siggnal)
5831 struct remote_state *rs = get_remote_state ();
5832 struct thread_info *thread;
5835 rs->last_sent_signal = siggnal;
5836 rs->last_sent_step = step;
5838 /* The c/s/C/S resume packets use Hc, so set the continue
5840 if (ptid_equal (ptid, minus_one_ptid))
5841 set_continue_thread (any_thread_ptid);
5843 set_continue_thread (ptid);
5845 ALL_NON_EXITED_THREADS (thread)
5846 resume_clear_thread_private_info (thread);
5849 if (execution_direction == EXEC_REVERSE)
5851 /* We don't pass signals to the target in reverse exec mode. */
5852 if (info_verbose && siggnal != GDB_SIGNAL_0)
5853 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
5856 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
5857 error (_("Remote reverse-step not supported."));
5858 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
5859 error (_("Remote reverse-continue not supported."));
5861 strcpy (buf, step ? "bs" : "bc");
5863 else if (siggnal != GDB_SIGNAL_0)
5865 buf[0] = step ? 'S' : 'C';
5866 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
5867 buf[2] = tohex (((int) siggnal) & 0xf);
5871 strcpy (buf, step ? "s" : "c");
5876 /* Resume the remote inferior by using a "vCont" packet. The thread
5877 to be resumed is PTID; STEP and SIGGNAL indicate whether the
5878 resumed thread should be single-stepped and/or signalled. If PTID
5879 equals minus_one_ptid, then all threads are resumed; the thread to
5880 be stepped and/or signalled is given in the global INFERIOR_PTID.
5881 This function returns non-zero iff it resumes the inferior.
5883 This function issues a strict subset of all possible vCont commands
5887 remote_resume_with_vcont (ptid_t ptid, int step, enum gdb_signal siggnal)
5889 struct remote_state *rs = get_remote_state ();
5893 /* No reverse execution actions defined for vCont. */
5894 if (execution_direction == EXEC_REVERSE)
5897 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
5898 remote_vcont_probe (rs);
5900 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
5904 endp = rs->buf + get_remote_packet_size ();
5906 /* If we could generate a wider range of packets, we'd have to worry
5907 about overflowing BUF. Should there be a generic
5908 "multi-part-packet" packet? */
5910 p += xsnprintf (p, endp - p, "vCont");
5912 if (ptid_equal (ptid, magic_null_ptid))
5914 /* MAGIC_NULL_PTID means that we don't have any active threads,
5915 so we don't have any TID numbers the inferior will
5916 understand. Make sure to only send forms that do not specify
5918 append_resumption (p, endp, minus_one_ptid, step, siggnal);
5920 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
5922 /* Resume all threads (of all processes, or of a single
5923 process), with preference for INFERIOR_PTID. This assumes
5924 inferior_ptid belongs to the set of all threads we are about
5926 if (step || siggnal != GDB_SIGNAL_0)
5928 /* Step inferior_ptid, with or without signal. */
5929 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
5932 /* Also pass down any pending signaled resumption for other
5933 threads not the current. */
5934 p = append_pending_thread_resumptions (p, endp, ptid);
5936 /* And continue others without a signal. */
5937 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
5941 /* Scheduler locking; resume only PTID. */
5942 append_resumption (p, endp, ptid, step, siggnal);
5945 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
5948 if (target_is_non_stop_p ())
5950 /* In non-stop, the stub replies to vCont with "OK". The stop
5951 reply will be reported asynchronously by means of a `%Stop'
5953 getpkt (&rs->buf, &rs->buf_size, 0);
5954 if (strcmp (rs->buf, "OK") != 0)
5955 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5961 /* Tell the remote machine to resume. */
5964 remote_target::resume (ptid_t ptid, int step, enum gdb_signal siggnal)
5966 struct remote_state *rs = get_remote_state ();
5968 /* When connected in non-stop mode, the core resumes threads
5969 individually. Resuming remote threads directly in target_resume
5970 would thus result in sending one packet per thread. Instead, to
5971 minimize roundtrip latency, here we just store the resume
5972 request; the actual remote resumption will be done in
5973 target_commit_resume / remote_commit_resume, where we'll be able
5974 to do vCont action coalescing. */
5975 if (target_is_non_stop_p () && ::execution_direction != EXEC_REVERSE)
5977 remote_thread_info *remote_thr;
5979 if (ptid_equal (minus_one_ptid, ptid) || ptid_is_pid (ptid))
5980 remote_thr = get_remote_thread_info (inferior_ptid);
5982 remote_thr = get_remote_thread_info (ptid);
5984 remote_thr->last_resume_step = step;
5985 remote_thr->last_resume_sig = siggnal;
5989 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
5990 (explained in remote-notif.c:handle_notification) so
5991 remote_notif_process is not called. We need find a place where
5992 it is safe to start a 'vNotif' sequence. It is good to do it
5993 before resuming inferior, because inferior was stopped and no RSP
5994 traffic at that moment. */
5995 if (!target_is_non_stop_p ())
5996 remote_notif_process (rs->notif_state, ¬if_client_stop);
5998 rs->last_resume_exec_dir = ::execution_direction;
6000 /* Prefer vCont, and fallback to s/c/S/C, which use Hc. */
6001 if (!remote_resume_with_vcont (ptid, step, siggnal))
6002 remote_resume_with_hc (this, ptid, step, siggnal);
6004 /* We are about to start executing the inferior, let's register it
6005 with the event loop. NOTE: this is the one place where all the
6006 execution commands end up. We could alternatively do this in each
6007 of the execution commands in infcmd.c. */
6008 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
6009 into infcmd.c in order to allow inferior function calls to work
6010 NOT asynchronously. */
6011 if (target_can_async_p ())
6014 /* We've just told the target to resume. The remote server will
6015 wait for the inferior to stop, and then send a stop reply. In
6016 the mean time, we can't start another command/query ourselves
6017 because the stub wouldn't be ready to process it. This applies
6018 only to the base all-stop protocol, however. In non-stop (which
6019 only supports vCont), the stub replies with an "OK", and is
6020 immediate able to process further serial input. */
6021 if (!target_is_non_stop_p ())
6022 rs->waiting_for_stop_reply = 1;
6025 static void check_pending_events_prevent_wildcard_vcont
6026 (int *may_global_wildcard_vcont);
6027 static int is_pending_fork_parent_thread (struct thread_info *thread);
6029 /* Private per-inferior info for target remote processes. */
6031 struct remote_inferior : public private_inferior
6033 /* Whether we can send a wildcard vCont for this process. */
6034 bool may_wildcard_vcont = true;
6037 /* Get the remote private inferior data associated to INF. */
6039 static remote_inferior *
6040 get_remote_inferior (inferior *inf)
6042 if (inf->priv == NULL)
6043 inf->priv.reset (new remote_inferior);
6045 return static_cast<remote_inferior *> (inf->priv.get ());
6048 /* Structure used to track the construction of a vCont packet in the
6049 outgoing packet buffer. This is used to send multiple vCont
6050 packets if we have more actions than would fit a single packet. */
6052 struct vcont_builder
6054 /* Pointer to the first action. P points here if no action has been
6058 /* Where the next action will be appended. */
6061 /* The end of the buffer. Must never write past this. */
6065 /* Prepare the outgoing buffer for a new vCont packet. */
6068 vcont_builder_restart (struct vcont_builder *builder)
6070 struct remote_state *rs = get_remote_state ();
6072 builder->p = rs->buf;
6073 builder->endp = rs->buf + get_remote_packet_size ();
6074 builder->p += xsnprintf (builder->p, builder->endp - builder->p, "vCont");
6075 builder->first_action = builder->p;
6078 /* If the vCont packet being built has any action, send it to the
6082 vcont_builder_flush (struct vcont_builder *builder)
6084 struct remote_state *rs;
6086 if (builder->p == builder->first_action)
6089 rs = get_remote_state ();
6091 getpkt (&rs->buf, &rs->buf_size, 0);
6092 if (strcmp (rs->buf, "OK") != 0)
6093 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
6096 /* The largest action is range-stepping, with its two addresses. This
6097 is more than sufficient. If a new, bigger action is created, it'll
6098 quickly trigger a failed assertion in append_resumption (and we'll
6100 #define MAX_ACTION_SIZE 200
6102 /* Append a new vCont action in the outgoing packet being built. If
6103 the action doesn't fit the packet along with previous actions, push
6104 what we've got so far to the remote end and start over a new vCont
6105 packet (with the new action). */
6108 vcont_builder_push_action (struct vcont_builder *builder,
6109 ptid_t ptid, int step, enum gdb_signal siggnal)
6111 char buf[MAX_ACTION_SIZE + 1];
6115 endp = append_resumption (buf, buf + sizeof (buf),
6116 ptid, step, siggnal);
6118 /* Check whether this new action would fit in the vCont packet along
6119 with previous actions. If not, send what we've got so far and
6120 start a new vCont packet. */
6122 if (rsize > builder->endp - builder->p)
6124 vcont_builder_flush (builder);
6125 vcont_builder_restart (builder);
6127 /* Should now fit. */
6128 gdb_assert (rsize <= builder->endp - builder->p);
6131 memcpy (builder->p, buf, rsize);
6132 builder->p += rsize;
6136 /* to_commit_resume implementation. */
6139 remote_target::commit_resume ()
6141 struct inferior *inf;
6142 struct thread_info *tp;
6143 int any_process_wildcard;
6144 int may_global_wildcard_vcont;
6145 struct vcont_builder vcont_builder;
6147 /* If connected in all-stop mode, we'd send the remote resume
6148 request directly from remote_resume. Likewise if
6149 reverse-debugging, as there are no defined vCont actions for
6150 reverse execution. */
6151 if (!target_is_non_stop_p () || ::execution_direction == EXEC_REVERSE)
6154 /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
6155 instead of resuming all threads of each process individually.
6156 However, if any thread of a process must remain halted, we can't
6157 send wildcard resumes and must send one action per thread.
6159 Care must be taken to not resume threads/processes the server
6160 side already told us are stopped, but the core doesn't know about
6161 yet, because the events are still in the vStopped notification
6164 #1 => vCont s:p1.1;c
6166 #3 <= %Stopped T05 p1.1
6171 #8 (infrun handles the stop for p1.1 and continues stepping)
6172 #9 => vCont s:p1.1;c
6174 The last vCont above would resume thread p1.2 by mistake, because
6175 the server has no idea that the event for p1.2 had not been
6178 The server side must similarly ignore resume actions for the
6179 thread that has a pending %Stopped notification (and any other
6180 threads with events pending), until GDB acks the notification
6181 with vStopped. Otherwise, e.g., the following case is
6184 #1 => g (or any other packet)
6186 #3 <= %Stopped T05 p1.2
6187 #4 => vCont s:p1.1;c
6190 Above, the server must not resume thread p1.2. GDB can't know
6191 that p1.2 stopped until it acks the %Stopped notification, and
6192 since from GDB's perspective all threads should be running, it
6195 Finally, special care must also be given to handling fork/vfork
6196 events. A (v)fork event actually tells us that two processes
6197 stopped -- the parent and the child. Until we follow the fork,
6198 we must not resume the child. Therefore, if we have a pending
6199 fork follow, we must not send a global wildcard resume action
6200 (vCont;c). We can still send process-wide wildcards though. */
6202 /* Start by assuming a global wildcard (vCont;c) is possible. */
6203 may_global_wildcard_vcont = 1;
6205 /* And assume every process is individually wildcard-able too. */
6206 ALL_NON_EXITED_INFERIORS (inf)
6208 remote_inferior *priv = get_remote_inferior (inf);
6210 priv->may_wildcard_vcont = true;
6213 /* Check for any pending events (not reported or processed yet) and
6214 disable process and global wildcard resumes appropriately. */
6215 check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
6217 ALL_NON_EXITED_THREADS (tp)
6219 /* If a thread of a process is not meant to be resumed, then we
6220 can't wildcard that process. */
6223 get_remote_inferior (tp->inf)->may_wildcard_vcont = false;
6225 /* And if we can't wildcard a process, we can't wildcard
6226 everything either. */
6227 may_global_wildcard_vcont = 0;
6231 /* If a thread is the parent of an unfollowed fork, then we
6232 can't do a global wildcard, as that would resume the fork
6234 if (is_pending_fork_parent_thread (tp))
6235 may_global_wildcard_vcont = 0;
6238 /* Now let's build the vCont packet(s). Actions must be appended
6239 from narrower to wider scopes (thread -> process -> global). If
6240 we end up with too many actions for a single packet vcont_builder
6241 flushes the current vCont packet to the remote side and starts a
6243 vcont_builder_restart (&vcont_builder);
6245 /* Threads first. */
6246 ALL_NON_EXITED_THREADS (tp)
6248 remote_thread_info *remote_thr = get_remote_thread_info (tp);
6250 if (!tp->executing || remote_thr->vcont_resumed)
6253 gdb_assert (!thread_is_in_step_over_chain (tp));
6255 if (!remote_thr->last_resume_step
6256 && remote_thr->last_resume_sig == GDB_SIGNAL_0
6257 && get_remote_inferior (tp->inf)->may_wildcard_vcont)
6259 /* We'll send a wildcard resume instead. */
6260 remote_thr->vcont_resumed = 1;
6264 vcont_builder_push_action (&vcont_builder, tp->ptid,
6265 remote_thr->last_resume_step,
6266 remote_thr->last_resume_sig);
6267 remote_thr->vcont_resumed = 1;
6270 /* Now check whether we can send any process-wide wildcard. This is
6271 to avoid sending a global wildcard in the case nothing is
6272 supposed to be resumed. */
6273 any_process_wildcard = 0;
6275 ALL_NON_EXITED_INFERIORS (inf)
6277 if (get_remote_inferior (inf)->may_wildcard_vcont)
6279 any_process_wildcard = 1;
6284 if (any_process_wildcard)
6286 /* If all processes are wildcard-able, then send a single "c"
6287 action, otherwise, send an "all (-1) threads of process"
6288 continue action for each running process, if any. */
6289 if (may_global_wildcard_vcont)
6291 vcont_builder_push_action (&vcont_builder, minus_one_ptid,
6296 ALL_NON_EXITED_INFERIORS (inf)
6298 if (get_remote_inferior (inf)->may_wildcard_vcont)
6300 vcont_builder_push_action (&vcont_builder,
6301 pid_to_ptid (inf->pid),
6308 vcont_builder_flush (&vcont_builder);
6313 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
6314 thread, all threads of a remote process, or all threads of all
6318 remote_stop_ns (ptid_t ptid)
6320 struct remote_state *rs = get_remote_state ();
6322 char *endp = rs->buf + get_remote_packet_size ();
6324 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6325 remote_vcont_probe (rs);
6327 if (!rs->supports_vCont.t)
6328 error (_("Remote server does not support stopping threads"));
6330 if (ptid_equal (ptid, minus_one_ptid)
6331 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
6332 p += xsnprintf (p, endp - p, "vCont;t");
6337 p += xsnprintf (p, endp - p, "vCont;t:");
6339 if (ptid_is_pid (ptid))
6340 /* All (-1) threads of process. */
6341 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
6344 /* Small optimization: if we already have a stop reply for
6345 this thread, no use in telling the stub we want this
6347 if (peek_stop_reply (ptid))
6353 write_ptid (p, endp, nptid);
6356 /* In non-stop, we get an immediate OK reply. The stop reply will
6357 come in asynchronously by notification. */
6359 getpkt (&rs->buf, &rs->buf_size, 0);
6360 if (strcmp (rs->buf, "OK") != 0)
6361 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
6364 /* All-stop version of target_interrupt. Sends a break or a ^C to
6365 interrupt the remote target. It is undefined which thread of which
6366 process reports the interrupt. */
6369 remote_interrupt_as (void)
6371 struct remote_state *rs = get_remote_state ();
6373 rs->ctrlc_pending_p = 1;
6375 /* If the inferior is stopped already, but the core didn't know
6376 about it yet, just ignore the request. The cached wait status
6377 will be collected in remote_wait. */
6378 if (rs->cached_wait_status)
6381 /* Send interrupt_sequence to remote target. */
6382 send_interrupt_sequence ();
6385 /* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
6386 the remote target. It is undefined which thread of which process
6387 reports the interrupt. Throws an error if the packet is not
6388 supported by the server. */
6391 remote_interrupt_ns (void)
6393 struct remote_state *rs = get_remote_state ();
6395 char *endp = rs->buf + get_remote_packet_size ();
6397 xsnprintf (p, endp - p, "vCtrlC");
6399 /* In non-stop, we get an immediate OK reply. The stop reply will
6400 come in asynchronously by notification. */
6402 getpkt (&rs->buf, &rs->buf_size, 0);
6404 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
6408 case PACKET_UNKNOWN:
6409 error (_("No support for interrupting the remote target."));
6411 error (_("Interrupting target failed: %s"), rs->buf);
6415 /* Implement the to_stop function for the remote targets. */
6418 remote_target::stop (ptid_t ptid)
6421 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
6423 if (target_is_non_stop_p ())
6424 remote_stop_ns (ptid);
6427 /* We don't currently have a way to transparently pause the
6428 remote target in all-stop mode. Interrupt it instead. */
6429 remote_interrupt_as ();
6433 /* Implement the to_interrupt function for the remote targets. */
6436 remote_target::interrupt ()
6439 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
6441 if (target_is_non_stop_p ())
6442 remote_interrupt_ns ();
6444 remote_interrupt_as ();
6447 /* Implement the to_pass_ctrlc function for the remote targets. */
6450 remote_target::pass_ctrlc ()
6452 struct remote_state *rs = get_remote_state ();
6455 fprintf_unfiltered (gdb_stdlog, "remote_pass_ctrlc called\n");
6457 /* If we're starting up, we're not fully synced yet. Quit
6459 if (rs->starting_up)
6461 /* If ^C has already been sent once, offer to disconnect. */
6462 else if (rs->ctrlc_pending_p)
6465 target_interrupt ();
6468 /* Ask the user what to do when an interrupt is received. */
6471 interrupt_query (void)
6473 struct remote_state *rs = get_remote_state ();
6475 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
6477 if (query (_("The target is not responding to interrupt requests.\n"
6478 "Stop debugging it? ")))
6480 remote_unpush_target ();
6481 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
6486 if (query (_("Interrupted while waiting for the program.\n"
6487 "Give up waiting? ")))
6492 /* Enable/disable target terminal ownership. Most targets can use
6493 terminal groups to control terminal ownership. Remote targets are
6494 different in that explicit transfer of ownership to/from GDB/target
6498 remote_target::terminal_inferior ()
6500 /* NOTE: At this point we could also register our selves as the
6501 recipient of all input. Any characters typed could then be
6502 passed on down to the target. */
6506 remote_target::terminal_ours ()
6511 remote_console_output (char *msg)
6515 for (p = msg; p[0] && p[1]; p += 2)
6518 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
6522 fputs_unfiltered (tb, gdb_stdtarg);
6524 gdb_flush (gdb_stdtarg);
6527 DEF_VEC_O(cached_reg_t);
6529 typedef struct stop_reply
6531 struct notif_event base;
6533 /* The identifier of the thread about this event */
6536 /* The remote state this event is associated with. When the remote
6537 connection, represented by a remote_state object, is closed,
6538 all the associated stop_reply events should be released. */
6539 struct remote_state *rs;
6541 struct target_waitstatus ws;
6543 /* The architecture associated with the expedited registers. */
6546 /* Expedited registers. This makes remote debugging a bit more
6547 efficient for those targets that provide critical registers as
6548 part of their normal status mechanism (as another roundtrip to
6549 fetch them is avoided). */
6550 VEC(cached_reg_t) *regcache;
6552 enum target_stop_reason stop_reason;
6554 CORE_ADDR watch_data_address;
6559 DECLARE_QUEUE_P (stop_reply_p);
6560 DEFINE_QUEUE_P (stop_reply_p);
6561 /* The list of already fetched and acknowledged stop events. This
6562 queue is used for notification Stop, and other notifications
6563 don't need queue for their events, because the notification events
6564 of Stop can't be consumed immediately, so that events should be
6565 queued first, and be consumed by remote_wait_{ns,as} one per
6566 time. Other notifications can consume their events immediately,
6567 so queue is not needed for them. */
6568 static QUEUE (stop_reply_p) *stop_reply_queue;
6571 stop_reply_xfree (struct stop_reply *r)
6573 notif_event_xfree ((struct notif_event *) r);
6576 /* Return the length of the stop reply queue. */
6579 stop_reply_queue_length (void)
6581 return QUEUE_length (stop_reply_p, stop_reply_queue);
6585 remote_notif_stop_parse (struct notif_client *self, char *buf,
6586 struct notif_event *event)
6588 remote_parse_stop_reply (buf, (struct stop_reply *) event);
6592 remote_notif_stop_ack (struct notif_client *self, char *buf,
6593 struct notif_event *event)
6595 struct stop_reply *stop_reply = (struct stop_reply *) event;
6598 putpkt (self->ack_command);
6600 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
6601 /* We got an unknown stop reply. */
6602 error (_("Unknown stop reply"));
6604 push_stop_reply (stop_reply);
6608 remote_notif_stop_can_get_pending_events (struct notif_client *self)
6610 /* We can't get pending events in remote_notif_process for
6611 notification stop, and we have to do this in remote_wait_ns
6612 instead. If we fetch all queued events from stub, remote stub
6613 may exit and we have no chance to process them back in
6615 mark_async_event_handler (remote_async_inferior_event_token);
6620 stop_reply_dtr (struct notif_event *event)
6622 struct stop_reply *r = (struct stop_reply *) event;
6627 VEC_iterate (cached_reg_t, r->regcache, ix, reg);
6631 VEC_free (cached_reg_t, r->regcache);
6634 static struct notif_event *
6635 remote_notif_stop_alloc_reply (void)
6637 /* We cast to a pointer to the "base class". */
6638 struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
6640 r->dtr = stop_reply_dtr;
6645 /* A client of notification Stop. */
6647 struct notif_client notif_client_stop =
6651 remote_notif_stop_parse,
6652 remote_notif_stop_ack,
6653 remote_notif_stop_can_get_pending_events,
6654 remote_notif_stop_alloc_reply,
6658 /* A parameter to pass data in and out. */
6660 struct queue_iter_param
6663 struct stop_reply *output;
6666 /* Determine if THREAD_PTID is a pending fork parent thread. ARG contains
6667 the pid of the process that owns the threads we want to check, or
6668 -1 if we want to check all threads. */
6671 is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
6674 if (ws->kind == TARGET_WAITKIND_FORKED
6675 || ws->kind == TARGET_WAITKIND_VFORKED)
6677 if (event_pid == -1 || event_pid == ptid_get_pid (thread_ptid))
6684 /* Return the thread's pending status used to determine whether the
6685 thread is a fork parent stopped at a fork event. */
6687 static struct target_waitstatus *
6688 thread_pending_fork_status (struct thread_info *thread)
6690 if (thread->suspend.waitstatus_pending_p)
6691 return &thread->suspend.waitstatus;
6693 return &thread->pending_follow;
6696 /* Determine if THREAD is a pending fork parent thread. */
6699 is_pending_fork_parent_thread (struct thread_info *thread)
6701 struct target_waitstatus *ws = thread_pending_fork_status (thread);
6704 return is_pending_fork_parent (ws, pid, thread->ptid);
6707 /* Check whether EVENT is a fork event, and if it is, remove the
6708 fork child from the context list passed in DATA. */
6711 remove_child_of_pending_fork (QUEUE (stop_reply_p) *q,
6712 QUEUE_ITER (stop_reply_p) *iter,
6716 struct queue_iter_param *param = (struct queue_iter_param *) data;
6717 struct threads_listing_context *context
6718 = (struct threads_listing_context *) param->input;
6720 if (event->ws.kind == TARGET_WAITKIND_FORKED
6721 || event->ws.kind == TARGET_WAITKIND_VFORKED
6722 || event->ws.kind == TARGET_WAITKIND_THREAD_EXITED)
6723 context->remove_thread (event->ws.value.related_pid);
6728 /* If CONTEXT contains any fork child threads that have not been
6729 reported yet, remove them from the CONTEXT list. If such a
6730 thread exists it is because we are stopped at a fork catchpoint
6731 and have not yet called follow_fork, which will set up the
6732 host-side data structures for the new process. */
6735 remove_new_fork_children (struct threads_listing_context *context)
6737 struct thread_info * thread;
6739 struct notif_client *notif = ¬if_client_stop;
6740 struct queue_iter_param param;
6742 /* For any threads stopped at a fork event, remove the corresponding
6743 fork child threads from the CONTEXT list. */
6744 ALL_NON_EXITED_THREADS (thread)
6746 struct target_waitstatus *ws = thread_pending_fork_status (thread);
6748 if (is_pending_fork_parent (ws, pid, thread->ptid))
6749 context->remove_thread (ws->value.related_pid);
6752 /* Check for any pending fork events (not reported or processed yet)
6753 in process PID and remove those fork child threads from the
6754 CONTEXT list as well. */
6755 remote_notif_get_pending_events (notif);
6756 param.input = context;
6757 param.output = NULL;
6758 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6759 remove_child_of_pending_fork, ¶m);
6762 /* Check whether EVENT would prevent a global or process wildcard
6766 check_pending_event_prevents_wildcard_vcont_callback
6767 (QUEUE (stop_reply_p) *q,
6768 QUEUE_ITER (stop_reply_p) *iter,
6772 struct inferior *inf;
6773 int *may_global_wildcard_vcont = (int *) data;
6775 if (event->ws.kind == TARGET_WAITKIND_NO_RESUMED
6776 || event->ws.kind == TARGET_WAITKIND_NO_HISTORY)
6779 if (event->ws.kind == TARGET_WAITKIND_FORKED
6780 || event->ws.kind == TARGET_WAITKIND_VFORKED)
6781 *may_global_wildcard_vcont = 0;
6783 inf = find_inferior_ptid (event->ptid);
6785 /* This may be the first time we heard about this process.
6786 Regardless, we must not do a global wildcard resume, otherwise
6787 we'd resume this process too. */
6788 *may_global_wildcard_vcont = 0;
6790 get_remote_inferior (inf)->may_wildcard_vcont = false;
6795 /* Check whether any event pending in the vStopped queue would prevent
6796 a global or process wildcard vCont action. Clear
6797 *may_global_wildcard if we can't do a global wildcard (vCont;c),
6798 and clear the event inferior's may_wildcard_vcont flag if we can't
6799 do a process-wide wildcard resume (vCont;c:pPID.-1). */
6802 check_pending_events_prevent_wildcard_vcont (int *may_global_wildcard)
6804 struct notif_client *notif = ¬if_client_stop;
6806 remote_notif_get_pending_events (notif);
6807 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6808 check_pending_event_prevents_wildcard_vcont_callback,
6809 may_global_wildcard);
6812 /* Remove stop replies in the queue if its pid is equal to the given
6816 remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
6817 QUEUE_ITER (stop_reply_p) *iter,
6821 struct queue_iter_param *param = (struct queue_iter_param *) data;
6822 struct inferior *inf = (struct inferior *) param->input;
6824 if (ptid_get_pid (event->ptid) == inf->pid)
6826 stop_reply_xfree (event);
6827 QUEUE_remove_elem (stop_reply_p, q, iter);
6833 /* Discard all pending stop replies of inferior INF. */
6836 discard_pending_stop_replies (struct inferior *inf)
6838 struct queue_iter_param param;
6839 struct stop_reply *reply;
6840 struct remote_state *rs = get_remote_state ();
6841 struct remote_notif_state *rns = rs->notif_state;
6843 /* This function can be notified when an inferior exists. When the
6844 target is not remote, the notification state is NULL. */
6845 if (rs->remote_desc == NULL)
6848 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
6850 /* Discard the in-flight notification. */
6851 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
6853 stop_reply_xfree (reply);
6854 rns->pending_event[notif_client_stop.id] = NULL;
6858 param.output = NULL;
6859 /* Discard the stop replies we have already pulled with
6861 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6862 remove_stop_reply_for_inferior, ¶m);
6865 /* If its remote state is equal to the given remote state,
6866 remove EVENT from the stop reply queue. */
6869 remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
6870 QUEUE_ITER (stop_reply_p) *iter,
6874 struct queue_iter_param *param = (struct queue_iter_param *) data;
6875 struct remote_state *rs = (struct remote_state *) param->input;
6877 if (event->rs == rs)
6879 stop_reply_xfree (event);
6880 QUEUE_remove_elem (stop_reply_p, q, iter);
6886 /* Discard the stop replies for RS in stop_reply_queue. */
6889 discard_pending_stop_replies_in_queue (struct remote_state *rs)
6891 struct queue_iter_param param;
6894 param.output = NULL;
6895 /* Discard the stop replies we have already pulled with
6897 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6898 remove_stop_reply_of_remote_state, ¶m);
6901 /* A parameter to pass data in and out. */
6904 remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
6905 QUEUE_ITER (stop_reply_p) *iter,
6909 struct queue_iter_param *param = (struct queue_iter_param *) data;
6910 ptid_t *ptid = (ptid_t *) param->input;
6912 if (ptid_match (event->ptid, *ptid))
6914 param->output = event;
6915 QUEUE_remove_elem (stop_reply_p, q, iter);
6922 /* Remove the first reply in 'stop_reply_queue' which matches
6925 static struct stop_reply *
6926 remote_notif_remove_queued_reply (ptid_t ptid)
6928 struct queue_iter_param param;
6930 param.input = &ptid;
6931 param.output = NULL;
6933 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6934 remote_notif_remove_once_on_match, ¶m);
6936 fprintf_unfiltered (gdb_stdlog,
6937 "notif: discard queued event: 'Stop' in %s\n",
6938 target_pid_to_str (ptid));
6940 return param.output;
6943 /* Look for a queued stop reply belonging to PTID. If one is found,
6944 remove it from the queue, and return it. Returns NULL if none is
6945 found. If there are still queued events left to process, tell the
6946 event loop to get back to target_wait soon. */
6948 static struct stop_reply *
6949 queued_stop_reply (ptid_t ptid)
6951 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
6953 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
6954 /* There's still at least an event left. */
6955 mark_async_event_handler (remote_async_inferior_event_token);
6960 /* Push a fully parsed stop reply in the stop reply queue. Since we
6961 know that we now have at least one queued event left to pass to the
6962 core side, tell the event loop to get back to target_wait soon. */
6965 push_stop_reply (struct stop_reply *new_event)
6967 QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
6970 fprintf_unfiltered (gdb_stdlog,
6971 "notif: push 'Stop' %s to queue %d\n",
6972 target_pid_to_str (new_event->ptid),
6973 QUEUE_length (stop_reply_p,
6976 mark_async_event_handler (remote_async_inferior_event_token);
6980 stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
6981 QUEUE_ITER (stop_reply_p) *iter,
6982 struct stop_reply *event,
6985 ptid_t *ptid = (ptid_t *) data;
6987 return !(ptid_equal (*ptid, event->ptid)
6988 && event->ws.kind == TARGET_WAITKIND_STOPPED);
6991 /* Returns true if we have a stop reply for PTID. */
6994 peek_stop_reply (ptid_t ptid)
6996 return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
6997 stop_reply_match_ptid_and_ws, &ptid);
7000 /* Helper for remote_parse_stop_reply. Return nonzero if the substring
7001 starting with P and ending with PEND matches PREFIX. */
7004 strprefix (const char *p, const char *pend, const char *prefix)
7006 for ( ; p < pend; p++, prefix++)
7009 return *prefix == '\0';
7012 /* Parse the stop reply in BUF. Either the function succeeds, and the
7013 result is stored in EVENT, or throws an error. */
7016 remote_parse_stop_reply (char *buf, struct stop_reply *event)
7018 remote_arch_state *rsa = NULL;
7023 event->ptid = null_ptid;
7024 event->rs = get_remote_state ();
7025 event->ws.kind = TARGET_WAITKIND_IGNORE;
7026 event->ws.value.integer = 0;
7027 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
7028 event->regcache = NULL;
7033 case 'T': /* Status with PC, SP, FP, ... */
7034 /* Expedited reply, containing Signal, {regno, reg} repeat. */
7035 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
7037 n... = register number
7038 r... = register contents
7041 p = &buf[3]; /* after Txx */
7047 p1 = strchr (p, ':');
7049 error (_("Malformed packet(a) (missing colon): %s\n\
7053 error (_("Malformed packet(a) (missing register number): %s\n\
7057 /* Some "registers" are actually extended stop information.
7058 Note if you're adding a new entry here: GDB 7.9 and
7059 earlier assume that all register "numbers" that start
7060 with an hex digit are real register numbers. Make sure
7061 the server only sends such a packet if it knows the
7062 client understands it. */
7064 if (strprefix (p, p1, "thread"))
7065 event->ptid = read_ptid (++p1, &p);
7066 else if (strprefix (p, p1, "syscall_entry"))
7070 event->ws.kind = TARGET_WAITKIND_SYSCALL_ENTRY;
7071 p = unpack_varlen_hex (++p1, &sysno);
7072 event->ws.value.syscall_number = (int) sysno;
7074 else if (strprefix (p, p1, "syscall_return"))
7078 event->ws.kind = TARGET_WAITKIND_SYSCALL_RETURN;
7079 p = unpack_varlen_hex (++p1, &sysno);
7080 event->ws.value.syscall_number = (int) sysno;
7082 else if (strprefix (p, p1, "watch")
7083 || strprefix (p, p1, "rwatch")
7084 || strprefix (p, p1, "awatch"))
7086 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
7087 p = unpack_varlen_hex (++p1, &addr);
7088 event->watch_data_address = (CORE_ADDR) addr;
7090 else if (strprefix (p, p1, "swbreak"))
7092 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
7094 /* Make sure the stub doesn't forget to indicate support
7096 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
7097 error (_("Unexpected swbreak stop reason"));
7099 /* The value part is documented as "must be empty",
7100 though we ignore it, in case we ever decide to make
7101 use of it in a backward compatible way. */
7102 p = strchrnul (p1 + 1, ';');
7104 else if (strprefix (p, p1, "hwbreak"))
7106 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
7108 /* Make sure the stub doesn't forget to indicate support
7110 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
7111 error (_("Unexpected hwbreak stop reason"));
7114 p = strchrnul (p1 + 1, ';');
7116 else if (strprefix (p, p1, "library"))
7118 event->ws.kind = TARGET_WAITKIND_LOADED;
7119 p = strchrnul (p1 + 1, ';');
7121 else if (strprefix (p, p1, "replaylog"))
7123 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
7124 /* p1 will indicate "begin" or "end", but it makes
7125 no difference for now, so ignore it. */
7126 p = strchrnul (p1 + 1, ';');
7128 else if (strprefix (p, p1, "core"))
7132 p = unpack_varlen_hex (++p1, &c);
7135 else if (strprefix (p, p1, "fork"))
7137 event->ws.value.related_pid = read_ptid (++p1, &p);
7138 event->ws.kind = TARGET_WAITKIND_FORKED;
7140 else if (strprefix (p, p1, "vfork"))
7142 event->ws.value.related_pid = read_ptid (++p1, &p);
7143 event->ws.kind = TARGET_WAITKIND_VFORKED;
7145 else if (strprefix (p, p1, "vforkdone"))
7147 event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
7148 p = strchrnul (p1 + 1, ';');
7150 else if (strprefix (p, p1, "exec"))
7153 char pathname[PATH_MAX];
7156 /* Determine the length of the execd pathname. */
7157 p = unpack_varlen_hex (++p1, &ignored);
7158 pathlen = (p - p1) / 2;
7160 /* Save the pathname for event reporting and for
7161 the next run command. */
7162 hex2bin (p1, (gdb_byte *) pathname, pathlen);
7163 pathname[pathlen] = '\0';
7165 /* This is freed during event handling. */
7166 event->ws.value.execd_pathname = xstrdup (pathname);
7167 event->ws.kind = TARGET_WAITKIND_EXECD;
7169 /* Skip the registers included in this packet, since
7170 they may be for an architecture different from the
7171 one used by the original program. */
7174 else if (strprefix (p, p1, "create"))
7176 event->ws.kind = TARGET_WAITKIND_THREAD_CREATED;
7177 p = strchrnul (p1 + 1, ';');
7186 p = strchrnul (p1 + 1, ';');
7191 /* Maybe a real ``P'' register number. */
7192 p_temp = unpack_varlen_hex (p, &pnum);
7193 /* If the first invalid character is the colon, we got a
7194 register number. Otherwise, it's an unknown stop
7198 /* If we haven't parsed the event's thread yet, find
7199 it now, in order to find the architecture of the
7200 reported expedited registers. */
7201 if (event->ptid == null_ptid)
7203 const char *thr = strstr (p1 + 1, ";thread:");
7205 event->ptid = read_ptid (thr + strlen (";thread:"),
7209 /* Either the current thread hasn't changed,
7210 or the inferior is not multi-threaded.
7211 The event must be for the thread we last
7212 set as (or learned as being) current. */
7213 event->ptid = event->rs->general_thread;
7219 inferior *inf = (event->ptid == null_ptid
7221 : find_inferior_ptid (event->ptid));
7222 /* If this is the first time we learn anything
7223 about this process, skip the registers
7224 included in this packet, since we don't yet
7225 know which architecture to use to parse them.
7226 We'll determine the architecture later when
7227 we process the stop reply and retrieve the
7228 target description, via
7229 remote_notice_new_inferior ->
7230 post_create_inferior. */
7233 p = strchrnul (p1 + 1, ';');
7238 event->arch = inf->gdbarch;
7239 rsa = get_remote_arch_state (event->arch);
7243 = packet_reg_from_pnum (event->arch, rsa, pnum);
7244 cached_reg_t cached_reg;
7247 error (_("Remote sent bad register number %s: %s\n\
7249 hex_string (pnum), p, buf);
7251 cached_reg.num = reg->regnum;
7252 cached_reg.data = (gdb_byte *)
7253 xmalloc (register_size (event->arch, reg->regnum));
7256 fieldsize = hex2bin (p, cached_reg.data,
7257 register_size (event->arch, reg->regnum));
7259 if (fieldsize < register_size (event->arch, reg->regnum))
7260 warning (_("Remote reply is too short: %s"), buf);
7262 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
7266 /* Not a number. Silently skip unknown optional
7268 p = strchrnul (p1 + 1, ';');
7273 error (_("Remote register badly formatted: %s\nhere: %s"),
7278 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
7282 case 'S': /* Old style status, just signal only. */
7286 event->ws.kind = TARGET_WAITKIND_STOPPED;
7287 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
7288 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
7289 event->ws.value.sig = (enum gdb_signal) sig;
7291 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
7294 case 'w': /* Thread exited. */
7299 event->ws.kind = TARGET_WAITKIND_THREAD_EXITED;
7300 p = unpack_varlen_hex (&buf[1], &value);
7301 event->ws.value.integer = value;
7303 error (_("stop reply packet badly formatted: %s"), buf);
7304 event->ptid = read_ptid (++p, NULL);
7307 case 'W': /* Target exited. */
7314 /* GDB used to accept only 2 hex chars here. Stubs should
7315 only send more if they detect GDB supports multi-process
7317 p = unpack_varlen_hex (&buf[1], &value);
7321 /* The remote process exited. */
7322 event->ws.kind = TARGET_WAITKIND_EXITED;
7323 event->ws.value.integer = value;
7327 /* The remote process exited with a signal. */
7328 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
7329 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
7330 event->ws.value.sig = (enum gdb_signal) value;
7332 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
7335 /* If no process is specified, assume inferior_ptid. */
7336 pid = ptid_get_pid (inferior_ptid);
7345 else if (startswith (p, "process:"))
7349 p += sizeof ("process:") - 1;
7350 unpack_varlen_hex (p, &upid);
7354 error (_("unknown stop reply packet: %s"), buf);
7357 error (_("unknown stop reply packet: %s"), buf);
7358 event->ptid = pid_to_ptid (pid);
7362 event->ws.kind = TARGET_WAITKIND_NO_RESUMED;
7363 event->ptid = minus_one_ptid;
7367 if (target_is_non_stop_p () && ptid_equal (event->ptid, null_ptid))
7368 error (_("No process or thread specified in stop reply: %s"), buf);
7371 /* When the stub wants to tell GDB about a new notification reply, it
7372 sends a notification (%Stop, for example). Those can come it at
7373 any time, hence, we have to make sure that any pending
7374 putpkt/getpkt sequence we're making is finished, before querying
7375 the stub for more events with the corresponding ack command
7376 (vStopped, for example). E.g., if we started a vStopped sequence
7377 immediately upon receiving the notification, something like this
7385 1.6) <-- (registers reply to step #1.3)
7387 Obviously, the reply in step #1.6 would be unexpected to a vStopped
7390 To solve this, whenever we parse a %Stop notification successfully,
7391 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
7392 doing whatever we were doing:
7398 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
7399 2.5) <-- (registers reply to step #2.3)
7401 Eventualy after step #2.5, we return to the event loop, which
7402 notices there's an event on the
7403 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
7404 associated callback --- the function below. At this point, we're
7405 always safe to start a vStopped sequence. :
7408 2.7) <-- T05 thread:2
7414 remote_notif_get_pending_events (struct notif_client *nc)
7416 struct remote_state *rs = get_remote_state ();
7418 if (rs->notif_state->pending_event[nc->id] != NULL)
7421 fprintf_unfiltered (gdb_stdlog,
7422 "notif: process: '%s' ack pending event\n",
7426 nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
7427 rs->notif_state->pending_event[nc->id] = NULL;
7431 getpkt (&rs->buf, &rs->buf_size, 0);
7432 if (strcmp (rs->buf, "OK") == 0)
7435 remote_notif_ack (nc, rs->buf);
7441 fprintf_unfiltered (gdb_stdlog,
7442 "notif: process: '%s' no pending reply\n",
7447 /* Called when it is decided that STOP_REPLY holds the info of the
7448 event that is to be returned to the core. This function always
7449 destroys STOP_REPLY. */
7452 process_stop_reply (struct stop_reply *stop_reply,
7453 struct target_waitstatus *status)
7457 *status = stop_reply->ws;
7458 ptid = stop_reply->ptid;
7460 /* If no thread/process was reported by the stub, assume the current
7462 if (ptid_equal (ptid, null_ptid))
7463 ptid = inferior_ptid;
7465 if (status->kind != TARGET_WAITKIND_EXITED
7466 && status->kind != TARGET_WAITKIND_SIGNALLED
7467 && status->kind != TARGET_WAITKIND_NO_RESUMED)
7469 /* Expedited registers. */
7470 if (stop_reply->regcache)
7472 struct regcache *regcache
7473 = get_thread_arch_regcache (ptid, stop_reply->arch);
7478 VEC_iterate (cached_reg_t, stop_reply->regcache, ix, reg);
7481 regcache_raw_supply (regcache, reg->num, reg->data);
7485 VEC_free (cached_reg_t, stop_reply->regcache);
7488 remote_notice_new_inferior (ptid, 0);
7489 remote_thread_info *remote_thr = get_remote_thread_info (ptid);
7490 remote_thr->core = stop_reply->core;
7491 remote_thr->stop_reason = stop_reply->stop_reason;
7492 remote_thr->watch_data_address = stop_reply->watch_data_address;
7493 remote_thr->vcont_resumed = 0;
7496 stop_reply_xfree (stop_reply);
7500 /* The non-stop mode version of target_wait. */
7503 remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
7505 struct remote_state *rs = get_remote_state ();
7506 struct stop_reply *stop_reply;
7510 /* If in non-stop mode, get out of getpkt even if a
7511 notification is received. */
7513 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7514 0 /* forever */, &is_notif);
7517 if (ret != -1 && !is_notif)
7520 case 'E': /* Error of some sort. */
7521 /* We're out of sync with the target now. Did it continue
7522 or not? We can't tell which thread it was in non-stop,
7523 so just ignore this. */
7524 warning (_("Remote failure reply: %s"), rs->buf);
7526 case 'O': /* Console output. */
7527 remote_console_output (rs->buf + 1);
7530 warning (_("Invalid remote reply: %s"), rs->buf);
7534 /* Acknowledge a pending stop reply that may have arrived in the
7536 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
7537 remote_notif_get_pending_events (¬if_client_stop);
7539 /* If indeed we noticed a stop reply, we're done. */
7540 stop_reply = queued_stop_reply (ptid);
7541 if (stop_reply != NULL)
7542 return process_stop_reply (stop_reply, status);
7544 /* Still no event. If we're just polling for an event, then
7545 return to the event loop. */
7546 if (options & TARGET_WNOHANG)
7548 status->kind = TARGET_WAITKIND_IGNORE;
7549 return minus_one_ptid;
7552 /* Otherwise do a blocking wait. */
7553 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7554 1 /* forever */, &is_notif);
7558 /* Wait until the remote machine stops, then return, storing status in
7559 STATUS just as `wait' would. */
7562 remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
7564 struct remote_state *rs = get_remote_state ();
7565 ptid_t event_ptid = null_ptid;
7567 struct stop_reply *stop_reply;
7571 status->kind = TARGET_WAITKIND_IGNORE;
7572 status->value.integer = 0;
7574 stop_reply = queued_stop_reply (ptid);
7575 if (stop_reply != NULL)
7576 return process_stop_reply (stop_reply, status);
7578 if (rs->cached_wait_status)
7579 /* Use the cached wait status, but only once. */
7580 rs->cached_wait_status = 0;
7585 int forever = ((options & TARGET_WNOHANG) == 0
7586 && wait_forever_enabled_p);
7588 if (!rs->waiting_for_stop_reply)
7590 status->kind = TARGET_WAITKIND_NO_RESUMED;
7591 return minus_one_ptid;
7594 /* FIXME: cagney/1999-09-27: If we're in async mode we should
7595 _never_ wait for ever -> test on target_is_async_p().
7596 However, before we do that we need to ensure that the caller
7597 knows how to take the target into/out of async mode. */
7598 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7599 forever, &is_notif);
7601 /* GDB gets a notification. Return to core as this event is
7603 if (ret != -1 && is_notif)
7604 return minus_one_ptid;
7606 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
7607 return minus_one_ptid;
7612 /* Assume that the target has acknowledged Ctrl-C unless we receive
7613 an 'F' or 'O' packet. */
7614 if (buf[0] != 'F' && buf[0] != 'O')
7615 rs->ctrlc_pending_p = 0;
7619 case 'E': /* Error of some sort. */
7620 /* We're out of sync with the target now. Did it continue or
7621 not? Not is more likely, so report a stop. */
7622 rs->waiting_for_stop_reply = 0;
7624 warning (_("Remote failure reply: %s"), buf);
7625 status->kind = TARGET_WAITKIND_STOPPED;
7626 status->value.sig = GDB_SIGNAL_0;
7628 case 'F': /* File-I/O request. */
7629 /* GDB may access the inferior memory while handling the File-I/O
7630 request, but we don't want GDB accessing memory while waiting
7631 for a stop reply. See the comments in putpkt_binary. Set
7632 waiting_for_stop_reply to 0 temporarily. */
7633 rs->waiting_for_stop_reply = 0;
7634 remote_fileio_request (buf, rs->ctrlc_pending_p);
7635 rs->ctrlc_pending_p = 0;
7636 /* GDB handled the File-I/O request, and the target is running
7637 again. Keep waiting for events. */
7638 rs->waiting_for_stop_reply = 1;
7640 case 'N': case 'T': case 'S': case 'X': case 'W':
7642 struct stop_reply *stop_reply;
7644 /* There is a stop reply to handle. */
7645 rs->waiting_for_stop_reply = 0;
7648 = (struct stop_reply *) remote_notif_parse (¬if_client_stop,
7651 event_ptid = process_stop_reply (stop_reply, status);
7654 case 'O': /* Console output. */
7655 remote_console_output (buf + 1);
7658 if (rs->last_sent_signal != GDB_SIGNAL_0)
7660 /* Zero length reply means that we tried 'S' or 'C' and the
7661 remote system doesn't support it. */
7662 target_terminal::ours_for_output ();
7664 ("Can't send signals to this remote system. %s not sent.\n",
7665 gdb_signal_to_name (rs->last_sent_signal));
7666 rs->last_sent_signal = GDB_SIGNAL_0;
7667 target_terminal::inferior ();
7669 strcpy (buf, rs->last_sent_step ? "s" : "c");
7673 /* else fallthrough */
7675 warning (_("Invalid remote reply: %s"), buf);
7679 if (status->kind == TARGET_WAITKIND_NO_RESUMED)
7680 return minus_one_ptid;
7681 else if (status->kind == TARGET_WAITKIND_IGNORE)
7683 /* Nothing interesting happened. If we're doing a non-blocking
7684 poll, we're done. Otherwise, go back to waiting. */
7685 if (options & TARGET_WNOHANG)
7686 return minus_one_ptid;
7690 else if (status->kind != TARGET_WAITKIND_EXITED
7691 && status->kind != TARGET_WAITKIND_SIGNALLED)
7693 if (!ptid_equal (event_ptid, null_ptid))
7694 record_currthread (rs, event_ptid);
7696 event_ptid = inferior_ptid;
7699 /* A process exit. Invalidate our notion of current thread. */
7700 record_currthread (rs, minus_one_ptid);
7705 /* Wait until the remote machine stops, then return, storing status in
7706 STATUS just as `wait' would. */
7709 remote_target::wait (ptid_t ptid, struct target_waitstatus *status, int options)
7713 if (target_is_non_stop_p ())
7714 event_ptid = remote_wait_ns (ptid, status, options);
7716 event_ptid = remote_wait_as (ptid, status, options);
7718 if (target_is_async_p ())
7720 /* If there are are events left in the queue tell the event loop
7722 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
7723 mark_async_event_handler (remote_async_inferior_event_token);
7729 /* Fetch a single register using a 'p' packet. */
7732 fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
7734 struct gdbarch *gdbarch = regcache->arch ();
7735 struct remote_state *rs = get_remote_state ();
7737 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
7740 if (packet_support (PACKET_p) == PACKET_DISABLE)
7743 if (reg->pnum == -1)
7748 p += hexnumstr (p, reg->pnum);
7751 getpkt (&rs->buf, &rs->buf_size, 0);
7755 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
7759 case PACKET_UNKNOWN:
7762 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
7763 gdbarch_register_name (regcache->arch (),
7768 /* If this register is unfetchable, tell the regcache. */
7771 regcache_raw_supply (regcache, reg->regnum, NULL);
7775 /* Otherwise, parse and supply the value. */
7781 error (_("fetch_register_using_p: early buf termination"));
7783 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
7786 regcache_raw_supply (regcache, reg->regnum, regp);
7790 /* Fetch the registers included in the target's 'g' packet. */
7793 send_g_packet (void)
7795 struct remote_state *rs = get_remote_state ();
7798 xsnprintf (rs->buf, get_remote_packet_size (), "g");
7800 getpkt (&rs->buf, &rs->buf_size, 0);
7801 if (packet_check_result (rs->buf) == PACKET_ERROR)
7802 error (_("Could not read registers; remote failure reply '%s'"),
7805 /* We can get out of synch in various cases. If the first character
7806 in the buffer is not a hex character, assume that has happened
7807 and try to fetch another packet to read. */
7808 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
7809 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
7810 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
7811 && rs->buf[0] != 'x') /* New: unavailable register value. */
7814 fprintf_unfiltered (gdb_stdlog,
7815 "Bad register packet; fetching a new packet\n");
7816 getpkt (&rs->buf, &rs->buf_size, 0);
7819 buf_len = strlen (rs->buf);
7821 /* Sanity check the received packet. */
7822 if (buf_len % 2 != 0)
7823 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
7829 process_g_packet (struct regcache *regcache)
7831 struct gdbarch *gdbarch = regcache->arch ();
7832 struct remote_state *rs = get_remote_state ();
7833 remote_arch_state *rsa = get_remote_arch_state (gdbarch);
7838 buf_len = strlen (rs->buf);
7840 /* Further sanity checks, with knowledge of the architecture. */
7841 if (buf_len > 2 * rsa->sizeof_g_packet)
7842 error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
7843 "bytes): %s"), rsa->sizeof_g_packet, buf_len / 2, rs->buf);
7845 /* Save the size of the packet sent to us by the target. It is used
7846 as a heuristic when determining the max size of packets that the
7847 target can safely receive. */
7848 if (rsa->actual_register_packet_size == 0)
7849 rsa->actual_register_packet_size = buf_len;
7851 /* If this is smaller than we guessed the 'g' packet would be,
7852 update our records. A 'g' reply that doesn't include a register's
7853 value implies either that the register is not available, or that
7854 the 'p' packet must be used. */
7855 if (buf_len < 2 * rsa->sizeof_g_packet)
7857 long sizeof_g_packet = buf_len / 2;
7859 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7861 long offset = rsa->regs[i].offset;
7862 long reg_size = register_size (gdbarch, i);
7864 if (rsa->regs[i].pnum == -1)
7867 if (offset >= sizeof_g_packet)
7868 rsa->regs[i].in_g_packet = 0;
7869 else if (offset + reg_size > sizeof_g_packet)
7870 error (_("Truncated register %d in remote 'g' packet"), i);
7872 rsa->regs[i].in_g_packet = 1;
7875 /* Looks valid enough, we can assume this is the correct length
7876 for a 'g' packet. It's important not to adjust
7877 rsa->sizeof_g_packet if we have truncated registers otherwise
7878 this "if" won't be run the next time the method is called
7879 with a packet of the same size and one of the internal errors
7880 below will trigger instead. */
7881 rsa->sizeof_g_packet = sizeof_g_packet;
7884 regs = (char *) alloca (rsa->sizeof_g_packet);
7886 /* Unimplemented registers read as all bits zero. */
7887 memset (regs, 0, rsa->sizeof_g_packet);
7889 /* Reply describes registers byte by byte, each byte encoded as two
7890 hex characters. Suck them all up, then supply them to the
7891 register cacheing/storage mechanism. */
7894 for (i = 0; i < rsa->sizeof_g_packet; i++)
7896 if (p[0] == 0 || p[1] == 0)
7897 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
7898 internal_error (__FILE__, __LINE__,
7899 _("unexpected end of 'g' packet reply"));
7901 if (p[0] == 'x' && p[1] == 'x')
7902 regs[i] = 0; /* 'x' */
7904 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
7908 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7910 struct packet_reg *r = &rsa->regs[i];
7911 long reg_size = register_size (gdbarch, i);
7915 if ((r->offset + reg_size) * 2 > strlen (rs->buf))
7916 /* This shouldn't happen - we adjusted in_g_packet above. */
7917 internal_error (__FILE__, __LINE__,
7918 _("unexpected end of 'g' packet reply"));
7919 else if (rs->buf[r->offset * 2] == 'x')
7921 gdb_assert (r->offset * 2 < strlen (rs->buf));
7922 /* The register isn't available, mark it as such (at
7923 the same time setting the value to zero). */
7924 regcache_raw_supply (regcache, r->regnum, NULL);
7927 regcache_raw_supply (regcache, r->regnum,
7934 fetch_registers_using_g (struct regcache *regcache)
7937 process_g_packet (regcache);
7940 /* Make the remote selected traceframe match GDB's selected
7944 set_remote_traceframe (void)
7947 struct remote_state *rs = get_remote_state ();
7949 if (rs->remote_traceframe_number == get_traceframe_number ())
7952 /* Avoid recursion, remote_trace_find calls us again. */
7953 rs->remote_traceframe_number = get_traceframe_number ();
7955 newnum = target_trace_find (tfind_number,
7956 get_traceframe_number (), 0, 0, NULL);
7958 /* Should not happen. If it does, all bets are off. */
7959 if (newnum != get_traceframe_number ())
7960 warning (_("could not set remote traceframe"));
7964 remote_target::fetch_registers (struct regcache *regcache, int regnum)
7966 struct gdbarch *gdbarch = regcache->arch ();
7967 remote_arch_state *rsa = get_remote_arch_state (gdbarch);
7970 set_remote_traceframe ();
7971 set_general_thread (regcache_get_ptid (regcache));
7975 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
7977 gdb_assert (reg != NULL);
7979 /* If this register might be in the 'g' packet, try that first -
7980 we are likely to read more than one register. If this is the
7981 first 'g' packet, we might be overly optimistic about its
7982 contents, so fall back to 'p'. */
7983 if (reg->in_g_packet)
7985 fetch_registers_using_g (regcache);
7986 if (reg->in_g_packet)
7990 if (fetch_register_using_p (regcache, reg))
7993 /* This register is not available. */
7994 regcache_raw_supply (regcache, reg->regnum, NULL);
7999 fetch_registers_using_g (regcache);
8001 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8002 if (!rsa->regs[i].in_g_packet)
8003 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
8005 /* This register is not available. */
8006 regcache_raw_supply (regcache, i, NULL);
8010 /* Prepare to store registers. Since we may send them all (using a
8011 'G' request), we have to read out the ones we don't want to change
8015 remote_target::prepare_to_store (struct regcache *regcache)
8017 remote_arch_state *rsa = get_remote_arch_state (regcache->arch ());
8020 /* Make sure the entire registers array is valid. */
8021 switch (packet_support (PACKET_P))
8023 case PACKET_DISABLE:
8024 case PACKET_SUPPORT_UNKNOWN:
8025 /* Make sure all the necessary registers are cached. */
8026 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8027 if (rsa->regs[i].in_g_packet)
8028 regcache_raw_update (regcache, rsa->regs[i].regnum);
8035 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
8036 packet was not recognized. */
8039 store_register_using_P (const struct regcache *regcache,
8040 struct packet_reg *reg)
8042 struct gdbarch *gdbarch = regcache->arch ();
8043 struct remote_state *rs = get_remote_state ();
8044 /* Try storing a single register. */
8045 char *buf = rs->buf;
8046 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
8049 if (packet_support (PACKET_P) == PACKET_DISABLE)
8052 if (reg->pnum == -1)
8055 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
8056 p = buf + strlen (buf);
8057 regcache_raw_collect (regcache, reg->regnum, regp);
8058 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
8060 getpkt (&rs->buf, &rs->buf_size, 0);
8062 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
8067 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
8068 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
8069 case PACKET_UNKNOWN:
8072 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8076 /* Store register REGNUM, or all registers if REGNUM == -1, from the
8077 contents of the register cache buffer. FIXME: ignores errors. */
8080 store_registers_using_G (const struct regcache *regcache)
8082 struct remote_state *rs = get_remote_state ();
8083 remote_arch_state *rsa = get_remote_arch_state (regcache->arch ());
8087 /* Extract all the registers in the regcache copying them into a
8092 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
8093 memset (regs, 0, rsa->sizeof_g_packet);
8094 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8096 struct packet_reg *r = &rsa->regs[i];
8099 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
8103 /* Command describes registers byte by byte,
8104 each byte encoded as two hex characters. */
8107 bin2hex (regs, p, rsa->sizeof_g_packet);
8109 getpkt (&rs->buf, &rs->buf_size, 0);
8110 if (packet_check_result (rs->buf) == PACKET_ERROR)
8111 error (_("Could not write registers; remote failure reply '%s'"),
8115 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
8116 of the register cache buffer. FIXME: ignores errors. */
8119 remote_target::store_registers (struct regcache *regcache, int regnum)
8121 struct gdbarch *gdbarch = regcache->arch ();
8122 remote_arch_state *rsa = get_remote_arch_state (gdbarch);
8125 set_remote_traceframe ();
8126 set_general_thread (regcache_get_ptid (regcache));
8130 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8132 gdb_assert (reg != NULL);
8134 /* Always prefer to store registers using the 'P' packet if
8135 possible; we often change only a small number of registers.
8136 Sometimes we change a larger number; we'd need help from a
8137 higher layer to know to use 'G'. */
8138 if (store_register_using_P (regcache, reg))
8141 /* For now, don't complain if we have no way to write the
8142 register. GDB loses track of unavailable registers too
8143 easily. Some day, this may be an error. We don't have
8144 any way to read the register, either... */
8145 if (!reg->in_g_packet)
8148 store_registers_using_G (regcache);
8152 store_registers_using_G (regcache);
8154 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8155 if (!rsa->regs[i].in_g_packet)
8156 if (!store_register_using_P (regcache, &rsa->regs[i]))
8157 /* See above for why we do not issue an error here. */
8162 /* Return the number of hex digits in num. */
8165 hexnumlen (ULONGEST num)
8169 for (i = 0; num != 0; i++)
8172 return std::max (i, 1);
8175 /* Set BUF to the minimum number of hex digits representing NUM. */
8178 hexnumstr (char *buf, ULONGEST num)
8180 int len = hexnumlen (num);
8182 return hexnumnstr (buf, num, len);
8186 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
8189 hexnumnstr (char *buf, ULONGEST num, int width)
8195 for (i = width - 1; i >= 0; i--)
8197 buf[i] = "0123456789abcdef"[(num & 0xf)];
8204 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
8207 remote_address_masked (CORE_ADDR addr)
8209 unsigned int address_size = remote_address_size;
8211 /* If "remoteaddresssize" was not set, default to target address size. */
8213 address_size = gdbarch_addr_bit (target_gdbarch ());
8215 if (address_size > 0
8216 && address_size < (sizeof (ULONGEST) * 8))
8218 /* Only create a mask when that mask can safely be constructed
8219 in a ULONGEST variable. */
8222 mask = (mask << address_size) - 1;
8228 /* Determine whether the remote target supports binary downloading.
8229 This is accomplished by sending a no-op memory write of zero length
8230 to the target at the specified address. It does not suffice to send
8231 the whole packet, since many stubs strip the eighth bit and
8232 subsequently compute a wrong checksum, which causes real havoc with
8235 NOTE: This can still lose if the serial line is not eight-bit
8236 clean. In cases like this, the user should clear "remote
8240 check_binary_download (CORE_ADDR addr)
8242 struct remote_state *rs = get_remote_state ();
8244 switch (packet_support (PACKET_X))
8246 case PACKET_DISABLE:
8250 case PACKET_SUPPORT_UNKNOWN:
8256 p += hexnumstr (p, (ULONGEST) addr);
8258 p += hexnumstr (p, (ULONGEST) 0);
8262 putpkt_binary (rs->buf, (int) (p - rs->buf));
8263 getpkt (&rs->buf, &rs->buf_size, 0);
8265 if (rs->buf[0] == '\0')
8268 fprintf_unfiltered (gdb_stdlog,
8269 "binary downloading NOT "
8270 "supported by target\n");
8271 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
8276 fprintf_unfiltered (gdb_stdlog,
8277 "binary downloading supported by target\n");
8278 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
8285 /* Helper function to resize the payload in order to try to get a good
8286 alignment. We try to write an amount of data such that the next write will
8287 start on an address aligned on REMOTE_ALIGN_WRITES. */
8290 align_for_efficient_write (int todo, CORE_ADDR memaddr)
8292 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
8295 /* Write memory data directly to the remote machine.
8296 This does not inform the data cache; the data cache uses this.
8297 HEADER is the starting part of the packet.
8298 MEMADDR is the address in the remote memory space.
8299 MYADDR is the address of the buffer in our space.
8300 LEN_UNITS is the number of addressable units to write.
8301 UNIT_SIZE is the length in bytes of an addressable unit.
8302 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
8303 should send data as binary ('X'), or hex-encoded ('M').
8305 The function creates packet of the form
8306 <HEADER><ADDRESS>,<LENGTH>:<DATA>
8308 where encoding of <DATA> is terminated by PACKET_FORMAT.
8310 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
8313 Return the transferred status, error or OK (an
8314 'enum target_xfer_status' value). Save the number of addressable units
8315 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
8317 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
8318 exchange between gdb and the stub could look like (?? in place of the
8324 -> $M1000,3:eeeeffffeeee#??
8328 <- eeeeffffeeeedddd */
8330 static enum target_xfer_status
8331 remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
8332 const gdb_byte *myaddr, ULONGEST len_units,
8333 int unit_size, ULONGEST *xfered_len_units,
8334 char packet_format, int use_length)
8336 struct remote_state *rs = get_remote_state ();
8342 int payload_capacity_bytes;
8343 int payload_length_bytes;
8345 if (packet_format != 'X' && packet_format != 'M')
8346 internal_error (__FILE__, __LINE__,
8347 _("remote_write_bytes_aux: bad packet format"));
8350 return TARGET_XFER_EOF;
8352 payload_capacity_bytes = get_memory_write_packet_size ();
8354 /* The packet buffer will be large enough for the payload;
8355 get_memory_packet_size ensures this. */
8358 /* Compute the size of the actual payload by subtracting out the
8359 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
8361 payload_capacity_bytes -= strlen ("$,:#NN");
8363 /* The comma won't be used. */
8364 payload_capacity_bytes += 1;
8365 payload_capacity_bytes -= strlen (header);
8366 payload_capacity_bytes -= hexnumlen (memaddr);
8368 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
8370 strcat (rs->buf, header);
8371 p = rs->buf + strlen (header);
8373 /* Compute a best guess of the number of bytes actually transfered. */
8374 if (packet_format == 'X')
8376 /* Best guess at number of bytes that will fit. */
8377 todo_units = std::min (len_units,
8378 (ULONGEST) payload_capacity_bytes / unit_size);
8380 payload_capacity_bytes -= hexnumlen (todo_units);
8381 todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
8385 /* Number of bytes that will fit. */
8387 = std::min (len_units,
8388 (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
8390 payload_capacity_bytes -= hexnumlen (todo_units);
8391 todo_units = std::min (todo_units,
8392 (payload_capacity_bytes / unit_size) / 2);
8395 if (todo_units <= 0)
8396 internal_error (__FILE__, __LINE__,
8397 _("minimum packet size too small to write data"));
8399 /* If we already need another packet, then try to align the end
8400 of this packet to a useful boundary. */
8401 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
8402 todo_units = align_for_efficient_write (todo_units, memaddr);
8404 /* Append "<memaddr>". */
8405 memaddr = remote_address_masked (memaddr);
8406 p += hexnumstr (p, (ULONGEST) memaddr);
8413 /* Append the length and retain its location and size. It may need to be
8414 adjusted once the packet body has been created. */
8416 plenlen = hexnumstr (p, (ULONGEST) todo_units);
8424 /* Append the packet body. */
8425 if (packet_format == 'X')
8427 /* Binary mode. Send target system values byte by byte, in
8428 increasing byte addresses. Only escape certain critical
8430 payload_length_bytes =
8431 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
8432 &units_written, payload_capacity_bytes);
8434 /* If not all TODO units fit, then we'll need another packet. Make
8435 a second try to keep the end of the packet aligned. Don't do
8436 this if the packet is tiny. */
8437 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
8441 new_todo_units = align_for_efficient_write (units_written, memaddr);
8443 if (new_todo_units != units_written)
8444 payload_length_bytes =
8445 remote_escape_output (myaddr, new_todo_units, unit_size,
8446 (gdb_byte *) p, &units_written,
8447 payload_capacity_bytes);
8450 p += payload_length_bytes;
8451 if (use_length && units_written < todo_units)
8453 /* Escape chars have filled up the buffer prematurely,
8454 and we have actually sent fewer units than planned.
8455 Fix-up the length field of the packet. Use the same
8456 number of characters as before. */
8457 plen += hexnumnstr (plen, (ULONGEST) units_written,
8459 *plen = ':'; /* overwrite \0 from hexnumnstr() */
8464 /* Normal mode: Send target system values byte by byte, in
8465 increasing byte addresses. Each byte is encoded as a two hex
8467 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
8468 units_written = todo_units;
8471 putpkt_binary (rs->buf, (int) (p - rs->buf));
8472 getpkt (&rs->buf, &rs->buf_size, 0);
8474 if (rs->buf[0] == 'E')
8475 return TARGET_XFER_E_IO;
8477 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
8478 send fewer units than we'd planned. */
8479 *xfered_len_units = (ULONGEST) units_written;
8480 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
8483 /* Write memory data directly to the remote machine.
8484 This does not inform the data cache; the data cache uses this.
8485 MEMADDR is the address in the remote memory space.
8486 MYADDR is the address of the buffer in our space.
8487 LEN is the number of bytes.
8489 Return the transferred status, error or OK (an
8490 'enum target_xfer_status' value). Save the number of bytes
8491 transferred in *XFERED_LEN. Only transfer a single packet. */
8493 static enum target_xfer_status
8494 remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
8495 int unit_size, ULONGEST *xfered_len)
8497 const char *packet_format = NULL;
8499 /* Check whether the target supports binary download. */
8500 check_binary_download (memaddr);
8502 switch (packet_support (PACKET_X))
8505 packet_format = "X";
8507 case PACKET_DISABLE:
8508 packet_format = "M";
8510 case PACKET_SUPPORT_UNKNOWN:
8511 internal_error (__FILE__, __LINE__,
8512 _("remote_write_bytes: bad internal state"));
8514 internal_error (__FILE__, __LINE__, _("bad switch"));
8517 return remote_write_bytes_aux (packet_format,
8518 memaddr, myaddr, len, unit_size, xfered_len,
8519 packet_format[0], 1);
8522 /* Read memory data directly from the remote machine.
8523 This does not use the data cache; the data cache uses this.
8524 MEMADDR is the address in the remote memory space.
8525 MYADDR is the address of the buffer in our space.
8526 LEN_UNITS is the number of addressable memory units to read..
8527 UNIT_SIZE is the length in bytes of an addressable unit.
8529 Return the transferred status, error or OK (an
8530 'enum target_xfer_status' value). Save the number of bytes
8531 transferred in *XFERED_LEN_UNITS.
8533 See the comment of remote_write_bytes_aux for an example of
8534 memory read/write exchange between gdb and the stub. */
8536 static enum target_xfer_status
8537 remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len_units,
8538 int unit_size, ULONGEST *xfered_len_units)
8540 struct remote_state *rs = get_remote_state ();
8541 int buf_size_bytes; /* Max size of packet output buffer. */
8546 buf_size_bytes = get_memory_read_packet_size ();
8547 /* The packet buffer will be large enough for the payload;
8548 get_memory_packet_size ensures this. */
8550 /* Number of units that will fit. */
8551 todo_units = std::min (len_units,
8552 (ULONGEST) (buf_size_bytes / unit_size) / 2);
8554 /* Construct "m"<memaddr>","<len>". */
8555 memaddr = remote_address_masked (memaddr);
8558 p += hexnumstr (p, (ULONGEST) memaddr);
8560 p += hexnumstr (p, (ULONGEST) todo_units);
8563 getpkt (&rs->buf, &rs->buf_size, 0);
8564 if (rs->buf[0] == 'E'
8565 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
8566 && rs->buf[3] == '\0')
8567 return TARGET_XFER_E_IO;
8568 /* Reply describes memory byte by byte, each byte encoded as two hex
8571 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
8572 /* Return what we have. Let higher layers handle partial reads. */
8573 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
8574 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
8577 /* Using the set of read-only target sections of remote, read live
8580 For interface/parameters/return description see target.h,
8583 static enum target_xfer_status
8584 remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
8585 ULONGEST memaddr, ULONGEST len,
8586 int unit_size, ULONGEST *xfered_len)
8588 struct target_section *secp;
8589 struct target_section_table *table;
8591 secp = target_section_by_addr (ops, memaddr);
8593 && (bfd_get_section_flags (secp->the_bfd_section->owner,
8594 secp->the_bfd_section)
8597 struct target_section *p;
8598 ULONGEST memend = memaddr + len;
8600 table = target_get_section_table (ops);
8602 for (p = table->sections; p < table->sections_end; p++)
8604 if (memaddr >= p->addr)
8606 if (memend <= p->endaddr)
8608 /* Entire transfer is within this section. */
8609 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
8612 else if (memaddr >= p->endaddr)
8614 /* This section ends before the transfer starts. */
8619 /* This section overlaps the transfer. Just do half. */
8620 len = p->endaddr - memaddr;
8621 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
8628 return TARGET_XFER_EOF;
8631 /* Similar to remote_read_bytes_1, but it reads from the remote stub
8632 first if the requested memory is unavailable in traceframe.
8633 Otherwise, fall back to remote_read_bytes_1. */
8635 static enum target_xfer_status
8636 remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
8637 gdb_byte *myaddr, ULONGEST len, int unit_size,
8638 ULONGEST *xfered_len)
8641 return TARGET_XFER_EOF;
8643 if (get_traceframe_number () != -1)
8645 std::vector<mem_range> available;
8647 /* If we fail to get the set of available memory, then the
8648 target does not support querying traceframe info, and so we
8649 attempt reading from the traceframe anyway (assuming the
8650 target implements the old QTro packet then). */
8651 if (traceframe_available_memory (&available, memaddr, len))
8653 if (available.empty () || available[0].start != memaddr)
8655 enum target_xfer_status res;
8657 /* Don't read into the traceframe's available
8659 if (!available.empty ())
8661 LONGEST oldlen = len;
8663 len = available[0].start - memaddr;
8664 gdb_assert (len <= oldlen);
8667 /* This goes through the topmost target again. */
8668 res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
8669 len, unit_size, xfered_len);
8670 if (res == TARGET_XFER_OK)
8671 return TARGET_XFER_OK;
8674 /* No use trying further, we know some memory starting
8675 at MEMADDR isn't available. */
8677 return (*xfered_len != 0) ?
8678 TARGET_XFER_UNAVAILABLE : TARGET_XFER_EOF;
8682 /* Don't try to read more than how much is available, in
8683 case the target implements the deprecated QTro packet to
8684 cater for older GDBs (the target's knowledge of read-only
8685 sections may be outdated by now). */
8686 len = available[0].length;
8690 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
8695 /* Sends a packet with content determined by the printf format string
8696 FORMAT and the remaining arguments, then gets the reply. Returns
8697 whether the packet was a success, a failure, or unknown. */
8699 static enum packet_result remote_send_printf (const char *format, ...)
8700 ATTRIBUTE_PRINTF (1, 2);
8702 static enum packet_result
8703 remote_send_printf (const char *format, ...)
8705 struct remote_state *rs = get_remote_state ();
8706 int max_size = get_remote_packet_size ();
8709 va_start (ap, format);
8712 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
8713 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
8715 if (putpkt (rs->buf) < 0)
8716 error (_("Communication problem with target."));
8719 getpkt (&rs->buf, &rs->buf_size, 0);
8721 return packet_check_result (rs->buf);
8724 /* Flash writing can take quite some time. We'll set
8725 effectively infinite timeout for flash operations.
8726 In future, we'll need to decide on a better approach. */
8727 static const int remote_flash_timeout = 1000;
8730 remote_target::flash_erase (ULONGEST address, LONGEST length)
8732 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
8733 enum packet_result ret;
8734 scoped_restore restore_timeout
8735 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8737 ret = remote_send_printf ("vFlashErase:%s,%s",
8738 phex (address, addr_size),
8742 case PACKET_UNKNOWN:
8743 error (_("Remote target does not support flash erase"));
8745 error (_("Error erasing flash with vFlashErase packet"));
8751 static enum target_xfer_status
8752 remote_flash_write (struct target_ops *ops, ULONGEST address,
8753 ULONGEST length, ULONGEST *xfered_len,
8754 const gdb_byte *data)
8756 scoped_restore restore_timeout
8757 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8758 return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
8763 remote_target::flash_done ()
8767 scoped_restore restore_timeout
8768 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8770 ret = remote_send_printf ("vFlashDone");
8774 case PACKET_UNKNOWN:
8775 error (_("Remote target does not support vFlashDone"));
8777 error (_("Error finishing flash operation"));
8784 remote_target::files_info ()
8786 puts_filtered ("Debugging a target over a serial line.\n");
8789 /* Stuff for dealing with the packets which are part of this protocol.
8790 See comment at top of file for details. */
8792 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
8793 error to higher layers. Called when a serial error is detected.
8794 The exception message is STRING, followed by a colon and a blank,
8795 the system error message for errno at function entry and final dot
8796 for output compatibility with throw_perror_with_name. */
8799 unpush_and_perror (const char *string)
8801 int saved_errno = errno;
8803 remote_unpush_target ();
8804 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
8805 safe_strerror (saved_errno));
8808 /* Read a single character from the remote end. The current quit
8809 handler is overridden to avoid quitting in the middle of packet
8810 sequence, as that would break communication with the remote server.
8811 See remote_serial_quit_handler for more detail. */
8814 readchar (int timeout)
8817 struct remote_state *rs = get_remote_state ();
8820 scoped_restore restore_quit
8821 = make_scoped_restore (&quit_handler, remote_serial_quit_handler);
8823 rs->got_ctrlc_during_io = 0;
8825 ch = serial_readchar (rs->remote_desc, timeout);
8827 if (rs->got_ctrlc_during_io)
8834 switch ((enum serial_rc) ch)
8837 remote_unpush_target ();
8838 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
8841 unpush_and_perror (_("Remote communication error. "
8842 "Target disconnected."));
8844 case SERIAL_TIMEOUT:
8850 /* Wrapper for serial_write that closes the target and throws if
8851 writing fails. The current quit handler is overridden to avoid
8852 quitting in the middle of packet sequence, as that would break
8853 communication with the remote server. See
8854 remote_serial_quit_handler for more detail. */
8857 remote_serial_write (const char *str, int len)
8859 struct remote_state *rs = get_remote_state ();
8861 scoped_restore restore_quit
8862 = make_scoped_restore (&quit_handler, remote_serial_quit_handler);
8864 rs->got_ctrlc_during_io = 0;
8866 if (serial_write (rs->remote_desc, str, len))
8868 unpush_and_perror (_("Remote communication error. "
8869 "Target disconnected."));
8872 if (rs->got_ctrlc_during_io)
8876 /* Return a string representing an escaped version of BUF, of len N.
8877 E.g. \n is converted to \\n, \t to \\t, etc. */
8880 escape_buffer (const char *buf, int n)
8884 stb.putstrn (buf, n, '\\');
8885 return std::move (stb.string ());
8888 /* Display a null-terminated packet on stdout, for debugging, using C
8892 print_packet (const char *buf)
8894 puts_filtered ("\"");
8895 fputstr_filtered (buf, '"', gdb_stdout);
8896 puts_filtered ("\"");
8900 putpkt (const char *buf)
8902 return putpkt_binary (buf, strlen (buf));
8905 /* Send a packet to the remote machine, with error checking. The data
8906 of the packet is in BUF. The string in BUF can be at most
8907 get_remote_packet_size () - 5 to account for the $, # and checksum,
8908 and for a possible /0 if we are debugging (remote_debug) and want
8909 to print the sent packet as a string. */
8912 putpkt_binary (const char *buf, int cnt)
8914 struct remote_state *rs = get_remote_state ();
8916 unsigned char csum = 0;
8917 gdb::def_vector<char> data (cnt + 6);
8918 char *buf2 = data.data ();
8924 /* Catch cases like trying to read memory or listing threads while
8925 we're waiting for a stop reply. The remote server wouldn't be
8926 ready to handle this request, so we'd hang and timeout. We don't
8927 have to worry about this in synchronous mode, because in that
8928 case it's not possible to issue a command while the target is
8929 running. This is not a problem in non-stop mode, because in that
8930 case, the stub is always ready to process serial input. */
8931 if (!target_is_non_stop_p ()
8932 && target_is_async_p ()
8933 && rs->waiting_for_stop_reply)
8935 error (_("Cannot execute this command while the target is running.\n"
8936 "Use the \"interrupt\" command to stop the target\n"
8937 "and then try again."));
8940 /* We're sending out a new packet. Make sure we don't look at a
8941 stale cached response. */
8942 rs->cached_wait_status = 0;
8944 /* Copy the packet into buffer BUF2, encapsulating it
8945 and giving it a checksum. */
8950 for (i = 0; i < cnt; i++)
8956 *p++ = tohex ((csum >> 4) & 0xf);
8957 *p++ = tohex (csum & 0xf);
8959 /* Send it over and over until we get a positive ack. */
8963 int started_error_output = 0;
8969 int len = (int) (p - buf2);
8972 = escape_buffer (buf2, std::min (len, REMOTE_DEBUG_MAX_CHAR));
8974 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s", str.c_str ());
8976 if (len > REMOTE_DEBUG_MAX_CHAR)
8977 fprintf_unfiltered (gdb_stdlog, "[%d bytes omitted]",
8978 len - REMOTE_DEBUG_MAX_CHAR);
8980 fprintf_unfiltered (gdb_stdlog, "...");
8982 gdb_flush (gdb_stdlog);
8984 remote_serial_write (buf2, p - buf2);
8986 /* If this is a no acks version of the remote protocol, send the
8987 packet and move on. */
8991 /* Read until either a timeout occurs (-2) or '+' is read.
8992 Handle any notification that arrives in the mean time. */
8995 ch = readchar (remote_timeout);
9003 case SERIAL_TIMEOUT:
9006 if (started_error_output)
9008 putchar_unfiltered ('\n');
9009 started_error_output = 0;
9018 fprintf_unfiltered (gdb_stdlog, "Ack\n");
9022 fprintf_unfiltered (gdb_stdlog, "Nak\n");
9024 case SERIAL_TIMEOUT:
9028 break; /* Retransmit buffer. */
9032 fprintf_unfiltered (gdb_stdlog,
9033 "Packet instead of Ack, ignoring it\n");
9034 /* It's probably an old response sent because an ACK
9035 was lost. Gobble up the packet and ack it so it
9036 doesn't get retransmitted when we resend this
9039 remote_serial_write ("+", 1);
9040 continue; /* Now, go look for +. */
9047 /* If we got a notification, handle it, and go back to looking
9049 /* We've found the start of a notification. Now
9050 collect the data. */
9051 val = read_frame (&rs->buf, &rs->buf_size);
9056 std::string str = escape_buffer (rs->buf, val);
9058 fprintf_unfiltered (gdb_stdlog,
9059 " Notification received: %s\n",
9062 handle_notification (rs->notif_state, rs->buf);
9063 /* We're in sync now, rewait for the ack. */
9070 if (!started_error_output)
9072 started_error_output = 1;
9073 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
9075 fputc_unfiltered (ch & 0177, gdb_stdlog);
9076 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
9085 if (!started_error_output)
9087 started_error_output = 1;
9088 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
9090 fputc_unfiltered (ch & 0177, gdb_stdlog);
9094 break; /* Here to retransmit. */
9098 /* This is wrong. If doing a long backtrace, the user should be
9099 able to get out next time we call QUIT, without anything as
9100 violent as interrupt_query. If we want to provide a way out of
9101 here without getting to the next QUIT, it should be based on
9102 hitting ^C twice as in remote_wait. */
9114 /* Come here after finding the start of a frame when we expected an
9115 ack. Do our best to discard the rest of this packet. */
9124 c = readchar (remote_timeout);
9127 case SERIAL_TIMEOUT:
9128 /* Nothing we can do. */
9131 /* Discard the two bytes of checksum and stop. */
9132 c = readchar (remote_timeout);
9134 c = readchar (remote_timeout);
9137 case '*': /* Run length encoding. */
9138 /* Discard the repeat count. */
9139 c = readchar (remote_timeout);
9144 /* A regular character. */
9150 /* Come here after finding the start of the frame. Collect the rest
9151 into *BUF, verifying the checksum, length, and handling run-length
9152 compression. NUL terminate the buffer. If there is not enough room,
9153 expand *BUF using xrealloc.
9155 Returns -1 on error, number of characters in buffer (ignoring the
9156 trailing NULL) on success. (could be extended to return one of the
9157 SERIAL status indications). */
9160 read_frame (char **buf_p,
9167 struct remote_state *rs = get_remote_state ();
9174 c = readchar (remote_timeout);
9177 case SERIAL_TIMEOUT:
9179 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
9183 fputs_filtered ("Saw new packet start in middle of old one\n",
9185 return -1; /* Start a new packet, count retries. */
9188 unsigned char pktcsum;
9194 check_0 = readchar (remote_timeout);
9196 check_1 = readchar (remote_timeout);
9198 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
9201 fputs_filtered ("Timeout in checksum, retrying\n",
9205 else if (check_0 < 0 || check_1 < 0)
9208 fputs_filtered ("Communication error in checksum\n",
9213 /* Don't recompute the checksum; with no ack packets we
9214 don't have any way to indicate a packet retransmission
9219 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
9220 if (csum == pktcsum)
9225 std::string str = escape_buffer (buf, bc);
9227 fprintf_unfiltered (gdb_stdlog,
9228 "Bad checksum, sentsum=0x%x, "
9229 "csum=0x%x, buf=%s\n",
9230 pktcsum, csum, str.c_str ());
9232 /* Number of characters in buffer ignoring trailing
9236 case '*': /* Run length encoding. */
9241 c = readchar (remote_timeout);
9243 repeat = c - ' ' + 3; /* Compute repeat count. */
9245 /* The character before ``*'' is repeated. */
9247 if (repeat > 0 && repeat <= 255 && bc > 0)
9249 if (bc + repeat - 1 >= *sizeof_buf - 1)
9251 /* Make some more room in the buffer. */
9252 *sizeof_buf += repeat;
9253 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
9257 memset (&buf[bc], buf[bc - 1], repeat);
9263 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
9267 if (bc >= *sizeof_buf - 1)
9269 /* Make some more room in the buffer. */
9271 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
9282 /* Read a packet from the remote machine, with error checking, and
9283 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
9284 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
9285 rather than timing out; this is used (in synchronous mode) to wait
9286 for a target that is is executing user code to stop. */
9287 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
9288 don't have to change all the calls to getpkt to deal with the
9289 return value, because at the moment I don't know what the right
9290 thing to do it for those. */
9296 getpkt_sane (buf, sizeof_buf, forever);
9300 /* Read a packet from the remote machine, with error checking, and
9301 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
9302 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
9303 rather than timing out; this is used (in synchronous mode) to wait
9304 for a target that is is executing user code to stop. If FOREVER ==
9305 0, this function is allowed to time out gracefully and return an
9306 indication of this to the caller. Otherwise return the number of
9307 bytes read. If EXPECTING_NOTIF, consider receiving a notification
9308 enough reason to return to the caller. *IS_NOTIF is an output
9309 boolean that indicates whether *BUF holds a notification or not
9310 (a regular packet). */
9313 getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
9314 int expecting_notif, int *is_notif)
9316 struct remote_state *rs = get_remote_state ();
9322 /* We're reading a new response. Make sure we don't look at a
9323 previously cached response. */
9324 rs->cached_wait_status = 0;
9326 strcpy (*buf, "timeout");
9329 timeout = watchdog > 0 ? watchdog : -1;
9330 else if (expecting_notif)
9331 timeout = 0; /* There should already be a char in the buffer. If
9334 timeout = remote_timeout;
9338 /* Process any number of notifications, and then return when
9342 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
9344 for (tries = 1; tries <= MAX_TRIES; tries++)
9346 /* This can loop forever if the remote side sends us
9347 characters continuously, but if it pauses, we'll get
9348 SERIAL_TIMEOUT from readchar because of timeout. Then
9349 we'll count that as a retry.
9351 Note that even when forever is set, we will only wait
9352 forever prior to the start of a packet. After that, we
9353 expect characters to arrive at a brisk pace. They should
9354 show up within remote_timeout intervals. */
9356 c = readchar (timeout);
9357 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
9359 if (c == SERIAL_TIMEOUT)
9361 if (expecting_notif)
9362 return -1; /* Don't complain, it's normal to not get
9363 anything in this case. */
9365 if (forever) /* Watchdog went off? Kill the target. */
9367 remote_unpush_target ();
9368 throw_error (TARGET_CLOSE_ERROR,
9369 _("Watchdog timeout has expired. "
9370 "Target detached."));
9373 fputs_filtered ("Timed out.\n", gdb_stdlog);
9377 /* We've found the start of a packet or notification.
9378 Now collect the data. */
9379 val = read_frame (buf, sizeof_buf);
9384 remote_serial_write ("-", 1);
9387 if (tries > MAX_TRIES)
9389 /* We have tried hard enough, and just can't receive the
9390 packet/notification. Give up. */
9391 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
9393 /* Skip the ack char if we're in no-ack mode. */
9394 if (!rs->noack_mode)
9395 remote_serial_write ("+", 1);
9399 /* If we got an ordinary packet, return that to our caller. */
9405 = escape_buffer (*buf,
9406 std::min (val, REMOTE_DEBUG_MAX_CHAR));
9408 fprintf_unfiltered (gdb_stdlog, "Packet received: %s",
9411 if (val > REMOTE_DEBUG_MAX_CHAR)
9412 fprintf_unfiltered (gdb_stdlog, "[%d bytes omitted]",
9413 val - REMOTE_DEBUG_MAX_CHAR);
9415 fprintf_unfiltered (gdb_stdlog, "\n");
9418 /* Skip the ack char if we're in no-ack mode. */
9419 if (!rs->noack_mode)
9420 remote_serial_write ("+", 1);
9421 if (is_notif != NULL)
9426 /* If we got a notification, handle it, and go back to looking
9430 gdb_assert (c == '%');
9434 std::string str = escape_buffer (*buf, val);
9436 fprintf_unfiltered (gdb_stdlog,
9437 " Notification received: %s\n",
9440 if (is_notif != NULL)
9443 handle_notification (rs->notif_state, *buf);
9445 /* Notifications require no acknowledgement. */
9447 if (expecting_notif)
9454 getpkt_sane (char **buf, long *sizeof_buf, int forever)
9456 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
9460 getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
9463 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
9467 /* Check whether EVENT is a fork event for the process specified
9468 by the pid passed in DATA, and if it is, kill the fork child. */
9471 kill_child_of_pending_fork (QUEUE (stop_reply_p) *q,
9472 QUEUE_ITER (stop_reply_p) *iter,
9476 struct queue_iter_param *param = (struct queue_iter_param *) data;
9477 int parent_pid = *(int *) param->input;
9479 if (is_pending_fork_parent (&event->ws, parent_pid, event->ptid))
9481 struct remote_state *rs = get_remote_state ();
9482 int child_pid = ptid_get_pid (event->ws.value.related_pid);
9485 res = remote_vkill (child_pid, rs);
9487 error (_("Can't kill fork child process %d"), child_pid);
9493 /* Kill any new fork children of process PID that haven't been
9494 processed by follow_fork. */
9497 kill_new_fork_children (int pid, struct remote_state *rs)
9499 struct thread_info *thread;
9500 struct notif_client *notif = ¬if_client_stop;
9501 struct queue_iter_param param;
9503 /* Kill the fork child threads of any threads in process PID
9504 that are stopped at a fork event. */
9505 ALL_NON_EXITED_THREADS (thread)
9507 struct target_waitstatus *ws = &thread->pending_follow;
9509 if (is_pending_fork_parent (ws, pid, thread->ptid))
9511 struct remote_state *rs = get_remote_state ();
9512 int child_pid = ptid_get_pid (ws->value.related_pid);
9515 res = remote_vkill (child_pid, rs);
9517 error (_("Can't kill fork child process %d"), child_pid);
9521 /* Check for any pending fork events (not reported or processed yet)
9522 in process PID and kill those fork child threads as well. */
9523 remote_notif_get_pending_events (notif);
9525 param.output = NULL;
9526 QUEUE_iterate (stop_reply_p, stop_reply_queue,
9527 kill_child_of_pending_fork, ¶m);
9531 /* Target hook to kill the current inferior. */
9534 remote_target::kill ()
9537 int pid = ptid_get_pid (inferior_ptid);
9538 struct remote_state *rs = get_remote_state ();
9540 if (packet_support (PACKET_vKill) != PACKET_DISABLE)
9542 /* If we're stopped while forking and we haven't followed yet,
9543 kill the child task. We need to do this before killing the
9544 parent task because if this is a vfork then the parent will
9546 kill_new_fork_children (pid, rs);
9548 res = remote_vkill (pid, rs);
9551 target_mourn_inferior (inferior_ptid);
9556 /* If we are in 'target remote' mode and we are killing the only
9557 inferior, then we will tell gdbserver to exit and unpush the
9559 if (res == -1 && !remote_multi_process_p (rs)
9560 && number_of_live_inferiors () == 1)
9564 /* We've killed the remote end, we get to mourn it. If we are
9565 not in extended mode, mourning the inferior also unpushes
9566 remote_ops from the target stack, which closes the remote
9568 target_mourn_inferior (inferior_ptid);
9573 error (_("Can't kill process"));
9576 /* Send a kill request to the target using the 'vKill' packet. */
9579 remote_vkill (int pid, struct remote_state *rs)
9581 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
9584 /* Tell the remote target to detach. */
9585 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
9587 getpkt (&rs->buf, &rs->buf_size, 0);
9589 switch (packet_ok (rs->buf,
9590 &remote_protocol_packets[PACKET_vKill]))
9596 case PACKET_UNKNOWN:
9599 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
9603 /* Send a kill request to the target using the 'k' packet. */
9606 remote_kill_k (void)
9608 /* Catch errors so the user can quit from gdb even when we
9609 aren't on speaking terms with the remote system. */
9614 CATCH (ex, RETURN_MASK_ERROR)
9616 if (ex.error == TARGET_CLOSE_ERROR)
9618 /* If we got an (EOF) error that caused the target
9619 to go away, then we're done, that's what we wanted.
9620 "k" is susceptible to cause a premature EOF, given
9621 that the remote server isn't actually required to
9622 reply to "k", and it can happen that it doesn't
9623 even get to reply ACK to the "k". */
9627 /* Otherwise, something went wrong. We didn't actually kill
9628 the target. Just propagate the exception, and let the
9629 user or higher layers decide what to do. */
9630 throw_exception (ex);
9636 remote_target::mourn_inferior ()
9638 struct remote_state *rs = get_remote_state ();
9640 /* In 'target remote' mode with one inferior, we close the connection. */
9641 if (!rs->extended && number_of_live_inferiors () <= 1)
9643 unpush_target (this);
9645 /* remote_close takes care of doing most of the clean up. */
9646 generic_mourn_inferior ();
9650 /* In case we got here due to an error, but we're going to stay
9652 rs->waiting_for_stop_reply = 0;
9654 /* If the current general thread belonged to the process we just
9655 detached from or has exited, the remote side current general
9656 thread becomes undefined. Considering a case like this:
9658 - We just got here due to a detach.
9659 - The process that we're detaching from happens to immediately
9660 report a global breakpoint being hit in non-stop mode, in the
9661 same thread we had selected before.
9662 - GDB attaches to this process again.
9663 - This event happens to be the next event we handle.
9665 GDB would consider that the current general thread didn't need to
9666 be set on the stub side (with Hg), since for all it knew,
9667 GENERAL_THREAD hadn't changed.
9669 Notice that although in all-stop mode, the remote server always
9670 sets the current thread to the thread reporting the stop event,
9671 that doesn't happen in non-stop mode; in non-stop, the stub *must
9672 not* change the current thread when reporting a breakpoint hit,
9673 due to the decoupling of event reporting and event handling.
9675 To keep things simple, we always invalidate our notion of the
9677 record_currthread (rs, minus_one_ptid);
9679 /* Call common code to mark the inferior as not running. */
9680 generic_mourn_inferior ();
9682 if (!have_inferiors ())
9684 if (!remote_multi_process_p (rs))
9686 /* Check whether the target is running now - some remote stubs
9687 automatically restart after kill. */
9689 getpkt (&rs->buf, &rs->buf_size, 0);
9691 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
9693 /* Assume that the target has been restarted. Set
9694 inferior_ptid so that bits of core GDB realizes
9695 there's something here, e.g., so that the user can
9696 say "kill" again. */
9697 inferior_ptid = magic_null_ptid;
9704 extended_remote_target::supports_disable_randomization ()
9706 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
9710 extended_remote_disable_randomization (int val)
9712 struct remote_state *rs = get_remote_state ();
9715 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
9718 reply = remote_get_noisy_reply ();
9720 error (_("Target does not support QDisableRandomization."));
9721 if (strcmp (reply, "OK") != 0)
9722 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
9726 extended_remote_run (const std::string &args)
9728 struct remote_state *rs = get_remote_state ();
9730 const char *remote_exec_file = get_remote_exec_file ();
9732 /* If the user has disabled vRun support, or we have detected that
9733 support is not available, do not try it. */
9734 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
9737 strcpy (rs->buf, "vRun;");
9738 len = strlen (rs->buf);
9740 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
9741 error (_("Remote file name too long for run packet"));
9742 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
9743 strlen (remote_exec_file));
9749 gdb_argv argv (args.c_str ());
9750 for (i = 0; argv[i] != NULL; i++)
9752 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
9753 error (_("Argument list too long for run packet"));
9754 rs->buf[len++] = ';';
9755 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
9760 rs->buf[len++] = '\0';
9763 getpkt (&rs->buf, &rs->buf_size, 0);
9765 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
9768 /* We have a wait response. All is well. */
9770 case PACKET_UNKNOWN:
9773 if (remote_exec_file[0] == '\0')
9774 error (_("Running the default executable on the remote target failed; "
9775 "try \"set remote exec-file\"?"));
9777 error (_("Running \"%s\" on the remote target failed"),
9780 gdb_assert_not_reached (_("bad switch"));
9784 /* Helper function to send set/unset environment packets. ACTION is
9785 either "set" or "unset". PACKET is either "QEnvironmentHexEncoded"
9786 or "QEnvironmentUnsetVariable". VALUE is the variable to be
9790 send_environment_packet (struct remote_state *rs,
9795 /* Convert the environment variable to an hex string, which
9796 is the best format to be transmitted over the wire. */
9797 std::string encoded_value = bin2hex ((const gdb_byte *) value,
9800 xsnprintf (rs->buf, get_remote_packet_size (),
9801 "%s:%s", packet, encoded_value.c_str ());
9804 getpkt (&rs->buf, &rs->buf_size, 0);
9805 if (strcmp (rs->buf, "OK") != 0)
9806 warning (_("Unable to %s environment variable '%s' on remote."),
9810 /* Helper function to handle the QEnvironment* packets. */
9813 extended_remote_environment_support (struct remote_state *rs)
9815 if (packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
9817 putpkt ("QEnvironmentReset");
9818 getpkt (&rs->buf, &rs->buf_size, 0);
9819 if (strcmp (rs->buf, "OK") != 0)
9820 warning (_("Unable to reset environment on remote."));
9823 gdb_environ *e = ¤t_inferior ()->environment;
9825 if (packet_support (PACKET_QEnvironmentHexEncoded) != PACKET_DISABLE)
9826 for (const std::string &el : e->user_set_env ())
9827 send_environment_packet (rs, "set", "QEnvironmentHexEncoded",
9830 if (packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
9831 for (const std::string &el : e->user_unset_env ())
9832 send_environment_packet (rs, "unset", "QEnvironmentUnset", el.c_str ());
9835 /* Helper function to set the current working directory for the
9836 inferior in the remote target. */
9839 extended_remote_set_inferior_cwd (struct remote_state *rs)
9841 if (packet_support (PACKET_QSetWorkingDir) != PACKET_DISABLE)
9843 const char *inferior_cwd = get_inferior_cwd ();
9845 if (inferior_cwd != NULL)
9847 std::string hexpath = bin2hex ((const gdb_byte *) inferior_cwd,
9848 strlen (inferior_cwd));
9850 xsnprintf (rs->buf, get_remote_packet_size (),
9851 "QSetWorkingDir:%s", hexpath.c_str ());
9855 /* An empty inferior_cwd means that the user wants us to
9856 reset the remote server's inferior's cwd. */
9857 xsnprintf (rs->buf, get_remote_packet_size (),
9862 getpkt (&rs->buf, &rs->buf_size, 0);
9863 if (packet_ok (rs->buf,
9864 &remote_protocol_packets[PACKET_QSetWorkingDir])
9867 Remote replied unexpectedly while setting the inferior's working\n\
9874 /* In the extended protocol we want to be able to do things like
9875 "run" and have them basically work as expected. So we need
9876 a special create_inferior function. We support changing the
9877 executable file and the command line arguments, but not the
9881 extended_remote_target::create_inferior (const char *exec_file,
9882 const std::string &args,
9883 char **env, int from_tty)
9887 struct remote_state *rs = get_remote_state ();
9888 const char *remote_exec_file = get_remote_exec_file ();
9890 /* If running asynchronously, register the target file descriptor
9891 with the event loop. */
9892 if (target_can_async_p ())
9895 /* Disable address space randomization if requested (and supported). */
9896 if (supports_disable_randomization ())
9897 extended_remote_disable_randomization (disable_randomization);
9899 /* If startup-with-shell is on, we inform gdbserver to start the
9900 remote inferior using a shell. */
9901 if (packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
9903 xsnprintf (rs->buf, get_remote_packet_size (),
9904 "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
9906 getpkt (&rs->buf, &rs->buf_size, 0);
9907 if (strcmp (rs->buf, "OK") != 0)
9909 Remote replied unexpectedly while setting startup-with-shell: %s"),
9913 extended_remote_environment_support (rs);
9915 extended_remote_set_inferior_cwd (rs);
9917 /* Now restart the remote server. */
9918 run_worked = extended_remote_run (args) != -1;
9921 /* vRun was not supported. Fail if we need it to do what the
9923 if (remote_exec_file[0])
9924 error (_("Remote target does not support \"set remote exec-file\""));
9926 error (_("Remote target does not support \"set args\" or run <ARGS>"));
9928 /* Fall back to "R". */
9929 extended_remote_restart ();
9932 if (!have_inferiors ())
9934 /* Clean up from the last time we ran, before we mark the target
9935 running again. This will mark breakpoints uninserted, and
9936 get_offsets may insert breakpoints. */
9937 init_thread_list ();
9938 init_wait_for_inferior ();
9941 /* vRun's success return is a stop reply. */
9942 stop_reply = run_worked ? rs->buf : NULL;
9943 add_current_inferior_and_thread (stop_reply);
9945 /* Get updated offsets, if the stub uses qOffsets. */
9950 /* Given a location's target info BP_TGT and the packet buffer BUF, output
9951 the list of conditions (in agent expression bytecode format), if any, the
9952 target needs to evaluate. The output is placed into the packet buffer
9953 started from BUF and ended at BUF_END. */
9956 remote_add_target_side_condition (struct gdbarch *gdbarch,
9957 struct bp_target_info *bp_tgt, char *buf,
9960 if (bp_tgt->conditions.empty ())
9963 buf += strlen (buf);
9964 xsnprintf (buf, buf_end - buf, "%s", ";");
9967 /* Send conditions to the target. */
9968 for (agent_expr *aexpr : bp_tgt->conditions)
9970 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
9971 buf += strlen (buf);
9972 for (int i = 0; i < aexpr->len; ++i)
9973 buf = pack_hex_byte (buf, aexpr->buf[i]);
9980 remote_add_target_side_commands (struct gdbarch *gdbarch,
9981 struct bp_target_info *bp_tgt, char *buf)
9983 if (bp_tgt->tcommands.empty ())
9986 buf += strlen (buf);
9988 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
9989 buf += strlen (buf);
9991 /* Concatenate all the agent expressions that are commands into the
9993 for (agent_expr *aexpr : bp_tgt->tcommands)
9995 sprintf (buf, "X%x,", aexpr->len);
9996 buf += strlen (buf);
9997 for (int i = 0; i < aexpr->len; ++i)
9998 buf = pack_hex_byte (buf, aexpr->buf[i]);
10003 /* Insert a breakpoint. On targets that have software breakpoint
10004 support, we ask the remote target to do the work; on targets
10005 which don't, we insert a traditional memory breakpoint. */
10008 remote_target::insert_breakpoint (struct gdbarch *gdbarch,
10009 struct bp_target_info *bp_tgt)
10011 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
10012 If it succeeds, then set the support to PACKET_ENABLE. If it
10013 fails, and the user has explicitly requested the Z support then
10014 report an error, otherwise, mark it disabled and go on. */
10016 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
10018 CORE_ADDR addr = bp_tgt->reqstd_address;
10019 struct remote_state *rs;
10022 /* Make sure the remote is pointing at the right process, if
10024 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10025 set_general_process ();
10027 rs = get_remote_state ();
10029 endbuf = rs->buf + get_remote_packet_size ();
10034 addr = (ULONGEST) remote_address_masked (addr);
10035 p += hexnumstr (p, addr);
10036 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10038 if (supports_evaluation_of_breakpoint_conditions ())
10039 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10041 if (can_run_breakpoint_commands ())
10042 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10045 getpkt (&rs->buf, &rs->buf_size, 0);
10047 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
10053 case PACKET_UNKNOWN:
10058 /* If this breakpoint has target-side commands but this stub doesn't
10059 support Z0 packets, throw error. */
10060 if (!bp_tgt->tcommands.empty ())
10061 throw_error (NOT_SUPPORTED_ERROR, _("\
10062 Target doesn't support breakpoints that have target side commands."));
10064 return memory_insert_breakpoint (this, gdbarch, bp_tgt);
10068 remote_target::remove_breakpoint (struct gdbarch *gdbarch,
10069 struct bp_target_info *bp_tgt,
10070 enum remove_bp_reason reason)
10072 CORE_ADDR addr = bp_tgt->placed_address;
10073 struct remote_state *rs = get_remote_state ();
10075 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
10078 char *endbuf = rs->buf + get_remote_packet_size ();
10080 /* Make sure the remote is pointing at the right process, if
10082 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10083 set_general_process ();
10089 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
10090 p += hexnumstr (p, addr);
10091 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10094 getpkt (&rs->buf, &rs->buf_size, 0);
10096 return (rs->buf[0] == 'E');
10099 return memory_remove_breakpoint (this, gdbarch, bp_tgt, reason);
10102 static enum Z_packet_type
10103 watchpoint_to_Z_packet (int type)
10108 return Z_PACKET_WRITE_WP;
10111 return Z_PACKET_READ_WP;
10114 return Z_PACKET_ACCESS_WP;
10117 internal_error (__FILE__, __LINE__,
10118 _("hw_bp_to_z: bad watchpoint type %d"), type);
10123 remote_target::insert_watchpoint (CORE_ADDR addr, int len,
10124 enum target_hw_bp_type type, struct expression *cond)
10126 struct remote_state *rs = get_remote_state ();
10127 char *endbuf = rs->buf + get_remote_packet_size ();
10129 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10131 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
10134 /* Make sure the remote is pointing at the right process, if
10136 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10137 set_general_process ();
10139 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
10140 p = strchr (rs->buf, '\0');
10141 addr = remote_address_masked (addr);
10142 p += hexnumstr (p, (ULONGEST) addr);
10143 xsnprintf (p, endbuf - p, ",%x", len);
10146 getpkt (&rs->buf, &rs->buf_size, 0);
10148 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
10152 case PACKET_UNKNOWN:
10157 internal_error (__FILE__, __LINE__,
10158 _("remote_insert_watchpoint: reached end of function"));
10162 remote_target::watchpoint_addr_within_range (CORE_ADDR addr,
10163 CORE_ADDR start, int length)
10165 CORE_ADDR diff = remote_address_masked (addr - start);
10167 return diff < length;
10172 remote_target::remove_watchpoint (CORE_ADDR addr, int len,
10173 enum target_hw_bp_type type, struct expression *cond)
10175 struct remote_state *rs = get_remote_state ();
10176 char *endbuf = rs->buf + get_remote_packet_size ();
10178 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10180 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
10183 /* Make sure the remote is pointing at the right process, if
10185 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10186 set_general_process ();
10188 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
10189 p = strchr (rs->buf, '\0');
10190 addr = remote_address_masked (addr);
10191 p += hexnumstr (p, (ULONGEST) addr);
10192 xsnprintf (p, endbuf - p, ",%x", len);
10194 getpkt (&rs->buf, &rs->buf_size, 0);
10196 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
10199 case PACKET_UNKNOWN:
10204 internal_error (__FILE__, __LINE__,
10205 _("remote_remove_watchpoint: reached end of function"));
10209 int remote_hw_watchpoint_limit = -1;
10210 int remote_hw_watchpoint_length_limit = -1;
10211 int remote_hw_breakpoint_limit = -1;
10214 remote_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
10216 if (remote_hw_watchpoint_length_limit == 0)
10218 else if (remote_hw_watchpoint_length_limit < 0)
10220 else if (len <= remote_hw_watchpoint_length_limit)
10227 remote_target::can_use_hw_breakpoint (enum bptype type, int cnt, int ot)
10229 if (type == bp_hardware_breakpoint)
10231 if (remote_hw_breakpoint_limit == 0)
10233 else if (remote_hw_breakpoint_limit < 0)
10235 else if (cnt <= remote_hw_breakpoint_limit)
10240 if (remote_hw_watchpoint_limit == 0)
10242 else if (remote_hw_watchpoint_limit < 0)
10246 else if (cnt <= remote_hw_watchpoint_limit)
10252 /* The to_stopped_by_sw_breakpoint method of target remote. */
10255 remote_target::stopped_by_sw_breakpoint ()
10257 struct thread_info *thread = inferior_thread ();
10259 return (thread->priv != NULL
10260 && (get_remote_thread_info (thread)->stop_reason
10261 == TARGET_STOPPED_BY_SW_BREAKPOINT));
10264 /* The to_supports_stopped_by_sw_breakpoint method of target
10268 remote_target::supports_stopped_by_sw_breakpoint ()
10270 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
10273 /* The to_stopped_by_hw_breakpoint method of target remote. */
10276 remote_target::stopped_by_hw_breakpoint ()
10278 struct thread_info *thread = inferior_thread ();
10280 return (thread->priv != NULL
10281 && (get_remote_thread_info (thread)->stop_reason
10282 == TARGET_STOPPED_BY_HW_BREAKPOINT));
10285 /* The to_supports_stopped_by_hw_breakpoint method of target
10289 remote_target::supports_stopped_by_hw_breakpoint ()
10291 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
10295 remote_target::stopped_by_watchpoint ()
10297 struct thread_info *thread = inferior_thread ();
10299 return (thread->priv != NULL
10300 && (get_remote_thread_info (thread)->stop_reason
10301 == TARGET_STOPPED_BY_WATCHPOINT));
10305 remote_target::stopped_data_address (CORE_ADDR *addr_p)
10307 struct thread_info *thread = inferior_thread ();
10309 if (thread->priv != NULL
10310 && (get_remote_thread_info (thread)->stop_reason
10311 == TARGET_STOPPED_BY_WATCHPOINT))
10313 *addr_p = get_remote_thread_info (thread)->watch_data_address;
10322 remote_target::insert_hw_breakpoint (struct gdbarch *gdbarch,
10323 struct bp_target_info *bp_tgt)
10325 CORE_ADDR addr = bp_tgt->reqstd_address;
10326 struct remote_state *rs;
10330 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10333 /* Make sure the remote is pointing at the right process, if
10335 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10336 set_general_process ();
10338 rs = get_remote_state ();
10340 endbuf = rs->buf + get_remote_packet_size ();
10346 addr = remote_address_masked (addr);
10347 p += hexnumstr (p, (ULONGEST) addr);
10348 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
10350 if (supports_evaluation_of_breakpoint_conditions ())
10351 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10353 if (can_run_breakpoint_commands ())
10354 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10357 getpkt (&rs->buf, &rs->buf_size, 0);
10359 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10362 if (rs->buf[1] == '.')
10364 message = strchr (rs->buf + 2, '.');
10366 error (_("Remote failure reply: %s"), message + 1);
10369 case PACKET_UNKNOWN:
10374 internal_error (__FILE__, __LINE__,
10375 _("remote_insert_hw_breakpoint: reached end of function"));
10380 remote_target::remove_hw_breakpoint (struct gdbarch *gdbarch,
10381 struct bp_target_info *bp_tgt)
10384 struct remote_state *rs = get_remote_state ();
10386 char *endbuf = rs->buf + get_remote_packet_size ();
10388 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10391 /* Make sure the remote is pointing at the right process, if
10393 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10394 set_general_process ();
10400 addr = remote_address_masked (bp_tgt->placed_address);
10401 p += hexnumstr (p, (ULONGEST) addr);
10402 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
10405 getpkt (&rs->buf, &rs->buf_size, 0);
10407 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10410 case PACKET_UNKNOWN:
10415 internal_error (__FILE__, __LINE__,
10416 _("remote_remove_hw_breakpoint: reached end of function"));
10419 /* Verify memory using the "qCRC:" request. */
10422 remote_target::verify_memory (const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
10424 struct remote_state *rs = get_remote_state ();
10425 unsigned long host_crc, target_crc;
10428 /* It doesn't make sense to use qCRC if the remote target is
10429 connected but not running. */
10430 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
10432 enum packet_result result;
10434 /* Make sure the remote is pointing at the right process. */
10435 set_general_process ();
10437 /* FIXME: assumes lma can fit into long. */
10438 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
10439 (long) lma, (long) size);
10442 /* Be clever; compute the host_crc before waiting for target
10444 host_crc = xcrc32 (data, size, 0xffffffff);
10446 getpkt (&rs->buf, &rs->buf_size, 0);
10448 result = packet_ok (rs->buf,
10449 &remote_protocol_packets[PACKET_qCRC]);
10450 if (result == PACKET_ERROR)
10452 else if (result == PACKET_OK)
10454 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
10455 target_crc = target_crc * 16 + fromhex (*tmp);
10457 return (host_crc == target_crc);
10461 return simple_verify_memory (this, data, lma, size);
10464 /* compare-sections command
10466 With no arguments, compares each loadable section in the exec bfd
10467 with the same memory range on the target, and reports mismatches.
10468 Useful for verifying the image on the target against the exec file. */
10471 compare_sections_command (const char *args, int from_tty)
10474 const char *sectname;
10475 bfd_size_type size;
10478 int mismatched = 0;
10483 error (_("command cannot be used without an exec file"));
10485 /* Make sure the remote is pointing at the right process. */
10486 set_general_process ();
10488 if (args != NULL && strcmp (args, "-r") == 0)
10494 for (s = exec_bfd->sections; s; s = s->next)
10496 if (!(s->flags & SEC_LOAD))
10497 continue; /* Skip non-loadable section. */
10499 if (read_only && (s->flags & SEC_READONLY) == 0)
10500 continue; /* Skip writeable sections */
10502 size = bfd_get_section_size (s);
10504 continue; /* Skip zero-length section. */
10506 sectname = bfd_get_section_name (exec_bfd, s);
10507 if (args && strcmp (args, sectname) != 0)
10508 continue; /* Not the section selected by user. */
10510 matched = 1; /* Do this section. */
10513 gdb::byte_vector sectdata (size);
10514 bfd_get_section_contents (exec_bfd, s, sectdata.data (), 0, size);
10516 res = target_verify_memory (sectdata.data (), lma, size);
10519 error (_("target memory fault, section %s, range %s -- %s"), sectname,
10520 paddress (target_gdbarch (), lma),
10521 paddress (target_gdbarch (), lma + size));
10523 printf_filtered ("Section %s, range %s -- %s: ", sectname,
10524 paddress (target_gdbarch (), lma),
10525 paddress (target_gdbarch (), lma + size));
10527 printf_filtered ("matched.\n");
10530 printf_filtered ("MIS-MATCHED!\n");
10534 if (mismatched > 0)
10535 warning (_("One or more sections of the target image does not match\n\
10536 the loaded file\n"));
10537 if (args && !matched)
10538 printf_filtered (_("No loaded section named '%s'.\n"), args);
10541 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
10542 into remote target. The number of bytes written to the remote
10543 target is returned, or -1 for error. */
10545 static enum target_xfer_status
10546 remote_write_qxfer (const char *object_name,
10547 const char *annex, const gdb_byte *writebuf,
10548 ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
10549 struct packet_config *packet)
10553 struct remote_state *rs = get_remote_state ();
10554 int max_size = get_memory_write_packet_size ();
10556 if (packet_config_support (packet) == PACKET_DISABLE)
10557 return TARGET_XFER_E_IO;
10559 /* Insert header. */
10560 i = snprintf (rs->buf, max_size,
10561 "qXfer:%s:write:%s:%s:",
10562 object_name, annex ? annex : "",
10563 phex_nz (offset, sizeof offset));
10564 max_size -= (i + 1);
10566 /* Escape as much data as fits into rs->buf. */
10567 buf_len = remote_escape_output
10568 (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
10570 if (putpkt_binary (rs->buf, i + buf_len) < 0
10571 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10572 || packet_ok (rs->buf, packet) != PACKET_OK)
10573 return TARGET_XFER_E_IO;
10575 unpack_varlen_hex (rs->buf, &n);
10578 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
10581 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
10582 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
10583 number of bytes read is returned, or 0 for EOF, or -1 for error.
10584 The number of bytes read may be less than LEN without indicating an
10585 EOF. PACKET is checked and updated to indicate whether the remote
10586 target supports this object. */
10588 static enum target_xfer_status
10589 remote_read_qxfer (const char *object_name,
10591 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
10592 ULONGEST *xfered_len,
10593 struct packet_config *packet)
10595 struct remote_state *rs = get_remote_state ();
10596 LONGEST i, n, packet_len;
10598 if (packet_config_support (packet) == PACKET_DISABLE)
10599 return TARGET_XFER_E_IO;
10601 /* Check whether we've cached an end-of-object packet that matches
10603 if (rs->finished_object)
10605 if (strcmp (object_name, rs->finished_object) == 0
10606 && strcmp (annex ? annex : "", rs->finished_annex) == 0
10607 && offset == rs->finished_offset)
10608 return TARGET_XFER_EOF;
10611 /* Otherwise, we're now reading something different. Discard
10613 xfree (rs->finished_object);
10614 xfree (rs->finished_annex);
10615 rs->finished_object = NULL;
10616 rs->finished_annex = NULL;
10619 /* Request only enough to fit in a single packet. The actual data
10620 may not, since we don't know how much of it will need to be escaped;
10621 the target is free to respond with slightly less data. We subtract
10622 five to account for the response type and the protocol frame. */
10623 n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
10624 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
10625 object_name, annex ? annex : "",
10626 phex_nz (offset, sizeof offset),
10627 phex_nz (n, sizeof n));
10628 i = putpkt (rs->buf);
10630 return TARGET_XFER_E_IO;
10633 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10634 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
10635 return TARGET_XFER_E_IO;
10637 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
10638 error (_("Unknown remote qXfer reply: %s"), rs->buf);
10640 /* 'm' means there is (or at least might be) more data after this
10641 batch. That does not make sense unless there's at least one byte
10642 of data in this reply. */
10643 if (rs->buf[0] == 'm' && packet_len == 1)
10644 error (_("Remote qXfer reply contained no data."));
10646 /* Got some data. */
10647 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
10648 packet_len - 1, readbuf, n);
10650 /* 'l' is an EOF marker, possibly including a final block of data,
10651 or possibly empty. If we have the final block of a non-empty
10652 object, record this fact to bypass a subsequent partial read. */
10653 if (rs->buf[0] == 'l' && offset + i > 0)
10655 rs->finished_object = xstrdup (object_name);
10656 rs->finished_annex = xstrdup (annex ? annex : "");
10657 rs->finished_offset = offset + i;
10661 return TARGET_XFER_EOF;
10665 return TARGET_XFER_OK;
10669 enum target_xfer_status
10670 remote_target::xfer_partial (enum target_object object,
10671 const char *annex, gdb_byte *readbuf,
10672 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
10673 ULONGEST *xfered_len)
10675 struct remote_state *rs;
10679 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
10681 set_remote_traceframe ();
10682 set_general_thread (inferior_ptid);
10684 rs = get_remote_state ();
10686 /* Handle memory using the standard memory routines. */
10687 if (object == TARGET_OBJECT_MEMORY)
10689 /* If the remote target is connected but not running, we should
10690 pass this request down to a lower stratum (e.g. the executable
10692 if (!target_has_execution)
10693 return TARGET_XFER_EOF;
10695 if (writebuf != NULL)
10696 return remote_write_bytes (offset, writebuf, len, unit_size,
10699 return remote_read_bytes (this, offset, readbuf, len, unit_size,
10703 /* Handle SPU memory using qxfer packets. */
10704 if (object == TARGET_OBJECT_SPU)
10707 return remote_read_qxfer ("spu", annex, readbuf, offset, len,
10708 xfered_len, &remote_protocol_packets
10709 [PACKET_qXfer_spu_read]);
10711 return remote_write_qxfer ("spu", annex, writebuf, offset, len,
10712 xfered_len, &remote_protocol_packets
10713 [PACKET_qXfer_spu_write]);
10716 /* Handle extra signal info using qxfer packets. */
10717 if (object == TARGET_OBJECT_SIGNAL_INFO)
10720 return remote_read_qxfer ("siginfo", annex, readbuf, offset, len,
10721 xfered_len, &remote_protocol_packets
10722 [PACKET_qXfer_siginfo_read]);
10724 return remote_write_qxfer ("siginfo", annex,
10725 writebuf, offset, len, xfered_len,
10726 &remote_protocol_packets
10727 [PACKET_qXfer_siginfo_write]);
10730 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
10733 return remote_read_qxfer ("statictrace", annex,
10734 readbuf, offset, len, xfered_len,
10735 &remote_protocol_packets
10736 [PACKET_qXfer_statictrace_read]);
10738 return TARGET_XFER_E_IO;
10741 /* Only handle flash writes. */
10742 if (writebuf != NULL)
10746 case TARGET_OBJECT_FLASH:
10747 return remote_flash_write (this, offset, len, xfered_len,
10751 return TARGET_XFER_E_IO;
10755 /* Map pre-existing objects onto letters. DO NOT do this for new
10756 objects!!! Instead specify new query packets. */
10759 case TARGET_OBJECT_AVR:
10763 case TARGET_OBJECT_AUXV:
10764 gdb_assert (annex == NULL);
10765 return remote_read_qxfer ("auxv", annex, readbuf, offset, len,
10767 &remote_protocol_packets[PACKET_qXfer_auxv]);
10769 case TARGET_OBJECT_AVAILABLE_FEATURES:
10770 return remote_read_qxfer
10771 ("features", annex, readbuf, offset, len, xfered_len,
10772 &remote_protocol_packets[PACKET_qXfer_features]);
10774 case TARGET_OBJECT_LIBRARIES:
10775 return remote_read_qxfer
10776 ("libraries", annex, readbuf, offset, len, xfered_len,
10777 &remote_protocol_packets[PACKET_qXfer_libraries]);
10779 case TARGET_OBJECT_LIBRARIES_SVR4:
10780 return remote_read_qxfer
10781 ("libraries-svr4", annex, readbuf, offset, len, xfered_len,
10782 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
10784 case TARGET_OBJECT_MEMORY_MAP:
10785 gdb_assert (annex == NULL);
10786 return remote_read_qxfer ("memory-map", annex, readbuf, offset, len,
10788 &remote_protocol_packets[PACKET_qXfer_memory_map]);
10790 case TARGET_OBJECT_OSDATA:
10791 /* Should only get here if we're connected. */
10792 gdb_assert (rs->remote_desc);
10793 return remote_read_qxfer
10794 ("osdata", annex, readbuf, offset, len, xfered_len,
10795 &remote_protocol_packets[PACKET_qXfer_osdata]);
10797 case TARGET_OBJECT_THREADS:
10798 gdb_assert (annex == NULL);
10799 return remote_read_qxfer ("threads", annex, readbuf, offset, len,
10801 &remote_protocol_packets[PACKET_qXfer_threads]);
10803 case TARGET_OBJECT_TRACEFRAME_INFO:
10804 gdb_assert (annex == NULL);
10805 return remote_read_qxfer
10806 ("traceframe-info", annex, readbuf, offset, len, xfered_len,
10807 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
10809 case TARGET_OBJECT_FDPIC:
10810 return remote_read_qxfer ("fdpic", annex, readbuf, offset, len,
10812 &remote_protocol_packets[PACKET_qXfer_fdpic]);
10814 case TARGET_OBJECT_OPENVMS_UIB:
10815 return remote_read_qxfer ("uib", annex, readbuf, offset, len,
10817 &remote_protocol_packets[PACKET_qXfer_uib]);
10819 case TARGET_OBJECT_BTRACE:
10820 return remote_read_qxfer ("btrace", annex, readbuf, offset, len,
10822 &remote_protocol_packets[PACKET_qXfer_btrace]);
10824 case TARGET_OBJECT_BTRACE_CONF:
10825 return remote_read_qxfer ("btrace-conf", annex, readbuf, offset,
10827 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
10829 case TARGET_OBJECT_EXEC_FILE:
10830 return remote_read_qxfer ("exec-file", annex, readbuf, offset,
10832 &remote_protocol_packets[PACKET_qXfer_exec_file]);
10835 return TARGET_XFER_E_IO;
10838 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
10839 large enough let the caller deal with it. */
10840 if (len < get_remote_packet_size ())
10841 return TARGET_XFER_E_IO;
10842 len = get_remote_packet_size ();
10844 /* Except for querying the minimum buffer size, target must be open. */
10845 if (!rs->remote_desc)
10846 error (_("remote query is only available after target open"));
10848 gdb_assert (annex != NULL);
10849 gdb_assert (readbuf != NULL);
10853 *p2++ = query_type;
10855 /* We used one buffer char for the remote protocol q command and
10856 another for the query type. As the remote protocol encapsulation
10857 uses 4 chars plus one extra in case we are debugging
10858 (remote_debug), we have PBUFZIZ - 7 left to pack the query
10861 while (annex[i] && (i < (get_remote_packet_size () - 8)))
10863 /* Bad caller may have sent forbidden characters. */
10864 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
10869 gdb_assert (annex[i] == '\0');
10871 i = putpkt (rs->buf);
10873 return TARGET_XFER_E_IO;
10875 getpkt (&rs->buf, &rs->buf_size, 0);
10876 strcpy ((char *) readbuf, rs->buf);
10878 *xfered_len = strlen ((char *) readbuf);
10879 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
10882 /* Implementation of to_get_memory_xfer_limit. */
10885 remote_target::get_memory_xfer_limit ()
10887 return get_memory_write_packet_size ();
10891 remote_target::search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
10892 const gdb_byte *pattern, ULONGEST pattern_len,
10893 CORE_ADDR *found_addrp)
10895 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
10896 struct remote_state *rs = get_remote_state ();
10897 int max_size = get_memory_write_packet_size ();
10898 struct packet_config *packet =
10899 &remote_protocol_packets[PACKET_qSearch_memory];
10900 /* Number of packet bytes used to encode the pattern;
10901 this could be more than PATTERN_LEN due to escape characters. */
10902 int escaped_pattern_len;
10903 /* Amount of pattern that was encodable in the packet. */
10904 int used_pattern_len;
10907 ULONGEST found_addr;
10909 /* Don't go to the target if we don't have to. This is done before
10910 checking packet_config_support to avoid the possibility that a
10911 success for this edge case means the facility works in
10913 if (pattern_len > search_space_len)
10915 if (pattern_len == 0)
10917 *found_addrp = start_addr;
10921 /* If we already know the packet isn't supported, fall back to the simple
10922 way of searching memory. */
10924 if (packet_config_support (packet) == PACKET_DISABLE)
10926 /* Target doesn't provided special support, fall back and use the
10927 standard support (copy memory and do the search here). */
10928 return simple_search_memory (this, start_addr, search_space_len,
10929 pattern, pattern_len, found_addrp);
10932 /* Make sure the remote is pointing at the right process. */
10933 set_general_process ();
10935 /* Insert header. */
10936 i = snprintf (rs->buf, max_size,
10937 "qSearch:memory:%s;%s;",
10938 phex_nz (start_addr, addr_size),
10939 phex_nz (search_space_len, sizeof (search_space_len)));
10940 max_size -= (i + 1);
10942 /* Escape as much data as fits into rs->buf. */
10943 escaped_pattern_len =
10944 remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
10945 &used_pattern_len, max_size);
10947 /* Bail if the pattern is too large. */
10948 if (used_pattern_len != pattern_len)
10949 error (_("Pattern is too large to transmit to remote target."));
10951 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
10952 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10953 || packet_ok (rs->buf, packet) != PACKET_OK)
10955 /* The request may not have worked because the command is not
10956 supported. If so, fall back to the simple way. */
10957 if (packet_config_support (packet) == PACKET_DISABLE)
10959 return simple_search_memory (this, start_addr, search_space_len,
10960 pattern, pattern_len, found_addrp);
10965 if (rs->buf[0] == '0')
10967 else if (rs->buf[0] == '1')
10970 if (rs->buf[1] != ',')
10971 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
10972 unpack_varlen_hex (rs->buf + 2, &found_addr);
10973 *found_addrp = found_addr;
10976 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
10982 remote_target::rcmd (const char *command, struct ui_file *outbuf)
10984 struct remote_state *rs = get_remote_state ();
10987 if (!rs->remote_desc)
10988 error (_("remote rcmd is only available after target open"));
10990 /* Send a NULL command across as an empty command. */
10991 if (command == NULL)
10994 /* The query prefix. */
10995 strcpy (rs->buf, "qRcmd,");
10996 p = strchr (rs->buf, '\0');
10998 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
10999 > get_remote_packet_size ())
11000 error (_("\"monitor\" command ``%s'' is too long."), command);
11002 /* Encode the actual command. */
11003 bin2hex ((const gdb_byte *) command, p, strlen (command));
11005 if (putpkt (rs->buf) < 0)
11006 error (_("Communication problem with target."));
11008 /* get/display the response */
11013 /* XXX - see also remote_get_noisy_reply(). */
11014 QUIT; /* Allow user to bail out with ^C. */
11016 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
11018 /* Timeout. Continue to (try to) read responses.
11019 This is better than stopping with an error, assuming the stub
11020 is still executing the (long) monitor command.
11021 If needed, the user can interrupt gdb using C-c, obtaining
11022 an effect similar to stop on timeout. */
11026 if (buf[0] == '\0')
11027 error (_("Target does not support this command."));
11028 if (buf[0] == 'O' && buf[1] != 'K')
11030 remote_console_output (buf + 1); /* 'O' message from stub. */
11033 if (strcmp (buf, "OK") == 0)
11035 if (strlen (buf) == 3 && buf[0] == 'E'
11036 && isdigit (buf[1]) && isdigit (buf[2]))
11038 error (_("Protocol error with Rcmd"));
11040 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
11042 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
11044 fputc_unfiltered (c, outbuf);
11050 std::vector<mem_region>
11051 remote_target::memory_map ()
11053 std::vector<mem_region> result;
11054 gdb::optional<gdb::char_vector> text
11055 = target_read_stralloc (target_stack, TARGET_OBJECT_MEMORY_MAP, NULL);
11058 result = parse_memory_map (text->data ());
11064 packet_command (const char *args, int from_tty)
11066 struct remote_state *rs = get_remote_state ();
11068 if (!rs->remote_desc)
11069 error (_("command can only be used with remote target"));
11072 error (_("remote-packet command requires packet text as argument"));
11074 puts_filtered ("sending: ");
11075 print_packet (args);
11076 puts_filtered ("\n");
11079 getpkt (&rs->buf, &rs->buf_size, 0);
11080 puts_filtered ("received: ");
11081 print_packet (rs->buf);
11082 puts_filtered ("\n");
11086 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
11088 static void display_thread_info (struct gdb_ext_thread_info *info);
11090 static void threadset_test_cmd (char *cmd, int tty);
11092 static void threadalive_test (char *cmd, int tty);
11094 static void threadlist_test_cmd (char *cmd, int tty);
11096 int get_and_display_threadinfo (threadref *ref);
11098 static void threadinfo_test_cmd (char *cmd, int tty);
11100 static int thread_display_step (threadref *ref, void *context);
11102 static void threadlist_update_test_cmd (char *cmd, int tty);
11104 static void init_remote_threadtests (void);
11106 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
11109 threadset_test_cmd (const char *cmd, int tty)
11111 int sample_thread = SAMPLE_THREAD;
11113 printf_filtered (_("Remote threadset test\n"));
11114 set_general_thread (sample_thread);
11119 threadalive_test (const char *cmd, int tty)
11121 int sample_thread = SAMPLE_THREAD;
11122 int pid = ptid_get_pid (inferior_ptid);
11123 ptid_t ptid = ptid_build (pid, sample_thread, 0);
11125 if (remote_thread_alive (ptid))
11126 printf_filtered ("PASS: Thread alive test\n");
11128 printf_filtered ("FAIL: Thread alive test\n");
11131 void output_threadid (char *title, threadref *ref);
11134 output_threadid (char *title, threadref *ref)
11138 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
11140 printf_filtered ("%s %s\n", title, (&hexid[0]));
11144 threadlist_test_cmd (const char *cmd, int tty)
11147 threadref nextthread;
11148 int done, result_count;
11149 threadref threadlist[3];
11151 printf_filtered ("Remote Threadlist test\n");
11152 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
11153 &result_count, &threadlist[0]))
11154 printf_filtered ("FAIL: threadlist test\n");
11157 threadref *scan = threadlist;
11158 threadref *limit = scan + result_count;
11160 while (scan < limit)
11161 output_threadid (" thread ", scan++);
11166 display_thread_info (struct gdb_ext_thread_info *info)
11168 output_threadid ("Threadid: ", &info->threadid);
11169 printf_filtered ("Name: %s\n ", info->shortname);
11170 printf_filtered ("State: %s\n", info->display);
11171 printf_filtered ("other: %s\n\n", info->more_display);
11175 get_and_display_threadinfo (threadref *ref)
11179 struct gdb_ext_thread_info threadinfo;
11181 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
11182 | TAG_MOREDISPLAY | TAG_DISPLAY;
11183 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
11184 display_thread_info (&threadinfo);
11189 threadinfo_test_cmd (const char *cmd, int tty)
11191 int athread = SAMPLE_THREAD;
11195 int_to_threadref (&thread, athread);
11196 printf_filtered ("Remote Threadinfo test\n");
11197 if (!get_and_display_threadinfo (&thread))
11198 printf_filtered ("FAIL cannot get thread info\n");
11202 thread_display_step (threadref *ref, void *context)
11204 /* output_threadid(" threadstep ",ref); *//* simple test */
11205 return get_and_display_threadinfo (ref);
11209 threadlist_update_test_cmd (const char *cmd, int tty)
11211 printf_filtered ("Remote Threadlist update test\n");
11212 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
11216 init_remote_threadtests (void)
11218 add_com ("tlist", class_obscure, threadlist_test_cmd,
11219 _("Fetch and print the remote list of "
11220 "thread identifiers, one pkt only"));
11221 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
11222 _("Fetch and display info about one thread"));
11223 add_com ("tset", class_obscure, threadset_test_cmd,
11224 _("Test setting to a different thread"));
11225 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
11226 _("Iterate through updating all remote thread info"));
11227 add_com ("talive", class_obscure, threadalive_test,
11228 _(" Remote thread alive test "));
11233 /* Convert a thread ID to a string. Returns the string in a static
11237 remote_target::pid_to_str (ptid_t ptid)
11239 static char buf[64];
11240 struct remote_state *rs = get_remote_state ();
11242 if (ptid_equal (ptid, null_ptid))
11243 return normal_pid_to_str (ptid);
11244 else if (ptid_is_pid (ptid))
11246 /* Printing an inferior target id. */
11248 /* When multi-process extensions are off, there's no way in the
11249 remote protocol to know the remote process id, if there's any
11250 at all. There's one exception --- when we're connected with
11251 target extended-remote, and we manually attached to a process
11252 with "attach PID". We don't record anywhere a flag that
11253 allows us to distinguish that case from the case of
11254 connecting with extended-remote and the stub already being
11255 attached to a process, and reporting yes to qAttached, hence
11256 no smart special casing here. */
11257 if (!remote_multi_process_p (rs))
11259 xsnprintf (buf, sizeof buf, "Remote target");
11263 return normal_pid_to_str (ptid);
11267 if (ptid_equal (magic_null_ptid, ptid))
11268 xsnprintf (buf, sizeof buf, "Thread <main>");
11269 else if (remote_multi_process_p (rs))
11270 if (ptid_get_lwp (ptid) == 0)
11271 return normal_pid_to_str (ptid);
11273 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
11274 ptid_get_pid (ptid), ptid_get_lwp (ptid));
11276 xsnprintf (buf, sizeof buf, "Thread %ld",
11277 ptid_get_lwp (ptid));
11282 /* Get the address of the thread local variable in OBJFILE which is
11283 stored at OFFSET within the thread local storage for thread PTID. */
11286 remote_target::get_thread_local_address (ptid_t ptid, CORE_ADDR lm,
11289 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
11291 struct remote_state *rs = get_remote_state ();
11293 char *endp = rs->buf + get_remote_packet_size ();
11294 enum packet_result result;
11296 strcpy (p, "qGetTLSAddr:");
11298 p = write_ptid (p, endp, ptid);
11300 p += hexnumstr (p, offset);
11302 p += hexnumstr (p, lm);
11306 getpkt (&rs->buf, &rs->buf_size, 0);
11307 result = packet_ok (rs->buf,
11308 &remote_protocol_packets[PACKET_qGetTLSAddr]);
11309 if (result == PACKET_OK)
11313 unpack_varlen_hex (rs->buf, &result);
11316 else if (result == PACKET_UNKNOWN)
11317 throw_error (TLS_GENERIC_ERROR,
11318 _("Remote target doesn't support qGetTLSAddr packet"));
11320 throw_error (TLS_GENERIC_ERROR,
11321 _("Remote target failed to process qGetTLSAddr request"));
11324 throw_error (TLS_GENERIC_ERROR,
11325 _("TLS not supported or disabled on this target"));
11330 /* Provide thread local base, i.e. Thread Information Block address.
11331 Returns 1 if ptid is found and thread_local_base is non zero. */
11334 remote_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
11336 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
11338 struct remote_state *rs = get_remote_state ();
11340 char *endp = rs->buf + get_remote_packet_size ();
11341 enum packet_result result;
11343 strcpy (p, "qGetTIBAddr:");
11345 p = write_ptid (p, endp, ptid);
11349 getpkt (&rs->buf, &rs->buf_size, 0);
11350 result = packet_ok (rs->buf,
11351 &remote_protocol_packets[PACKET_qGetTIBAddr]);
11352 if (result == PACKET_OK)
11356 unpack_varlen_hex (rs->buf, &result);
11358 *addr = (CORE_ADDR) result;
11361 else if (result == PACKET_UNKNOWN)
11362 error (_("Remote target doesn't support qGetTIBAddr packet"));
11364 error (_("Remote target failed to process qGetTIBAddr request"));
11367 error (_("qGetTIBAddr not supported or disabled on this target"));
11372 /* Support for inferring a target description based on the current
11373 architecture and the size of a 'g' packet. While the 'g' packet
11374 can have any size (since optional registers can be left off the
11375 end), some sizes are easily recognizable given knowledge of the
11376 approximate architecture. */
11378 struct remote_g_packet_guess
11381 const struct target_desc *tdesc;
11383 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
11384 DEF_VEC_O(remote_g_packet_guess_s);
11386 struct remote_g_packet_data
11388 VEC(remote_g_packet_guess_s) *guesses;
11391 static struct gdbarch_data *remote_g_packet_data_handle;
11394 remote_g_packet_data_init (struct obstack *obstack)
11396 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
11400 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
11401 const struct target_desc *tdesc)
11403 struct remote_g_packet_data *data
11404 = ((struct remote_g_packet_data *)
11405 gdbarch_data (gdbarch, remote_g_packet_data_handle));
11406 struct remote_g_packet_guess new_guess, *guess;
11409 gdb_assert (tdesc != NULL);
11412 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
11414 if (guess->bytes == bytes)
11415 internal_error (__FILE__, __LINE__,
11416 _("Duplicate g packet description added for size %d"),
11419 new_guess.bytes = bytes;
11420 new_guess.tdesc = tdesc;
11421 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
11424 /* Return 1 if remote_read_description would do anything on this target
11425 and architecture, 0 otherwise. */
11428 remote_read_description_p (struct target_ops *target)
11430 struct remote_g_packet_data *data
11431 = ((struct remote_g_packet_data *)
11432 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
11434 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
11440 const struct target_desc *
11441 remote_target::read_description ()
11443 struct remote_g_packet_data *data
11444 = ((struct remote_g_packet_data *)
11445 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
11447 /* Do not try this during initial connection, when we do not know
11448 whether there is a running but stopped thread. */
11449 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
11450 return beneath->read_description ();
11452 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
11454 struct remote_g_packet_guess *guess;
11456 int bytes = send_g_packet ();
11459 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
11461 if (guess->bytes == bytes)
11462 return guess->tdesc;
11464 /* We discard the g packet. A minor optimization would be to
11465 hold on to it, and fill the register cache once we have selected
11466 an architecture, but it's too tricky to do safely. */
11469 return beneath->read_description ();
11472 /* Remote file transfer support. This is host-initiated I/O, not
11473 target-initiated; for target-initiated, see remote-fileio.c. */
11475 /* If *LEFT is at least the length of STRING, copy STRING to
11476 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11477 decrease *LEFT. Otherwise raise an error. */
11480 remote_buffer_add_string (char **buffer, int *left, const char *string)
11482 int len = strlen (string);
11485 error (_("Packet too long for target."));
11487 memcpy (*buffer, string, len);
11491 /* NUL-terminate the buffer as a convenience, if there is
11497 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
11498 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11499 decrease *LEFT. Otherwise raise an error. */
11502 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
11505 if (2 * len > *left)
11506 error (_("Packet too long for target."));
11508 bin2hex (bytes, *buffer, len);
11509 *buffer += 2 * len;
11512 /* NUL-terminate the buffer as a convenience, if there is
11518 /* If *LEFT is large enough, convert VALUE to hex and add it to
11519 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11520 decrease *LEFT. Otherwise raise an error. */
11523 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
11525 int len = hexnumlen (value);
11528 error (_("Packet too long for target."));
11530 hexnumstr (*buffer, value);
11534 /* NUL-terminate the buffer as a convenience, if there is
11540 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
11541 value, *REMOTE_ERRNO to the remote error number or zero if none
11542 was included, and *ATTACHMENT to point to the start of the annex
11543 if any. The length of the packet isn't needed here; there may
11544 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
11546 Return 0 if the packet could be parsed, -1 if it could not. If
11547 -1 is returned, the other variables may not be initialized. */
11550 remote_hostio_parse_result (char *buffer, int *retcode,
11551 int *remote_errno, char **attachment)
11556 *attachment = NULL;
11558 if (buffer[0] != 'F')
11562 *retcode = strtol (&buffer[1], &p, 16);
11563 if (errno != 0 || p == &buffer[1])
11566 /* Check for ",errno". */
11570 *remote_errno = strtol (p + 1, &p2, 16);
11571 if (errno != 0 || p + 1 == p2)
11576 /* Check for ";attachment". If there is no attachment, the
11577 packet should end here. */
11580 *attachment = p + 1;
11583 else if (*p == '\0')
11589 /* Send a prepared I/O packet to the target and read its response.
11590 The prepared packet is in the global RS->BUF before this function
11591 is called, and the answer is there when we return.
11593 COMMAND_BYTES is the length of the request to send, which may include
11594 binary data. WHICH_PACKET is the packet configuration to check
11595 before attempting a packet. If an error occurs, *REMOTE_ERRNO
11596 is set to the error number and -1 is returned. Otherwise the value
11597 returned by the function is returned.
11599 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
11600 attachment is expected; an error will be reported if there's a
11601 mismatch. If one is found, *ATTACHMENT will be set to point into
11602 the packet buffer and *ATTACHMENT_LEN will be set to the
11603 attachment's length. */
11606 remote_hostio_send_command (int command_bytes, int which_packet,
11607 int *remote_errno, char **attachment,
11608 int *attachment_len)
11610 struct remote_state *rs = get_remote_state ();
11611 int ret, bytes_read;
11612 char *attachment_tmp;
11614 if (packet_support (which_packet) == PACKET_DISABLE)
11616 *remote_errno = FILEIO_ENOSYS;
11620 putpkt_binary (rs->buf, command_bytes);
11621 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
11623 /* If it timed out, something is wrong. Don't try to parse the
11625 if (bytes_read < 0)
11627 *remote_errno = FILEIO_EINVAL;
11631 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
11634 *remote_errno = FILEIO_EINVAL;
11636 case PACKET_UNKNOWN:
11637 *remote_errno = FILEIO_ENOSYS;
11643 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
11646 *remote_errno = FILEIO_EINVAL;
11650 /* Make sure we saw an attachment if and only if we expected one. */
11651 if ((attachment_tmp == NULL && attachment != NULL)
11652 || (attachment_tmp != NULL && attachment == NULL))
11654 *remote_errno = FILEIO_EINVAL;
11658 /* If an attachment was found, it must point into the packet buffer;
11659 work out how many bytes there were. */
11660 if (attachment_tmp != NULL)
11662 *attachment = attachment_tmp;
11663 *attachment_len = bytes_read - (*attachment - rs->buf);
11669 /* Invalidate the readahead cache. */
11672 readahead_cache_invalidate (void)
11674 struct remote_state *rs = get_remote_state ();
11676 rs->readahead_cache.fd = -1;
11679 /* Invalidate the readahead cache if it is holding data for FD. */
11682 readahead_cache_invalidate_fd (int fd)
11684 struct remote_state *rs = get_remote_state ();
11686 if (rs->readahead_cache.fd == fd)
11687 rs->readahead_cache.fd = -1;
11690 /* Set the filesystem remote_hostio functions that take FILENAME
11691 arguments will use. Return 0 on success, or -1 if an error
11692 occurs (and set *REMOTE_ERRNO). */
11695 remote_hostio_set_filesystem (struct inferior *inf, int *remote_errno)
11697 struct remote_state *rs = get_remote_state ();
11698 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
11700 int left = get_remote_packet_size () - 1;
11704 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11707 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
11710 remote_buffer_add_string (&p, &left, "vFile:setfs:");
11712 xsnprintf (arg, sizeof (arg), "%x", required_pid);
11713 remote_buffer_add_string (&p, &left, arg);
11715 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
11716 remote_errno, NULL, NULL);
11718 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11722 rs->fs_pid = required_pid;
11727 /* Implementation of to_fileio_open. */
11730 remote_hostio_open (struct target_ops *self,
11731 struct inferior *inf, const char *filename,
11732 int flags, int mode, int warn_if_slow,
11735 struct remote_state *rs = get_remote_state ();
11737 int left = get_remote_packet_size () - 1;
11741 static int warning_issued = 0;
11743 printf_unfiltered (_("Reading %s from remote target...\n"),
11746 if (!warning_issued)
11748 warning (_("File transfers from remote targets can be slow."
11749 " Use \"set sysroot\" to access files locally"
11751 warning_issued = 1;
11755 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11758 remote_buffer_add_string (&p, &left, "vFile:open:");
11760 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11761 strlen (filename));
11762 remote_buffer_add_string (&p, &left, ",");
11764 remote_buffer_add_int (&p, &left, flags);
11765 remote_buffer_add_string (&p, &left, ",");
11767 remote_buffer_add_int (&p, &left, mode);
11769 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
11770 remote_errno, NULL, NULL);
11774 remote_target::fileio_open (struct inferior *inf, const char *filename,
11775 int flags, int mode, int warn_if_slow,
11778 return remote_hostio_open (this, inf, filename, flags, mode, warn_if_slow,
11782 /* Implementation of to_fileio_pwrite. */
11785 remote_hostio_pwrite (struct target_ops *self,
11786 int fd, const gdb_byte *write_buf, int len,
11787 ULONGEST offset, int *remote_errno)
11789 struct remote_state *rs = get_remote_state ();
11791 int left = get_remote_packet_size ();
11794 readahead_cache_invalidate_fd (fd);
11796 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
11798 remote_buffer_add_int (&p, &left, fd);
11799 remote_buffer_add_string (&p, &left, ",");
11801 remote_buffer_add_int (&p, &left, offset);
11802 remote_buffer_add_string (&p, &left, ",");
11804 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
11805 get_remote_packet_size () - (p - rs->buf));
11807 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
11808 remote_errno, NULL, NULL);
11812 remote_target::fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
11813 ULONGEST offset, int *remote_errno)
11815 return remote_hostio_pwrite (this, fd, write_buf, len, offset, remote_errno);
11818 /* Helper for the implementation of to_fileio_pread. Read the file
11819 from the remote side with vFile:pread. */
11822 remote_hostio_pread_vFile (struct target_ops *self,
11823 int fd, gdb_byte *read_buf, int len,
11824 ULONGEST offset, int *remote_errno)
11826 struct remote_state *rs = get_remote_state ();
11829 int left = get_remote_packet_size ();
11830 int ret, attachment_len;
11833 remote_buffer_add_string (&p, &left, "vFile:pread:");
11835 remote_buffer_add_int (&p, &left, fd);
11836 remote_buffer_add_string (&p, &left, ",");
11838 remote_buffer_add_int (&p, &left, len);
11839 remote_buffer_add_string (&p, &left, ",");
11841 remote_buffer_add_int (&p, &left, offset);
11843 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
11844 remote_errno, &attachment,
11850 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11852 if (read_len != ret)
11853 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
11858 /* Serve pread from the readahead cache. Returns number of bytes
11859 read, or 0 if the request can't be served from the cache. */
11862 remote_hostio_pread_from_cache (struct remote_state *rs,
11863 int fd, gdb_byte *read_buf, size_t len,
11866 struct readahead_cache *cache = &rs->readahead_cache;
11868 if (cache->fd == fd
11869 && cache->offset <= offset
11870 && offset < cache->offset + cache->bufsize)
11872 ULONGEST max = cache->offset + cache->bufsize;
11874 if (offset + len > max)
11875 len = max - offset;
11877 memcpy (read_buf, cache->buf + offset - cache->offset, len);
11884 /* Implementation of to_fileio_pread. */
11887 remote_hostio_pread (struct target_ops *self,
11888 int fd, gdb_byte *read_buf, int len,
11889 ULONGEST offset, int *remote_errno)
11892 struct remote_state *rs = get_remote_state ();
11893 struct readahead_cache *cache = &rs->readahead_cache;
11895 ret = remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11898 cache->hit_count++;
11901 fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
11902 pulongest (cache->hit_count));
11906 cache->miss_count++;
11908 fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
11909 pulongest (cache->miss_count));
11912 cache->offset = offset;
11913 cache->bufsize = get_remote_packet_size ();
11914 cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
11916 ret = remote_hostio_pread_vFile (self, cache->fd, cache->buf, cache->bufsize,
11917 cache->offset, remote_errno);
11920 readahead_cache_invalidate_fd (fd);
11924 cache->bufsize = ret;
11925 return remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11929 remote_target::fileio_pread (int fd, gdb_byte *read_buf, int len,
11930 ULONGEST offset, int *remote_errno)
11932 return remote_hostio_pread (this, fd, read_buf, len, offset, remote_errno);
11935 /* Implementation of to_fileio_close. */
11938 remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
11940 struct remote_state *rs = get_remote_state ();
11942 int left = get_remote_packet_size () - 1;
11944 readahead_cache_invalidate_fd (fd);
11946 remote_buffer_add_string (&p, &left, "vFile:close:");
11948 remote_buffer_add_int (&p, &left, fd);
11950 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
11951 remote_errno, NULL, NULL);
11955 remote_target::fileio_close (int fd, int *remote_errno)
11957 return remote_hostio_close (this, fd, remote_errno);
11960 /* Implementation of to_fileio_unlink. */
11963 remote_hostio_unlink (struct target_ops *self,
11964 struct inferior *inf, const char *filename,
11967 struct remote_state *rs = get_remote_state ();
11969 int left = get_remote_packet_size () - 1;
11971 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11974 remote_buffer_add_string (&p, &left, "vFile:unlink:");
11976 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11977 strlen (filename));
11979 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
11980 remote_errno, NULL, NULL);
11984 remote_target::fileio_unlink (struct inferior *inf, const char *filename,
11987 return remote_hostio_unlink (this, inf, filename, remote_errno);
11990 /* Implementation of to_fileio_readlink. */
11992 gdb::optional<std::string>
11993 remote_target::fileio_readlink (struct inferior *inf, const char *filename,
11996 struct remote_state *rs = get_remote_state ();
11999 int left = get_remote_packet_size ();
12000 int len, attachment_len;
12003 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12006 remote_buffer_add_string (&p, &left, "vFile:readlink:");
12008 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12009 strlen (filename));
12011 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
12012 remote_errno, &attachment,
12018 std::string ret (len, '\0');
12020 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12021 (gdb_byte *) &ret[0], len);
12022 if (read_len != len)
12023 error (_("Readlink returned %d, but %d bytes."), len, read_len);
12028 /* Implementation of to_fileio_fstat. */
12031 remote_target::fileio_fstat (int fd, struct stat *st, int *remote_errno)
12033 struct remote_state *rs = get_remote_state ();
12035 int left = get_remote_packet_size ();
12036 int attachment_len, ret;
12038 struct fio_stat fst;
12041 remote_buffer_add_string (&p, &left, "vFile:fstat:");
12043 remote_buffer_add_int (&p, &left, fd);
12045 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
12046 remote_errno, &attachment,
12050 if (*remote_errno != FILEIO_ENOSYS)
12053 /* Strictly we should return -1, ENOSYS here, but when
12054 "set sysroot remote:" was implemented in August 2008
12055 BFD's need for a stat function was sidestepped with
12056 this hack. This was not remedied until March 2015
12057 so we retain the previous behavior to avoid breaking
12060 Note that the memset is a March 2015 addition; older
12061 GDBs set st_size *and nothing else* so the structure
12062 would have garbage in all other fields. This might
12063 break something but retaining the previous behavior
12064 here would be just too wrong. */
12066 memset (st, 0, sizeof (struct stat));
12067 st->st_size = INT_MAX;
12071 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12072 (gdb_byte *) &fst, sizeof (fst));
12074 if (read_len != ret)
12075 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
12077 if (read_len != sizeof (fst))
12078 error (_("vFile:fstat returned %d bytes, but expecting %d."),
12079 read_len, (int) sizeof (fst));
12081 remote_fileio_to_host_stat (&fst, st);
12086 /* Implementation of to_filesystem_is_local. */
12089 remote_target::filesystem_is_local ()
12091 /* Valgrind GDB presents itself as a remote target but works
12092 on the local filesystem: it does not implement remote get
12093 and users are not expected to set a sysroot. To handle
12094 this case we treat the remote filesystem as local if the
12095 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
12096 does not support vFile:open. */
12097 if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
12099 enum packet_support ps = packet_support (PACKET_vFile_open);
12101 if (ps == PACKET_SUPPORT_UNKNOWN)
12103 int fd, remote_errno;
12105 /* Try opening a file to probe support. The supplied
12106 filename is irrelevant, we only care about whether
12107 the stub recognizes the packet or not. */
12108 fd = remote_hostio_open (this, NULL, "just probing",
12109 FILEIO_O_RDONLY, 0700, 0,
12113 remote_hostio_close (this, fd, &remote_errno);
12115 ps = packet_support (PACKET_vFile_open);
12118 if (ps == PACKET_DISABLE)
12120 static int warning_issued = 0;
12122 if (!warning_issued)
12124 warning (_("remote target does not support file"
12125 " transfer, attempting to access files"
12126 " from local filesystem."));
12127 warning_issued = 1;
12138 remote_fileio_errno_to_host (int errnum)
12144 case FILEIO_ENOENT:
12152 case FILEIO_EACCES:
12154 case FILEIO_EFAULT:
12158 case FILEIO_EEXIST:
12160 case FILEIO_ENODEV:
12162 case FILEIO_ENOTDIR:
12164 case FILEIO_EISDIR:
12166 case FILEIO_EINVAL:
12168 case FILEIO_ENFILE:
12170 case FILEIO_EMFILE:
12174 case FILEIO_ENOSPC:
12176 case FILEIO_ESPIPE:
12180 case FILEIO_ENOSYS:
12182 case FILEIO_ENAMETOOLONG:
12183 return ENAMETOOLONG;
12189 remote_hostio_error (int errnum)
12191 int host_error = remote_fileio_errno_to_host (errnum);
12193 if (host_error == -1)
12194 error (_("Unknown remote I/O error %d"), errnum);
12196 error (_("Remote I/O error: %s"), safe_strerror (host_error));
12200 remote_hostio_close_cleanup (void *opaque)
12202 int fd = *(int *) opaque;
12205 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
12209 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
12211 struct cleanup *back_to, *close_cleanup;
12212 int retcode, fd, remote_errno, bytes, io_size;
12214 int bytes_in_buffer;
12217 struct remote_state *rs = get_remote_state ();
12219 if (!rs->remote_desc)
12220 error (_("command can only be used with remote target"));
12222 gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
12224 perror_with_name (local_file);
12226 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
12227 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
12229 0700, 0, &remote_errno);
12231 remote_hostio_error (remote_errno);
12233 /* Send up to this many bytes at once. They won't all fit in the
12234 remote packet limit, so we'll transfer slightly fewer. */
12235 io_size = get_remote_packet_size ();
12236 buffer = (gdb_byte *) xmalloc (io_size);
12237 back_to = make_cleanup (xfree, buffer);
12239 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
12241 bytes_in_buffer = 0;
12244 while (bytes_in_buffer || !saw_eof)
12248 bytes = fread (buffer + bytes_in_buffer, 1,
12249 io_size - bytes_in_buffer,
12253 if (ferror (file.get ()))
12254 error (_("Error reading %s."), local_file);
12257 /* EOF. Unless there is something still in the
12258 buffer from the last iteration, we are done. */
12260 if (bytes_in_buffer == 0)
12268 bytes += bytes_in_buffer;
12269 bytes_in_buffer = 0;
12271 retcode = remote_hostio_pwrite (find_target_at (process_stratum),
12273 offset, &remote_errno);
12276 remote_hostio_error (remote_errno);
12277 else if (retcode == 0)
12278 error (_("Remote write of %d bytes returned 0!"), bytes);
12279 else if (retcode < bytes)
12281 /* Short write. Save the rest of the read data for the next
12283 bytes_in_buffer = bytes - retcode;
12284 memmove (buffer, buffer + retcode, bytes_in_buffer);
12290 discard_cleanups (close_cleanup);
12291 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
12292 remote_hostio_error (remote_errno);
12295 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
12296 do_cleanups (back_to);
12300 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
12302 struct cleanup *back_to, *close_cleanup;
12303 int fd, remote_errno, bytes, io_size;
12306 struct remote_state *rs = get_remote_state ();
12308 if (!rs->remote_desc)
12309 error (_("command can only be used with remote target"));
12311 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
12312 remote_file, FILEIO_O_RDONLY, 0, 0,
12315 remote_hostio_error (remote_errno);
12317 gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
12319 perror_with_name (local_file);
12321 /* Send up to this many bytes at once. They won't all fit in the
12322 remote packet limit, so we'll transfer slightly fewer. */
12323 io_size = get_remote_packet_size ();
12324 buffer = (gdb_byte *) xmalloc (io_size);
12325 back_to = make_cleanup (xfree, buffer);
12327 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
12332 bytes = remote_hostio_pread (find_target_at (process_stratum),
12333 fd, buffer, io_size, offset, &remote_errno);
12335 /* Success, but no bytes, means end-of-file. */
12338 remote_hostio_error (remote_errno);
12342 bytes = fwrite (buffer, 1, bytes, file.get ());
12344 perror_with_name (local_file);
12347 discard_cleanups (close_cleanup);
12348 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
12349 remote_hostio_error (remote_errno);
12352 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
12353 do_cleanups (back_to);
12357 remote_file_delete (const char *remote_file, int from_tty)
12359 int retcode, remote_errno;
12360 struct remote_state *rs = get_remote_state ();
12362 if (!rs->remote_desc)
12363 error (_("command can only be used with remote target"));
12365 retcode = remote_hostio_unlink (find_target_at (process_stratum),
12366 NULL, remote_file, &remote_errno);
12368 remote_hostio_error (remote_errno);
12371 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
12375 remote_put_command (const char *args, int from_tty)
12378 error_no_arg (_("file to put"));
12380 gdb_argv argv (args);
12381 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12382 error (_("Invalid parameters to remote put"));
12384 remote_file_put (argv[0], argv[1], from_tty);
12388 remote_get_command (const char *args, int from_tty)
12391 error_no_arg (_("file to get"));
12393 gdb_argv argv (args);
12394 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12395 error (_("Invalid parameters to remote get"));
12397 remote_file_get (argv[0], argv[1], from_tty);
12401 remote_delete_command (const char *args, int from_tty)
12404 error_no_arg (_("file to delete"));
12406 gdb_argv argv (args);
12407 if (argv[0] == NULL || argv[1] != NULL)
12408 error (_("Invalid parameters to remote delete"));
12410 remote_file_delete (argv[0], from_tty);
12414 remote_command (const char *args, int from_tty)
12416 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
12420 remote_target::can_execute_reverse ()
12422 if (packet_support (PACKET_bs) == PACKET_ENABLE
12423 || packet_support (PACKET_bc) == PACKET_ENABLE)
12430 remote_target::supports_non_stop ()
12436 remote_target::supports_disable_randomization ()
12438 /* Only supported in extended mode. */
12443 remote_target::supports_multi_process ()
12445 struct remote_state *rs = get_remote_state ();
12447 return remote_multi_process_p (rs);
12451 remote_supports_cond_tracepoints ()
12453 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
12457 remote_target::supports_evaluation_of_breakpoint_conditions ()
12459 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
12463 remote_supports_fast_tracepoints ()
12465 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
12469 remote_supports_static_tracepoints ()
12471 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
12475 remote_supports_install_in_trace ()
12477 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
12481 remote_target::supports_enable_disable_tracepoint ()
12483 return (packet_support (PACKET_EnableDisableTracepoints_feature)
12488 remote_target::supports_string_tracing ()
12490 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
12494 remote_target::can_run_breakpoint_commands ()
12496 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
12500 remote_target::trace_init ()
12502 struct remote_state *rs = get_remote_state ();
12505 remote_get_noisy_reply ();
12506 if (strcmp (rs->buf, "OK") != 0)
12507 error (_("Target does not support this command."));
12510 /* Recursive routine to walk through command list including loops, and
12511 download packets for each command. */
12514 remote_download_command_source (int num, ULONGEST addr,
12515 struct command_line *cmds)
12517 struct remote_state *rs = get_remote_state ();
12518 struct command_line *cmd;
12520 for (cmd = cmds; cmd; cmd = cmd->next)
12522 QUIT; /* Allow user to bail out with ^C. */
12523 strcpy (rs->buf, "QTDPsrc:");
12524 encode_source_string (num, addr, "cmd", cmd->line,
12525 rs->buf + strlen (rs->buf),
12526 rs->buf_size - strlen (rs->buf));
12528 remote_get_noisy_reply ();
12529 if (strcmp (rs->buf, "OK"))
12530 warning (_("Target does not support source download."));
12532 if (cmd->control_type == while_control
12533 || cmd->control_type == while_stepping_control)
12535 remote_download_command_source (num, addr, *cmd->body_list);
12537 QUIT; /* Allow user to bail out with ^C. */
12538 strcpy (rs->buf, "QTDPsrc:");
12539 encode_source_string (num, addr, "cmd", "end",
12540 rs->buf + strlen (rs->buf),
12541 rs->buf_size - strlen (rs->buf));
12543 remote_get_noisy_reply ();
12544 if (strcmp (rs->buf, "OK"))
12545 warning (_("Target does not support source download."));
12551 remote_target::download_tracepoint (struct bp_location *loc)
12553 #define BUF_SIZE 2048
12557 char buf[BUF_SIZE];
12558 std::vector<std::string> tdp_actions;
12559 std::vector<std::string> stepping_actions;
12561 struct breakpoint *b = loc->owner;
12562 struct tracepoint *t = (struct tracepoint *) b;
12563 struct remote_state *rs = get_remote_state ();
12565 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
12567 tpaddr = loc->address;
12568 sprintf_vma (addrbuf, tpaddr);
12569 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
12570 addrbuf, /* address */
12571 (b->enable_state == bp_enabled ? 'E' : 'D'),
12572 t->step_count, t->pass_count);
12573 /* Fast tracepoints are mostly handled by the target, but we can
12574 tell the target how big of an instruction block should be moved
12576 if (b->type == bp_fast_tracepoint)
12578 /* Only test for support at download time; we may not know
12579 target capabilities at definition time. */
12580 if (remote_supports_fast_tracepoints ())
12582 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
12584 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
12585 gdb_insn_length (loc->gdbarch, tpaddr));
12587 /* If it passed validation at definition but fails now,
12588 something is very wrong. */
12589 internal_error (__FILE__, __LINE__,
12590 _("Fast tracepoint not "
12591 "valid during download"));
12594 /* Fast tracepoints are functionally identical to regular
12595 tracepoints, so don't take lack of support as a reason to
12596 give up on the trace run. */
12597 warning (_("Target does not support fast tracepoints, "
12598 "downloading %d as regular tracepoint"), b->number);
12600 else if (b->type == bp_static_tracepoint)
12602 /* Only test for support at download time; we may not know
12603 target capabilities at definition time. */
12604 if (remote_supports_static_tracepoints ())
12606 struct static_tracepoint_marker marker;
12608 if (target_static_tracepoint_marker_at (tpaddr, &marker))
12609 strcat (buf, ":S");
12611 error (_("Static tracepoint not valid during download"));
12614 /* Fast tracepoints are functionally identical to regular
12615 tracepoints, so don't take lack of support as a reason
12616 to give up on the trace run. */
12617 error (_("Target does not support static tracepoints"));
12619 /* If the tracepoint has a conditional, make it into an agent
12620 expression and append to the definition. */
12623 /* Only test support at download time, we may not know target
12624 capabilities at definition time. */
12625 if (remote_supports_cond_tracepoints ())
12627 agent_expr_up aexpr = gen_eval_for_expr (tpaddr, loc->cond.get ());
12628 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
12630 pkt = buf + strlen (buf);
12631 for (int ndx = 0; ndx < aexpr->len; ++ndx)
12632 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
12636 warning (_("Target does not support conditional tracepoints, "
12637 "ignoring tp %d cond"), b->number);
12640 if (b->commands || *default_collect)
12643 remote_get_noisy_reply ();
12644 if (strcmp (rs->buf, "OK"))
12645 error (_("Target does not support tracepoints."));
12647 /* do_single_steps (t); */
12648 for (auto action_it = tdp_actions.begin ();
12649 action_it != tdp_actions.end (); action_it++)
12651 QUIT; /* Allow user to bail out with ^C. */
12653 bool has_more = (action_it != tdp_actions.end ()
12654 || !stepping_actions.empty ());
12656 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
12657 b->number, addrbuf, /* address */
12658 action_it->c_str (),
12659 has_more ? '-' : 0);
12661 remote_get_noisy_reply ();
12662 if (strcmp (rs->buf, "OK"))
12663 error (_("Error on target while setting tracepoints."));
12666 for (auto action_it = stepping_actions.begin ();
12667 action_it != stepping_actions.end (); action_it++)
12669 QUIT; /* Allow user to bail out with ^C. */
12671 bool is_first = action_it == stepping_actions.begin ();
12672 bool has_more = action_it != stepping_actions.end ();
12674 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
12675 b->number, addrbuf, /* address */
12676 is_first ? "S" : "",
12677 action_it->c_str (),
12678 has_more ? "-" : "");
12680 remote_get_noisy_reply ();
12681 if (strcmp (rs->buf, "OK"))
12682 error (_("Error on target while setting tracepoints."));
12685 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
12687 if (b->location != NULL)
12689 strcpy (buf, "QTDPsrc:");
12690 encode_source_string (b->number, loc->address, "at",
12691 event_location_to_string (b->location.get ()),
12692 buf + strlen (buf), 2048 - strlen (buf));
12694 remote_get_noisy_reply ();
12695 if (strcmp (rs->buf, "OK"))
12696 warning (_("Target does not support source download."));
12698 if (b->cond_string)
12700 strcpy (buf, "QTDPsrc:");
12701 encode_source_string (b->number, loc->address,
12702 "cond", b->cond_string, buf + strlen (buf),
12703 2048 - strlen (buf));
12705 remote_get_noisy_reply ();
12706 if (strcmp (rs->buf, "OK"))
12707 warning (_("Target does not support source download."));
12709 remote_download_command_source (b->number, loc->address,
12710 breakpoint_commands (b));
12715 remote_target::can_download_tracepoint ()
12717 struct remote_state *rs = get_remote_state ();
12718 struct trace_status *ts;
12721 /* Don't try to install tracepoints until we've relocated our
12722 symbols, and fetched and merged the target's tracepoint list with
12724 if (rs->starting_up)
12727 ts = current_trace_status ();
12728 status = get_trace_status (ts);
12730 if (status == -1 || !ts->running_known || !ts->running)
12733 /* If we are in a tracing experiment, but remote stub doesn't support
12734 installing tracepoint in trace, we have to return. */
12735 if (!remote_supports_install_in_trace ())
12743 remote_target::download_trace_state_variable (const trace_state_variable &tsv)
12745 struct remote_state *rs = get_remote_state ();
12748 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
12749 tsv.number, phex ((ULONGEST) tsv.initial_value, 8),
12751 p = rs->buf + strlen (rs->buf);
12752 if ((p - rs->buf) + tsv.name.length () * 2 >= get_remote_packet_size ())
12753 error (_("Trace state variable name too long for tsv definition packet"));
12754 p += 2 * bin2hex ((gdb_byte *) (tsv.name.data ()), p, tsv.name.length ());
12757 remote_get_noisy_reply ();
12758 if (*rs->buf == '\0')
12759 error (_("Target does not support this command."));
12760 if (strcmp (rs->buf, "OK") != 0)
12761 error (_("Error on target while downloading trace state variable."));
12765 remote_target::enable_tracepoint (struct bp_location *location)
12767 struct remote_state *rs = get_remote_state ();
12770 sprintf_vma (addr_buf, location->address);
12771 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
12772 location->owner->number, addr_buf);
12774 remote_get_noisy_reply ();
12775 if (*rs->buf == '\0')
12776 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
12777 if (strcmp (rs->buf, "OK") != 0)
12778 error (_("Error on target while enabling tracepoint."));
12782 remote_target::disable_tracepoint (struct bp_location *location)
12784 struct remote_state *rs = get_remote_state ();
12787 sprintf_vma (addr_buf, location->address);
12788 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
12789 location->owner->number, addr_buf);
12791 remote_get_noisy_reply ();
12792 if (*rs->buf == '\0')
12793 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
12794 if (strcmp (rs->buf, "OK") != 0)
12795 error (_("Error on target while disabling tracepoint."));
12799 remote_target::trace_set_readonly_regions ()
12803 bfd_size_type size;
12809 return; /* No information to give. */
12811 struct remote_state *rs = get_remote_state ();
12813 strcpy (rs->buf, "QTro");
12814 offset = strlen (rs->buf);
12815 for (s = exec_bfd->sections; s; s = s->next)
12817 char tmp1[40], tmp2[40];
12820 if ((s->flags & SEC_LOAD) == 0 ||
12821 /* (s->flags & SEC_CODE) == 0 || */
12822 (s->flags & SEC_READONLY) == 0)
12826 vma = bfd_get_section_vma (abfd, s);
12827 size = bfd_get_section_size (s);
12828 sprintf_vma (tmp1, vma);
12829 sprintf_vma (tmp2, vma + size);
12830 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
12831 if (offset + sec_length + 1 > rs->buf_size)
12833 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
12835 Too many sections for read-only sections definition packet."));
12838 xsnprintf (rs->buf + offset, rs->buf_size - offset, ":%s,%s",
12840 offset += sec_length;
12845 getpkt (&rs->buf, &rs->buf_size, 0);
12850 remote_target::trace_start ()
12852 struct remote_state *rs = get_remote_state ();
12854 putpkt ("QTStart");
12855 remote_get_noisy_reply ();
12856 if (*rs->buf == '\0')
12857 error (_("Target does not support this command."));
12858 if (strcmp (rs->buf, "OK") != 0)
12859 error (_("Bogus reply from target: %s"), rs->buf);
12863 remote_target::get_trace_status (struct trace_status *ts)
12865 /* Initialize it just to avoid a GCC false warning. */
12867 /* FIXME we need to get register block size some other way. */
12868 extern int trace_regblock_size;
12869 enum packet_result result;
12870 struct remote_state *rs = get_remote_state ();
12872 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
12875 trace_regblock_size
12876 = get_remote_arch_state (target_gdbarch ())->sizeof_g_packet;
12878 putpkt ("qTStatus");
12882 p = remote_get_noisy_reply ();
12884 CATCH (ex, RETURN_MASK_ERROR)
12886 if (ex.error != TARGET_CLOSE_ERROR)
12888 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
12891 throw_exception (ex);
12895 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
12897 /* If the remote target doesn't do tracing, flag it. */
12898 if (result == PACKET_UNKNOWN)
12901 /* We're working with a live target. */
12902 ts->filename = NULL;
12905 error (_("Bogus trace status reply from target: %s"), rs->buf);
12907 /* Function 'parse_trace_status' sets default value of each field of
12908 'ts' at first, so we don't have to do it here. */
12909 parse_trace_status (p, ts);
12911 return ts->running;
12915 remote_target::get_tracepoint_status (struct breakpoint *bp,
12916 struct uploaded_tp *utp)
12918 struct remote_state *rs = get_remote_state ();
12920 struct bp_location *loc;
12921 struct tracepoint *tp = (struct tracepoint *) bp;
12922 size_t size = get_remote_packet_size ();
12927 tp->traceframe_usage = 0;
12928 for (loc = tp->loc; loc; loc = loc->next)
12930 /* If the tracepoint was never downloaded, don't go asking for
12932 if (tp->number_on_target == 0)
12934 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
12935 phex_nz (loc->address, 0));
12937 reply = remote_get_noisy_reply ();
12938 if (reply && *reply)
12941 parse_tracepoint_status (reply + 1, bp, utp);
12947 utp->hit_count = 0;
12948 utp->traceframe_usage = 0;
12949 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
12950 phex_nz (utp->addr, 0));
12952 reply = remote_get_noisy_reply ();
12953 if (reply && *reply)
12956 parse_tracepoint_status (reply + 1, bp, utp);
12962 remote_target::trace_stop ()
12964 struct remote_state *rs = get_remote_state ();
12967 remote_get_noisy_reply ();
12968 if (*rs->buf == '\0')
12969 error (_("Target does not support this command."));
12970 if (strcmp (rs->buf, "OK") != 0)
12971 error (_("Bogus reply from target: %s"), rs->buf);
12975 remote_target::trace_find (enum trace_find_type type, int num,
12976 CORE_ADDR addr1, CORE_ADDR addr2,
12979 struct remote_state *rs = get_remote_state ();
12980 char *endbuf = rs->buf + get_remote_packet_size ();
12982 int target_frameno = -1, target_tracept = -1;
12984 /* Lookups other than by absolute frame number depend on the current
12985 trace selected, so make sure it is correct on the remote end
12987 if (type != tfind_number)
12988 set_remote_traceframe ();
12991 strcpy (p, "QTFrame:");
12992 p = strchr (p, '\0');
12996 xsnprintf (p, endbuf - p, "%x", num);
12999 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
13002 xsnprintf (p, endbuf - p, "tdp:%x", num);
13005 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
13006 phex_nz (addr2, 0));
13008 case tfind_outside:
13009 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
13010 phex_nz (addr2, 0));
13013 error (_("Unknown trace find type %d"), type);
13017 reply = remote_get_noisy_reply ();
13018 if (*reply == '\0')
13019 error (_("Target does not support this command."));
13021 while (reply && *reply)
13026 target_frameno = (int) strtol (p, &reply, 16);
13028 error (_("Unable to parse trace frame number"));
13029 /* Don't update our remote traceframe number cache on failure
13030 to select a remote traceframe. */
13031 if (target_frameno == -1)
13036 target_tracept = (int) strtol (p, &reply, 16);
13038 error (_("Unable to parse tracepoint number"));
13040 case 'O': /* "OK"? */
13041 if (reply[1] == 'K' && reply[2] == '\0')
13044 error (_("Bogus reply from target: %s"), reply);
13047 error (_("Bogus reply from target: %s"), reply);
13050 *tpp = target_tracept;
13052 rs->remote_traceframe_number = target_frameno;
13053 return target_frameno;
13057 remote_target::get_trace_state_variable_value (int tsvnum, LONGEST *val)
13059 struct remote_state *rs = get_remote_state ();
13063 set_remote_traceframe ();
13065 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
13067 reply = remote_get_noisy_reply ();
13068 if (reply && *reply)
13072 unpack_varlen_hex (reply + 1, &uval);
13073 *val = (LONGEST) uval;
13081 remote_target::save_trace_data (const char *filename)
13083 struct remote_state *rs = get_remote_state ();
13087 strcpy (p, "QTSave:");
13089 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
13090 error (_("Remote file name too long for trace save packet"));
13091 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
13094 reply = remote_get_noisy_reply ();
13095 if (*reply == '\0')
13096 error (_("Target does not support this command."));
13097 if (strcmp (reply, "OK") != 0)
13098 error (_("Bogus reply from target: %s"), reply);
13102 /* This is basically a memory transfer, but needs to be its own packet
13103 because we don't know how the target actually organizes its trace
13104 memory, plus we want to be able to ask for as much as possible, but
13105 not be unhappy if we don't get as much as we ask for. */
13108 remote_target::get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
13110 struct remote_state *rs = get_remote_state ();
13116 strcpy (p, "qTBuffer:");
13118 p += hexnumstr (p, offset);
13120 p += hexnumstr (p, len);
13124 reply = remote_get_noisy_reply ();
13125 if (reply && *reply)
13127 /* 'l' by itself means we're at the end of the buffer and
13128 there is nothing more to get. */
13132 /* Convert the reply into binary. Limit the number of bytes to
13133 convert according to our passed-in buffer size, rather than
13134 what was returned in the packet; if the target is
13135 unexpectedly generous and gives us a bigger reply than we
13136 asked for, we don't want to crash. */
13137 rslt = hex2bin (reply, buf, len);
13141 /* Something went wrong, flag as an error. */
13146 remote_target::set_disconnected_tracing (int val)
13148 struct remote_state *rs = get_remote_state ();
13150 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
13154 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
13156 reply = remote_get_noisy_reply ();
13157 if (*reply == '\0')
13158 error (_("Target does not support this command."));
13159 if (strcmp (reply, "OK") != 0)
13160 error (_("Bogus reply from target: %s"), reply);
13163 warning (_("Target does not support disconnected tracing."));
13167 remote_target::core_of_thread (ptid_t ptid)
13169 struct thread_info *info = find_thread_ptid (ptid);
13171 if (info != NULL && info->priv != NULL)
13172 return get_remote_thread_info (info)->core;
13178 remote_target::set_circular_trace_buffer (int val)
13180 struct remote_state *rs = get_remote_state ();
13183 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
13185 reply = remote_get_noisy_reply ();
13186 if (*reply == '\0')
13187 error (_("Target does not support this command."));
13188 if (strcmp (reply, "OK") != 0)
13189 error (_("Bogus reply from target: %s"), reply);
13193 remote_target::traceframe_info ()
13195 gdb::optional<gdb::char_vector> text
13196 = target_read_stralloc (target_stack, TARGET_OBJECT_TRACEFRAME_INFO,
13199 return parse_traceframe_info (text->data ());
13204 /* Handle the qTMinFTPILen packet. Returns the minimum length of
13205 instruction on which a fast tracepoint may be placed. Returns -1
13206 if the packet is not supported, and 0 if the minimum instruction
13207 length is unknown. */
13210 remote_target::get_min_fast_tracepoint_insn_len ()
13212 struct remote_state *rs = get_remote_state ();
13215 /* If we're not debugging a process yet, the IPA can't be
13217 if (!target_has_execution)
13220 /* Make sure the remote is pointing at the right process. */
13221 set_general_process ();
13223 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
13225 reply = remote_get_noisy_reply ();
13226 if (*reply == '\0')
13230 ULONGEST min_insn_len;
13232 unpack_varlen_hex (reply, &min_insn_len);
13234 return (int) min_insn_len;
13239 remote_target::set_trace_buffer_size (LONGEST val)
13241 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
13243 struct remote_state *rs = get_remote_state ();
13244 char *buf = rs->buf;
13245 char *endbuf = rs->buf + get_remote_packet_size ();
13246 enum packet_result result;
13248 gdb_assert (val >= 0 || val == -1);
13249 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
13250 /* Send -1 as literal "-1" to avoid host size dependency. */
13254 buf += hexnumstr (buf, (ULONGEST) -val);
13257 buf += hexnumstr (buf, (ULONGEST) val);
13260 remote_get_noisy_reply ();
13261 result = packet_ok (rs->buf,
13262 &remote_protocol_packets[PACKET_QTBuffer_size]);
13264 if (result != PACKET_OK)
13265 warning (_("Bogus reply from target: %s"), rs->buf);
13270 remote_target::set_trace_notes (const char *user, const char *notes,
13271 const char *stop_notes)
13273 struct remote_state *rs = get_remote_state ();
13275 char *buf = rs->buf;
13276 char *endbuf = rs->buf + get_remote_packet_size ();
13279 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
13282 buf += xsnprintf (buf, endbuf - buf, "user:");
13283 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
13289 buf += xsnprintf (buf, endbuf - buf, "notes:");
13290 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
13296 buf += xsnprintf (buf, endbuf - buf, "tstop:");
13297 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
13301 /* Ensure the buffer is terminated. */
13305 reply = remote_get_noisy_reply ();
13306 if (*reply == '\0')
13309 if (strcmp (reply, "OK") != 0)
13310 error (_("Bogus reply from target: %s"), reply);
13316 remote_target::use_agent (int use)
13318 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
13320 struct remote_state *rs = get_remote_state ();
13322 /* If the stub supports QAgent. */
13323 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
13325 getpkt (&rs->buf, &rs->buf_size, 0);
13327 if (strcmp (rs->buf, "OK") == 0)
13338 remote_target::can_use_agent ()
13340 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
13343 struct btrace_target_info
13345 /* The ptid of the traced thread. */
13348 /* The obtained branch trace configuration. */
13349 struct btrace_config conf;
13352 /* Reset our idea of our target's btrace configuration. */
13355 remote_btrace_reset (void)
13357 struct remote_state *rs = get_remote_state ();
13359 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
13362 /* Synchronize the configuration with the target. */
13365 btrace_sync_conf (const struct btrace_config *conf)
13367 struct packet_config *packet;
13368 struct remote_state *rs;
13369 char *buf, *pos, *endbuf;
13371 rs = get_remote_state ();
13373 endbuf = buf + get_remote_packet_size ();
13375 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
13376 if (packet_config_support (packet) == PACKET_ENABLE
13377 && conf->bts.size != rs->btrace_config.bts.size)
13380 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13384 getpkt (&buf, &rs->buf_size, 0);
13386 if (packet_ok (buf, packet) == PACKET_ERROR)
13388 if (buf[0] == 'E' && buf[1] == '.')
13389 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
13391 error (_("Failed to configure the BTS buffer size."));
13394 rs->btrace_config.bts.size = conf->bts.size;
13397 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
13398 if (packet_config_support (packet) == PACKET_ENABLE
13399 && conf->pt.size != rs->btrace_config.pt.size)
13402 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13406 getpkt (&buf, &rs->buf_size, 0);
13408 if (packet_ok (buf, packet) == PACKET_ERROR)
13410 if (buf[0] == 'E' && buf[1] == '.')
13411 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
13413 error (_("Failed to configure the trace buffer size."));
13416 rs->btrace_config.pt.size = conf->pt.size;
13420 /* Read the current thread's btrace configuration from the target and
13421 store it into CONF. */
13424 btrace_read_config (struct btrace_config *conf)
13426 gdb::optional<gdb::char_vector> xml
13427 = target_read_stralloc (target_stack, TARGET_OBJECT_BTRACE_CONF, "");
13429 parse_xml_btrace_conf (conf, xml->data ());
13432 /* Maybe reopen target btrace. */
13435 remote_btrace_maybe_reopen (void)
13437 struct remote_state *rs = get_remote_state ();
13438 struct thread_info *tp;
13439 int btrace_target_pushed = 0;
13442 scoped_restore_current_thread restore_thread;
13444 ALL_NON_EXITED_THREADS (tp)
13446 set_general_thread (tp->ptid);
13448 memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
13449 btrace_read_config (&rs->btrace_config);
13451 if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
13454 #if !defined (HAVE_LIBIPT)
13455 if (rs->btrace_config.format == BTRACE_FORMAT_PT)
13460 warning (_("Target is recording using Intel Processor Trace "
13461 "but support was disabled at compile time."));
13466 #endif /* !defined (HAVE_LIBIPT) */
13468 /* Push target, once, but before anything else happens. This way our
13469 changes to the threads will be cleaned up by unpushing the target
13470 in case btrace_read_config () throws. */
13471 if (!btrace_target_pushed)
13473 btrace_target_pushed = 1;
13474 record_btrace_push_target ();
13475 printf_filtered (_("Target is recording using %s.\n"),
13476 btrace_format_string (rs->btrace_config.format));
13479 tp->btrace.target = XCNEW (struct btrace_target_info);
13480 tp->btrace.target->ptid = tp->ptid;
13481 tp->btrace.target->conf = rs->btrace_config;
13485 /* Enable branch tracing. */
13487 struct btrace_target_info *
13488 remote_target::enable_btrace (ptid_t ptid, const struct btrace_config *conf)
13490 struct btrace_target_info *tinfo = NULL;
13491 struct packet_config *packet = NULL;
13492 struct remote_state *rs = get_remote_state ();
13493 char *buf = rs->buf;
13494 char *endbuf = rs->buf + get_remote_packet_size ();
13496 switch (conf->format)
13498 case BTRACE_FORMAT_BTS:
13499 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
13502 case BTRACE_FORMAT_PT:
13503 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
13507 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
13508 error (_("Target does not support branch tracing."));
13510 btrace_sync_conf (conf);
13512 set_general_thread (ptid);
13514 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13516 getpkt (&rs->buf, &rs->buf_size, 0);
13518 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13520 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13521 error (_("Could not enable branch tracing for %s: %s"),
13522 target_pid_to_str (ptid), rs->buf + 2);
13524 error (_("Could not enable branch tracing for %s."),
13525 target_pid_to_str (ptid));
13528 tinfo = XCNEW (struct btrace_target_info);
13529 tinfo->ptid = ptid;
13531 /* If we fail to read the configuration, we lose some information, but the
13532 tracing itself is not impacted. */
13535 btrace_read_config (&tinfo->conf);
13537 CATCH (err, RETURN_MASK_ERROR)
13539 if (err.message != NULL)
13540 warning ("%s", err.message);
13547 /* Disable branch tracing. */
13550 remote_target::disable_btrace (struct btrace_target_info *tinfo)
13552 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
13553 struct remote_state *rs = get_remote_state ();
13554 char *buf = rs->buf;
13555 char *endbuf = rs->buf + get_remote_packet_size ();
13557 if (packet_config_support (packet) != PACKET_ENABLE)
13558 error (_("Target does not support branch tracing."));
13560 set_general_thread (tinfo->ptid);
13562 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13564 getpkt (&rs->buf, &rs->buf_size, 0);
13566 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13568 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13569 error (_("Could not disable branch tracing for %s: %s"),
13570 target_pid_to_str (tinfo->ptid), rs->buf + 2);
13572 error (_("Could not disable branch tracing for %s."),
13573 target_pid_to_str (tinfo->ptid));
13579 /* Teardown branch tracing. */
13582 remote_target::teardown_btrace (struct btrace_target_info *tinfo)
13584 /* We must not talk to the target during teardown. */
13588 /* Read the branch trace. */
13591 remote_target::read_btrace (struct btrace_data *btrace,
13592 struct btrace_target_info *tinfo,
13593 enum btrace_read_type type)
13595 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
13598 if (packet_config_support (packet) != PACKET_ENABLE)
13599 error (_("Target does not support branch tracing."));
13601 #if !defined(HAVE_LIBEXPAT)
13602 error (_("Cannot process branch tracing result. XML parsing not supported."));
13607 case BTRACE_READ_ALL:
13610 case BTRACE_READ_NEW:
13613 case BTRACE_READ_DELTA:
13617 internal_error (__FILE__, __LINE__,
13618 _("Bad branch tracing read type: %u."),
13619 (unsigned int) type);
13622 gdb::optional<gdb::char_vector> xml
13623 = target_read_stralloc (target_stack, TARGET_OBJECT_BTRACE, annex);
13625 return BTRACE_ERR_UNKNOWN;
13627 parse_xml_btrace (btrace, xml->data ());
13629 return BTRACE_ERR_NONE;
13632 const struct btrace_config *
13633 remote_target::btrace_conf (const struct btrace_target_info *tinfo)
13635 return &tinfo->conf;
13639 remote_target::augmented_libraries_svr4_read ()
13641 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
13645 /* Implementation of to_load. */
13648 remote_target::load (const char *name, int from_tty)
13650 generic_load (name, from_tty);
13653 /* Accepts an integer PID; returns a string representing a file that
13654 can be opened on the remote side to get the symbols for the child
13655 process. Returns NULL if the operation is not supported. */
13658 remote_target::pid_to_exec_file (int pid)
13660 static gdb::optional<gdb::char_vector> filename;
13661 struct inferior *inf;
13662 char *annex = NULL;
13664 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
13667 inf = find_inferior_pid (pid);
13669 internal_error (__FILE__, __LINE__,
13670 _("not currently attached to process %d"), pid);
13672 if (!inf->fake_pid_p)
13674 const int annex_size = 9;
13676 annex = (char *) alloca (annex_size);
13677 xsnprintf (annex, annex_size, "%x", pid);
13680 filename = target_read_stralloc (target_stack,
13681 TARGET_OBJECT_EXEC_FILE, annex);
13683 return filename ? filename->data () : nullptr;
13686 /* Implement the to_can_do_single_step target_ops method. */
13689 remote_target::can_do_single_step ()
13691 /* We can only tell whether target supports single step or not by
13692 supported s and S vCont actions if the stub supports vContSupported
13693 feature. If the stub doesn't support vContSupported feature,
13694 we have conservatively to think target doesn't supports single
13696 if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
13698 struct remote_state *rs = get_remote_state ();
13700 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
13701 remote_vcont_probe (rs);
13703 return rs->supports_vCont.s && rs->supports_vCont.S;
13709 /* Implementation of the to_execution_direction method for the remote
13712 enum exec_direction_kind
13713 remote_target::execution_direction ()
13715 struct remote_state *rs = get_remote_state ();
13717 return rs->last_resume_exec_dir;
13720 /* Return pointer to the thread_info struct which corresponds to
13721 THREAD_HANDLE (having length HANDLE_LEN). */
13724 remote_target::thread_handle_to_thread_info (const gdb_byte *thread_handle,
13728 struct thread_info *tp;
13730 ALL_NON_EXITED_THREADS (tp)
13732 remote_thread_info *priv = get_remote_thread_info (tp);
13734 if (tp->inf == inf && priv != NULL)
13736 if (handle_len != priv->thread_handle.size ())
13737 error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
13738 handle_len, priv->thread_handle.size ());
13739 if (memcmp (thread_handle, priv->thread_handle.data (),
13749 remote_target::can_async_p ()
13751 struct remote_state *rs = get_remote_state ();
13753 /* We don't go async if the user has explicitly prevented it with the
13754 "maint set target-async" command. */
13755 if (!target_async_permitted)
13758 /* We're async whenever the serial device is. */
13759 return serial_can_async_p (rs->remote_desc);
13763 remote_target::is_async_p ()
13765 struct remote_state *rs = get_remote_state ();
13767 if (!target_async_permitted)
13768 /* We only enable async when the user specifically asks for it. */
13771 /* We're async whenever the serial device is. */
13772 return serial_is_async_p (rs->remote_desc);
13775 /* Pass the SERIAL event on and up to the client. One day this code
13776 will be able to delay notifying the client of an event until the
13777 point where an entire packet has been received. */
13779 static serial_event_ftype remote_async_serial_handler;
13782 remote_async_serial_handler (struct serial *scb, void *context)
13784 /* Don't propogate error information up to the client. Instead let
13785 the client find out about the error by querying the target. */
13786 inferior_event_handler (INF_REG_EVENT, NULL);
13790 remote_async_inferior_event_handler (gdb_client_data data)
13792 inferior_event_handler (INF_REG_EVENT, NULL);
13796 remote_target::async (int enable)
13798 struct remote_state *rs = get_remote_state ();
13802 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
13804 /* If there are pending events in the stop reply queue tell the
13805 event loop to process them. */
13806 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
13807 mark_async_event_handler (remote_async_inferior_event_token);
13808 /* For simplicity, below we clear the pending events token
13809 without remembering whether it is marked, so here we always
13810 mark it. If there's actually no pending notification to
13811 process, this ends up being a no-op (other than a spurious
13812 event-loop wakeup). */
13813 if (target_is_non_stop_p ())
13814 mark_async_event_handler (rs->notif_state->get_pending_events_token);
13818 serial_async (rs->remote_desc, NULL, NULL);
13819 /* If the core is disabling async, it doesn't want to be
13820 disturbed with target events. Clear all async event sources
13822 clear_async_event_handler (remote_async_inferior_event_token);
13823 if (target_is_non_stop_p ())
13824 clear_async_event_handler (rs->notif_state->get_pending_events_token);
13828 /* Implementation of the to_thread_events method. */
13831 remote_target::thread_events (int enable)
13833 struct remote_state *rs = get_remote_state ();
13834 size_t size = get_remote_packet_size ();
13836 if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
13839 xsnprintf (rs->buf, size, "QThreadEvents:%x", enable ? 1 : 0);
13841 getpkt (&rs->buf, &rs->buf_size, 0);
13843 switch (packet_ok (rs->buf,
13844 &remote_protocol_packets[PACKET_QThreadEvents]))
13847 if (strcmp (rs->buf, "OK") != 0)
13848 error (_("Remote refused setting thread events: %s"), rs->buf);
13851 warning (_("Remote failure reply: %s"), rs->buf);
13853 case PACKET_UNKNOWN:
13859 set_remote_cmd (const char *args, int from_tty)
13861 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
13865 show_remote_cmd (const char *args, int from_tty)
13867 /* We can't just use cmd_show_list here, because we want to skip
13868 the redundant "show remote Z-packet" and the legacy aliases. */
13869 struct cmd_list_element *list = remote_show_cmdlist;
13870 struct ui_out *uiout = current_uiout;
13872 ui_out_emit_tuple tuple_emitter (uiout, "showlist");
13873 for (; list != NULL; list = list->next)
13874 if (strcmp (list->name, "Z-packet") == 0)
13876 else if (list->type == not_set_cmd)
13877 /* Alias commands are exactly like the original, except they
13878 don't have the normal type. */
13882 ui_out_emit_tuple option_emitter (uiout, "option");
13884 uiout->field_string ("name", list->name);
13885 uiout->text (": ");
13886 if (list->type == show_cmd)
13887 do_show_command (NULL, from_tty, list);
13889 cmd_func (list, NULL, from_tty);
13894 /* Function to be called whenever a new objfile (shlib) is detected. */
13896 remote_new_objfile (struct objfile *objfile)
13898 struct remote_state *rs = get_remote_state ();
13900 if (rs->remote_desc != 0) /* Have a remote connection. */
13901 remote_check_symbols ();
13904 /* Pull all the tracepoints defined on the target and create local
13905 data structures representing them. We don't want to create real
13906 tracepoints yet, we don't want to mess up the user's existing
13910 remote_target::upload_tracepoints (struct uploaded_tp **utpp)
13912 struct remote_state *rs = get_remote_state ();
13915 /* Ask for a first packet of tracepoint definition. */
13917 getpkt (&rs->buf, &rs->buf_size, 0);
13919 while (*p && *p != 'l')
13921 parse_tracepoint_definition (p, utpp);
13922 /* Ask for another packet of tracepoint definition. */
13924 getpkt (&rs->buf, &rs->buf_size, 0);
13931 remote_target::upload_trace_state_variables (struct uploaded_tsv **utsvp)
13933 struct remote_state *rs = get_remote_state ();
13936 /* Ask for a first packet of variable definition. */
13938 getpkt (&rs->buf, &rs->buf_size, 0);
13940 while (*p && *p != 'l')
13942 parse_tsv_definition (p, utsvp);
13943 /* Ask for another packet of variable definition. */
13945 getpkt (&rs->buf, &rs->buf_size, 0);
13951 /* The "set/show range-stepping" show hook. */
13954 show_range_stepping (struct ui_file *file, int from_tty,
13955 struct cmd_list_element *c,
13958 fprintf_filtered (file,
13959 _("Debugger's willingness to use range stepping "
13960 "is %s.\n"), value);
13963 /* The "set/show range-stepping" set hook. */
13966 set_range_stepping (const char *ignore_args, int from_tty,
13967 struct cmd_list_element *c)
13969 struct remote_state *rs = get_remote_state ();
13971 /* Whene enabling, check whether range stepping is actually
13972 supported by the target, and warn if not. */
13973 if (use_range_stepping)
13975 if (rs->remote_desc != NULL)
13977 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
13978 remote_vcont_probe (rs);
13980 if (packet_support (PACKET_vCont) == PACKET_ENABLE
13981 && rs->supports_vCont.r)
13985 warning (_("Range stepping is not supported by the current target"));
13990 _initialize_remote (void)
13992 struct cmd_list_element *cmd;
13993 const char *cmd_name;
13995 /* architecture specific data */
13996 remote_gdbarch_data_handle =
13997 gdbarch_data_register_post_init (init_remote_state);
13998 remote_g_packet_data_handle =
13999 gdbarch_data_register_pre_init (remote_g_packet_data_init);
14002 = register_program_space_data_with_cleanup (NULL,
14003 remote_pspace_data_cleanup);
14005 /* Initialize the per-target state. At the moment there is only one
14006 of these, not one per target. Only one target is active at a
14008 remote_state = new_remote_state ();
14010 add_target (&remote_ops);
14011 add_target (&extended_remote_ops);
14013 /* Hook into new objfile notification. */
14014 gdb::observers::new_objfile.attach (remote_new_objfile);
14015 /* We're no longer interested in notification events of an inferior
14017 gdb::observers::inferior_exit.attach (discard_pending_stop_replies);
14020 init_remote_threadtests ();
14023 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
14024 /* set/show remote ... */
14026 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
14027 Remote protocol specific variables\n\
14028 Configure various remote-protocol specific variables such as\n\
14029 the packets being used"),
14030 &remote_set_cmdlist, "set remote ",
14031 0 /* allow-unknown */, &setlist);
14032 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
14033 Remote protocol specific variables\n\
14034 Configure various remote-protocol specific variables such as\n\
14035 the packets being used"),
14036 &remote_show_cmdlist, "show remote ",
14037 0 /* allow-unknown */, &showlist);
14039 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
14040 Compare section data on target to the exec file.\n\
14041 Argument is a single section name (default: all loaded sections).\n\
14042 To compare only read-only loaded sections, specify the -r option."),
14045 add_cmd ("packet", class_maintenance, packet_command, _("\
14046 Send an arbitrary packet to a remote target.\n\
14047 maintenance packet TEXT\n\
14048 If GDB is talking to an inferior via the GDB serial protocol, then\n\
14049 this command sends the string TEXT to the inferior, and displays the\n\
14050 response packet. GDB supplies the initial `$' character, and the\n\
14051 terminating `#' character and checksum."),
14054 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
14055 Set whether to send break if interrupted."), _("\
14056 Show whether to send break if interrupted."), _("\
14057 If set, a break, instead of a cntrl-c, is sent to the remote target."),
14058 set_remotebreak, show_remotebreak,
14059 &setlist, &showlist);
14060 cmd_name = "remotebreak";
14061 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
14062 deprecate_cmd (cmd, "set remote interrupt-sequence");
14063 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
14064 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
14065 deprecate_cmd (cmd, "show remote interrupt-sequence");
14067 add_setshow_enum_cmd ("interrupt-sequence", class_support,
14068 interrupt_sequence_modes, &interrupt_sequence_mode,
14070 Set interrupt sequence to remote target."), _("\
14071 Show interrupt sequence to remote target."), _("\
14072 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
14073 NULL, show_interrupt_sequence,
14074 &remote_set_cmdlist,
14075 &remote_show_cmdlist);
14077 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
14078 &interrupt_on_connect, _("\
14079 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
14080 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
14081 If set, interrupt sequence is sent to remote target."),
14083 &remote_set_cmdlist, &remote_show_cmdlist);
14085 /* Install commands for configuring memory read/write packets. */
14087 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
14088 Set the maximum number of bytes per memory write packet (deprecated)."),
14090 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
14091 Show the maximum number of bytes per memory write packet (deprecated)."),
14093 add_cmd ("memory-write-packet-size", no_class,
14094 set_memory_write_packet_size, _("\
14095 Set the maximum number of bytes per memory-write packet.\n\
14096 Specify the number of bytes in a packet or 0 (zero) for the\n\
14097 default packet size. The actual limit is further reduced\n\
14098 dependent on the target. Specify ``fixed'' to disable the\n\
14099 further restriction and ``limit'' to enable that restriction."),
14100 &remote_set_cmdlist);
14101 add_cmd ("memory-read-packet-size", no_class,
14102 set_memory_read_packet_size, _("\
14103 Set the maximum number of bytes per memory-read packet.\n\
14104 Specify the number of bytes in a packet or 0 (zero) for the\n\
14105 default packet size. The actual limit is further reduced\n\
14106 dependent on the target. Specify ``fixed'' to disable the\n\
14107 further restriction and ``limit'' to enable that restriction."),
14108 &remote_set_cmdlist);
14109 add_cmd ("memory-write-packet-size", no_class,
14110 show_memory_write_packet_size,
14111 _("Show the maximum number of bytes per memory-write packet."),
14112 &remote_show_cmdlist);
14113 add_cmd ("memory-read-packet-size", no_class,
14114 show_memory_read_packet_size,
14115 _("Show the maximum number of bytes per memory-read packet."),
14116 &remote_show_cmdlist);
14118 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
14119 &remote_hw_watchpoint_limit, _("\
14120 Set the maximum number of target hardware watchpoints."), _("\
14121 Show the maximum number of target hardware watchpoints."), _("\
14122 Specify a negative limit for unlimited."),
14123 NULL, NULL, /* FIXME: i18n: The maximum
14124 number of target hardware
14125 watchpoints is %s. */
14126 &remote_set_cmdlist, &remote_show_cmdlist);
14127 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
14128 &remote_hw_watchpoint_length_limit, _("\
14129 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
14130 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
14131 Specify a negative limit for unlimited."),
14132 NULL, NULL, /* FIXME: i18n: The maximum
14133 length (in bytes) of a target
14134 hardware watchpoint is %s. */
14135 &remote_set_cmdlist, &remote_show_cmdlist);
14136 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
14137 &remote_hw_breakpoint_limit, _("\
14138 Set the maximum number of target hardware breakpoints."), _("\
14139 Show the maximum number of target hardware breakpoints."), _("\
14140 Specify a negative limit for unlimited."),
14141 NULL, NULL, /* FIXME: i18n: The maximum
14142 number of target hardware
14143 breakpoints is %s. */
14144 &remote_set_cmdlist, &remote_show_cmdlist);
14146 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
14147 &remote_address_size, _("\
14148 Set the maximum size of the address (in bits) in a memory packet."), _("\
14149 Show the maximum size of the address (in bits) in a memory packet."), NULL,
14151 NULL, /* FIXME: i18n: */
14152 &setlist, &showlist);
14154 init_all_packet_configs ();
14156 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
14157 "X", "binary-download", 1);
14159 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
14160 "vCont", "verbose-resume", 0);
14162 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
14163 "QPassSignals", "pass-signals", 0);
14165 add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
14166 "QCatchSyscalls", "catch-syscalls", 0);
14168 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
14169 "QProgramSignals", "program-signals", 0);
14171 add_packet_config_cmd (&remote_protocol_packets[PACKET_QSetWorkingDir],
14172 "QSetWorkingDir", "set-working-dir", 0);
14174 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartupWithShell],
14175 "QStartupWithShell", "startup-with-shell", 0);
14177 add_packet_config_cmd (&remote_protocol_packets
14178 [PACKET_QEnvironmentHexEncoded],
14179 "QEnvironmentHexEncoded", "environment-hex-encoded",
14182 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentReset],
14183 "QEnvironmentReset", "environment-reset",
14186 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentUnset],
14187 "QEnvironmentUnset", "environment-unset",
14190 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
14191 "qSymbol", "symbol-lookup", 0);
14193 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
14194 "P", "set-register", 1);
14196 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
14197 "p", "fetch-register", 1);
14199 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
14200 "Z0", "software-breakpoint", 0);
14202 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
14203 "Z1", "hardware-breakpoint", 0);
14205 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
14206 "Z2", "write-watchpoint", 0);
14208 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
14209 "Z3", "read-watchpoint", 0);
14211 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
14212 "Z4", "access-watchpoint", 0);
14214 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
14215 "qXfer:auxv:read", "read-aux-vector", 0);
14217 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
14218 "qXfer:exec-file:read", "pid-to-exec-file", 0);
14220 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
14221 "qXfer:features:read", "target-features", 0);
14223 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
14224 "qXfer:libraries:read", "library-info", 0);
14226 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
14227 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
14229 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
14230 "qXfer:memory-map:read", "memory-map", 0);
14232 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
14233 "qXfer:spu:read", "read-spu-object", 0);
14235 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
14236 "qXfer:spu:write", "write-spu-object", 0);
14238 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
14239 "qXfer:osdata:read", "osdata", 0);
14241 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
14242 "qXfer:threads:read", "threads", 0);
14244 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
14245 "qXfer:siginfo:read", "read-siginfo-object", 0);
14247 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
14248 "qXfer:siginfo:write", "write-siginfo-object", 0);
14250 add_packet_config_cmd
14251 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
14252 "qXfer:traceframe-info:read", "traceframe-info", 0);
14254 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
14255 "qXfer:uib:read", "unwind-info-block", 0);
14257 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
14258 "qGetTLSAddr", "get-thread-local-storage-address",
14261 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
14262 "qGetTIBAddr", "get-thread-information-block-address",
14265 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
14266 "bc", "reverse-continue", 0);
14268 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
14269 "bs", "reverse-step", 0);
14271 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
14272 "qSupported", "supported-packets", 0);
14274 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
14275 "qSearch:memory", "search-memory", 0);
14277 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
14278 "qTStatus", "trace-status", 0);
14280 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
14281 "vFile:setfs", "hostio-setfs", 0);
14283 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
14284 "vFile:open", "hostio-open", 0);
14286 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
14287 "vFile:pread", "hostio-pread", 0);
14289 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
14290 "vFile:pwrite", "hostio-pwrite", 0);
14292 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
14293 "vFile:close", "hostio-close", 0);
14295 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
14296 "vFile:unlink", "hostio-unlink", 0);
14298 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
14299 "vFile:readlink", "hostio-readlink", 0);
14301 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
14302 "vFile:fstat", "hostio-fstat", 0);
14304 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
14305 "vAttach", "attach", 0);
14307 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
14310 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
14311 "QStartNoAckMode", "noack", 0);
14313 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
14314 "vKill", "kill", 0);
14316 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
14317 "qAttached", "query-attached", 0);
14319 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
14320 "ConditionalTracepoints",
14321 "conditional-tracepoints", 0);
14323 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
14324 "ConditionalBreakpoints",
14325 "conditional-breakpoints", 0);
14327 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
14328 "BreakpointCommands",
14329 "breakpoint-commands", 0);
14331 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
14332 "FastTracepoints", "fast-tracepoints", 0);
14334 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
14335 "TracepointSource", "TracepointSource", 0);
14337 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
14338 "QAllow", "allow", 0);
14340 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
14341 "StaticTracepoints", "static-tracepoints", 0);
14343 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
14344 "InstallInTrace", "install-in-trace", 0);
14346 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
14347 "qXfer:statictrace:read", "read-sdata-object", 0);
14349 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
14350 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
14352 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
14353 "QDisableRandomization", "disable-randomization", 0);
14355 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
14356 "QAgent", "agent", 0);
14358 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
14359 "QTBuffer:size", "trace-buffer-size", 0);
14361 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
14362 "Qbtrace:off", "disable-btrace", 0);
14364 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
14365 "Qbtrace:bts", "enable-btrace-bts", 0);
14367 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
14368 "Qbtrace:pt", "enable-btrace-pt", 0);
14370 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
14371 "qXfer:btrace", "read-btrace", 0);
14373 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
14374 "qXfer:btrace-conf", "read-btrace-conf", 0);
14376 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
14377 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
14379 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
14380 "multiprocess-feature", "multiprocess-feature", 0);
14382 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
14383 "swbreak-feature", "swbreak-feature", 0);
14385 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
14386 "hwbreak-feature", "hwbreak-feature", 0);
14388 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
14389 "fork-event-feature", "fork-event-feature", 0);
14391 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
14392 "vfork-event-feature", "vfork-event-feature", 0);
14394 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
14395 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
14397 add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
14398 "vContSupported", "verbose-resume-supported", 0);
14400 add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
14401 "exec-event-feature", "exec-event-feature", 0);
14403 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
14404 "vCtrlC", "ctrl-c", 0);
14406 add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
14407 "QThreadEvents", "thread-events", 0);
14409 add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
14410 "N stop reply", "no-resumed-stop-reply", 0);
14412 /* Assert that we've registered "set remote foo-packet" commands
14413 for all packet configs. */
14417 for (i = 0; i < PACKET_MAX; i++)
14419 /* Ideally all configs would have a command associated. Some
14420 still don't though. */
14425 case PACKET_QNonStop:
14426 case PACKET_EnableDisableTracepoints_feature:
14427 case PACKET_tracenz_feature:
14428 case PACKET_DisconnectedTracing_feature:
14429 case PACKET_augmented_libraries_svr4_read_feature:
14431 /* Additions to this list need to be well justified:
14432 pre-existing packets are OK; new packets are not. */
14440 /* This catches both forgetting to add a config command, and
14441 forgetting to remove a packet from the exception list. */
14442 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
14446 /* Keep the old ``set remote Z-packet ...'' working. Each individual
14447 Z sub-packet has its own set and show commands, but users may
14448 have sets to this variable in their .gdbinit files (or in their
14450 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
14451 &remote_Z_packet_detect, _("\
14452 Set use of remote protocol `Z' packets"), _("\
14453 Show use of remote protocol `Z' packets "), _("\
14454 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
14456 set_remote_protocol_Z_packet_cmd,
14457 show_remote_protocol_Z_packet_cmd,
14458 /* FIXME: i18n: Use of remote protocol
14459 `Z' packets is %s. */
14460 &remote_set_cmdlist, &remote_show_cmdlist);
14462 add_prefix_cmd ("remote", class_files, remote_command, _("\
14463 Manipulate files on the remote system\n\
14464 Transfer files to and from the remote target system."),
14465 &remote_cmdlist, "remote ",
14466 0 /* allow-unknown */, &cmdlist);
14468 add_cmd ("put", class_files, remote_put_command,
14469 _("Copy a local file to the remote system."),
14472 add_cmd ("get", class_files, remote_get_command,
14473 _("Copy a remote file to the local system."),
14476 add_cmd ("delete", class_files, remote_delete_command,
14477 _("Delete a remote file."),
14480 add_setshow_string_noescape_cmd ("exec-file", class_files,
14481 &remote_exec_file_var, _("\
14482 Set the remote pathname for \"run\""), _("\
14483 Show the remote pathname for \"run\""), NULL,
14484 set_remote_exec_file,
14485 show_remote_exec_file,
14486 &remote_set_cmdlist,
14487 &remote_show_cmdlist);
14489 add_setshow_boolean_cmd ("range-stepping", class_run,
14490 &use_range_stepping, _("\
14491 Enable or disable range stepping."), _("\
14492 Show whether target-assisted range stepping is enabled."), _("\
14493 If on, and the target supports it, when stepping a source line, GDB\n\
14494 tells the target to step the corresponding range of addresses itself instead\n\
14495 of issuing multiple single-steps. This speeds up source level\n\
14496 stepping. If off, GDB always issues single-steps, even if range\n\
14497 stepping is supported by the target. The default is on."),
14498 set_range_stepping,
14499 show_range_stepping,
14503 /* Eventually initialize fileio. See fileio.c */
14504 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
14506 /* Take advantage of the fact that the TID field is not used, to tag
14507 special ptids with it set to != 0. */
14508 magic_null_ptid = ptid_build (42000, -1, 1);
14509 not_sent_ptid = ptid_build (42000, -2, 1);
14510 any_thread_ptid = ptid_build (42000, 0, 1);