Fix snafu in version number. Regenerate files
[binutils-gdb.git] / gdb / remote.c
blobea968ee0c59ae6c3e561e31e7296ef23f7c40345
1 /* Remote target communications for serial-line targets in custom GDB protocol
3 Copyright (C) 1988-2022 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. */
22 #include "defs.h"
23 #include <ctype.h>
24 #include <fcntl.h>
25 #include "inferior.h"
26 #include "infrun.h"
27 #include "bfd.h"
28 #include "symfile.h"
29 #include "target.h"
30 #include "process-stratum-target.h"
31 #include "gdbcmd.h"
32 #include "objfiles.h"
33 #include "gdb-stabs.h"
34 #include "gdbthread.h"
35 #include "remote.h"
36 #include "remote-notif.h"
37 #include "regcache.h"
38 #include "value.h"
39 #include "observable.h"
40 #include "solib.h"
41 #include "cli/cli-decode.h"
42 #include "cli/cli-setshow.h"
43 #include "target-descriptions.h"
44 #include "gdb_bfd.h"
45 #include "gdbsupport/filestuff.h"
46 #include "gdbsupport/rsp-low.h"
47 #include "disasm.h"
48 #include "location.h"
50 #include "gdbsupport/gdb_sys_time.h"
52 #include "gdbsupport/event-loop.h"
53 #include "event-top.h"
54 #include "inf-loop.h"
56 #include <signal.h>
57 #include "serial.h"
59 #include "gdbcore.h"
61 #include "remote-fileio.h"
62 #include "gdbsupport/fileio.h"
63 #include <sys/stat.h>
64 #include "xml-support.h"
66 #include "memory-map.h"
68 #include "tracepoint.h"
69 #include "ax.h"
70 #include "ax-gdb.h"
71 #include "gdbsupport/agent.h"
72 #include "btrace.h"
73 #include "record-btrace.h"
74 #include <algorithm>
75 #include "gdbsupport/scoped_restore.h"
76 #include "gdbsupport/environ.h"
77 #include "gdbsupport/byte-vector.h"
78 #include "gdbsupport/search.h"
79 #include <algorithm>
80 #include <unordered_map>
81 #include "async-event.h"
82 #include "gdbsupport/selftest.h"
84 /* The remote target. */
86 static const char remote_doc[] = N_("\
87 Use a remote computer via a serial line, using a gdb-specific protocol.\n\
88 Specify the serial device it is connected to\n\
89 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).");
91 /* See remote.h */
93 bool remote_debug = false;
95 #define OPAQUETHREADBYTES 8
97 /* a 64 bit opaque identifier */
98 typedef unsigned char threadref[OPAQUETHREADBYTES];
100 struct gdb_ext_thread_info;
101 struct threads_listing_context;
102 typedef int (*rmt_thread_action) (threadref *ref, void *context);
103 struct protocol_feature;
104 struct packet_reg;
106 struct stop_reply;
107 typedef std::unique_ptr<stop_reply> stop_reply_up;
109 /* Generic configuration support for packets the stub optionally
110 supports. Allows the user to specify the use of the packet as well
111 as allowing GDB to auto-detect support in the remote stub. */
113 enum packet_support
115 PACKET_SUPPORT_UNKNOWN = 0,
116 PACKET_ENABLE,
117 PACKET_DISABLE
120 /* Analyze a packet's return value and update the packet config
121 accordingly. */
123 enum packet_result
125 PACKET_ERROR,
126 PACKET_OK,
127 PACKET_UNKNOWN
130 struct threads_listing_context;
132 /* Stub vCont actions support.
134 Each field is a boolean flag indicating whether the stub reports
135 support for the corresponding action. */
137 struct vCont_action_support
139 /* vCont;t */
140 bool t = false;
142 /* vCont;r */
143 bool r = false;
145 /* vCont;s */
146 bool s = false;
148 /* vCont;S */
149 bool S = false;
152 /* About this many threadids fit in a packet. */
154 #define MAXTHREADLISTRESULTS 32
156 /* Data for the vFile:pread readahead cache. */
158 struct readahead_cache
160 /* Invalidate the readahead cache. */
161 void invalidate ();
163 /* Invalidate the readahead cache if it is holding data for FD. */
164 void invalidate_fd (int fd);
166 /* Serve pread from the readahead cache. Returns number of bytes
167 read, or 0 if the request can't be served from the cache. */
168 int pread (int fd, gdb_byte *read_buf, size_t len, ULONGEST offset);
170 /* The file descriptor for the file that is being cached. -1 if the
171 cache is invalid. */
172 int fd = -1;
174 /* The offset into the file that the cache buffer corresponds
175 to. */
176 ULONGEST offset = 0;
178 /* The buffer holding the cache contents. */
179 gdb_byte *buf = nullptr;
180 /* The buffer's size. We try to read as much as fits into a packet
181 at a time. */
182 size_t bufsize = 0;
184 /* Cache hit and miss counters. */
185 ULONGEST hit_count = 0;
186 ULONGEST miss_count = 0;
189 /* Description of the remote protocol for a given architecture. */
191 struct packet_reg
193 long offset; /* Offset into G packet. */
194 long regnum; /* GDB's internal register number. */
195 LONGEST pnum; /* Remote protocol register number. */
196 int in_g_packet; /* Always part of G packet. */
197 /* long size in bytes; == register_size (target_gdbarch (), regnum);
198 at present. */
199 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
200 at present. */
203 struct remote_arch_state
205 explicit remote_arch_state (struct gdbarch *gdbarch);
207 /* Description of the remote protocol registers. */
208 long sizeof_g_packet;
210 /* Description of the remote protocol registers indexed by REGNUM
211 (making an array gdbarch_num_regs in size). */
212 std::unique_ptr<packet_reg[]> regs;
214 /* This is the size (in chars) of the first response to the ``g''
215 packet. It is used as a heuristic when determining the maximum
216 size of memory-read and memory-write packets. A target will
217 typically only reserve a buffer large enough to hold the ``g''
218 packet. The size does not include packet overhead (headers and
219 trailers). */
220 long actual_register_packet_size;
222 /* This is the maximum size (in chars) of a non read/write packet.
223 It is also used as a cap on the size of read/write packets. */
224 long remote_packet_size;
227 /* Description of the remote protocol state for the currently
228 connected target. This is per-target state, and independent of the
229 selected architecture. */
231 class remote_state
233 public:
235 remote_state ();
236 ~remote_state ();
238 /* Get the remote arch state for GDBARCH. */
239 struct remote_arch_state *get_remote_arch_state (struct gdbarch *gdbarch);
241 public: /* data */
243 /* A buffer to use for incoming packets, and its current size. The
244 buffer is grown dynamically for larger incoming packets.
245 Outgoing packets may also be constructed in this buffer.
246 The size of the buffer is always at least REMOTE_PACKET_SIZE;
247 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
248 packets. */
249 gdb::char_vector buf;
251 /* True if we're going through initial connection setup (finding out
252 about the remote side's threads, relocating symbols, etc.). */
253 bool starting_up = false;
255 /* If we negotiated packet size explicitly (and thus can bypass
256 heuristics for the largest packet size that will not overflow
257 a buffer in the stub), this will be set to that packet size.
258 Otherwise zero, meaning to use the guessed size. */
259 long explicit_packet_size = 0;
261 /* True, if in no ack mode. That is, neither GDB nor the stub will
262 expect acks from each other. The connection is assumed to be
263 reliable. */
264 bool noack_mode = false;
266 /* True if we're connected in extended remote mode. */
267 bool extended = false;
269 /* True if we resumed the target and we're waiting for the target to
270 stop. In the mean time, we can't start another command/query.
271 The remote server wouldn't be ready to process it, so we'd
272 timeout waiting for a reply that would never come and eventually
273 we'd close the connection. This can happen in asynchronous mode
274 because we allow GDB commands while the target is running. */
275 bool waiting_for_stop_reply = false;
277 /* The status of the stub support for the various vCont actions. */
278 vCont_action_support supports_vCont;
279 /* Whether vCont support was probed already. This is a workaround
280 until packet_support is per-connection. */
281 bool supports_vCont_probed;
283 /* True if the user has pressed Ctrl-C, but the target hasn't
284 responded to that. */
285 bool ctrlc_pending_p = false;
287 /* True if we saw a Ctrl-C while reading or writing from/to the
288 remote descriptor. At that point it is not safe to send a remote
289 interrupt packet, so we instead remember we saw the Ctrl-C and
290 process it once we're done with sending/receiving the current
291 packet, which should be shortly. If however that takes too long,
292 and the user presses Ctrl-C again, we offer to disconnect. */
293 bool got_ctrlc_during_io = false;
295 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
296 remote_open knows that we don't have a file open when the program
297 starts. */
298 struct serial *remote_desc = nullptr;
300 /* These are the threads which we last sent to the remote system. The
301 TID member will be -1 for all or -2 for not sent yet. */
302 ptid_t general_thread = null_ptid;
303 ptid_t continue_thread = null_ptid;
305 /* This is the traceframe which we last selected on the remote system.
306 It will be -1 if no traceframe is selected. */
307 int remote_traceframe_number = -1;
309 char *last_pass_packet = nullptr;
311 /* The last QProgramSignals packet sent to the target. We bypass
312 sending a new program signals list down to the target if the new
313 packet is exactly the same as the last we sent. IOW, we only let
314 the target know about program signals list changes. */
315 char *last_program_signals_packet = nullptr;
317 gdb_signal last_sent_signal = GDB_SIGNAL_0;
319 bool last_sent_step = false;
321 /* The execution direction of the last resume we got. */
322 exec_direction_kind last_resume_exec_dir = EXEC_FORWARD;
324 char *finished_object = nullptr;
325 char *finished_annex = nullptr;
326 ULONGEST finished_offset = 0;
328 /* Should we try the 'ThreadInfo' query packet?
330 This variable (NOT available to the user: auto-detect only!)
331 determines whether GDB will use the new, simpler "ThreadInfo"
332 query or the older, more complex syntax for thread queries.
333 This is an auto-detect variable (set to true at each connect,
334 and set to false when the target fails to recognize it). */
335 bool use_threadinfo_query = false;
336 bool use_threadextra_query = false;
338 threadref echo_nextthread {};
339 threadref nextthread {};
340 threadref resultthreadlist[MAXTHREADLISTRESULTS] {};
342 /* The state of remote notification. */
343 struct remote_notif_state *notif_state = nullptr;
345 /* The branch trace configuration. */
346 struct btrace_config btrace_config {};
348 /* The argument to the last "vFile:setfs:" packet we sent, used
349 to avoid sending repeated unnecessary "vFile:setfs:" packets.
350 Initialized to -1 to indicate that no "vFile:setfs:" packet
351 has yet been sent. */
352 int fs_pid = -1;
354 /* A readahead cache for vFile:pread. Often, reading a binary
355 involves a sequence of small reads. E.g., when parsing an ELF
356 file. A readahead cache helps mostly the case of remote
357 debugging on a connection with higher latency, due to the
358 request/reply nature of the RSP. We only cache data for a single
359 file descriptor at a time. */
360 struct readahead_cache readahead_cache;
362 /* The list of already fetched and acknowledged stop events. This
363 queue is used for notification Stop, and other notifications
364 don't need queue for their events, because the notification
365 events of Stop can't be consumed immediately, so that events
366 should be queued first, and be consumed by remote_wait_{ns,as}
367 one per time. Other notifications can consume their events
368 immediately, so queue is not needed for them. */
369 std::vector<stop_reply_up> stop_reply_queue;
371 /* Asynchronous signal handle registered as event loop source for
372 when we have pending events ready to be passed to the core. */
373 struct async_event_handler *remote_async_inferior_event_token = nullptr;
375 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
376 ``forever'' still use the normal timeout mechanism. This is
377 currently used by the ASYNC code to guarentee that target reads
378 during the initial connect always time-out. Once getpkt has been
379 modified to return a timeout indication and, in turn
380 remote_wait()/wait_for_inferior() have gained a timeout parameter
381 this can go away. */
382 int wait_forever_enabled_p = 1;
384 private:
385 /* Mapping of remote protocol data for each gdbarch. Usually there
386 is only one entry here, though we may see more with stubs that
387 support multi-process. */
388 std::unordered_map<struct gdbarch *, remote_arch_state>
389 m_arch_states;
392 static const target_info remote_target_info = {
393 "remote",
394 N_("Remote target using gdb-specific protocol"),
395 remote_doc
398 class remote_target : public process_stratum_target
400 public:
401 remote_target () = default;
402 ~remote_target () override;
404 const target_info &info () const override
405 { return remote_target_info; }
407 const char *connection_string () override;
409 thread_control_capabilities get_thread_control_capabilities () override
410 { return tc_schedlock; }
412 /* Open a remote connection. */
413 static void open (const char *, int);
415 void close () override;
417 void detach (inferior *, int) override;
418 void disconnect (const char *, int) override;
420 void commit_resumed () override;
421 void resume (ptid_t, int, enum gdb_signal) override;
422 ptid_t wait (ptid_t, struct target_waitstatus *, target_wait_flags) override;
423 bool has_pending_events () override;
425 void fetch_registers (struct regcache *, int) override;
426 void store_registers (struct regcache *, int) override;
427 void prepare_to_store (struct regcache *) override;
429 int insert_breakpoint (struct gdbarch *, struct bp_target_info *) override;
431 int remove_breakpoint (struct gdbarch *, struct bp_target_info *,
432 enum remove_bp_reason) override;
435 bool stopped_by_sw_breakpoint () override;
436 bool supports_stopped_by_sw_breakpoint () override;
438 bool stopped_by_hw_breakpoint () override;
440 bool supports_stopped_by_hw_breakpoint () override;
442 bool stopped_by_watchpoint () override;
444 bool stopped_data_address (CORE_ADDR *) override;
446 bool watchpoint_addr_within_range (CORE_ADDR, CORE_ADDR, int) override;
448 int can_use_hw_breakpoint (enum bptype, int, int) override;
450 int insert_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
452 int remove_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
454 int region_ok_for_hw_watchpoint (CORE_ADDR, int) override;
456 int insert_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
457 struct expression *) override;
459 int remove_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
460 struct expression *) override;
462 void kill () override;
464 void load (const char *, int) override;
466 void mourn_inferior () override;
468 void pass_signals (gdb::array_view<const unsigned char>) override;
470 int set_syscall_catchpoint (int, bool, int,
471 gdb::array_view<const int>) override;
473 void program_signals (gdb::array_view<const unsigned char>) override;
475 bool thread_alive (ptid_t ptid) override;
477 const char *thread_name (struct thread_info *) override;
479 void update_thread_list () override;
481 std::string pid_to_str (ptid_t) override;
483 const char *extra_thread_info (struct thread_info *) override;
485 ptid_t get_ada_task_ptid (long lwp, ULONGEST thread) override;
487 thread_info *thread_handle_to_thread_info (const gdb_byte *thread_handle,
488 int handle_len,
489 inferior *inf) override;
491 gdb::byte_vector thread_info_to_thread_handle (struct thread_info *tp)
492 override;
494 void stop (ptid_t) override;
496 void interrupt () override;
498 void pass_ctrlc () override;
500 enum target_xfer_status xfer_partial (enum target_object object,
501 const char *annex,
502 gdb_byte *readbuf,
503 const gdb_byte *writebuf,
504 ULONGEST offset, ULONGEST len,
505 ULONGEST *xfered_len) override;
507 ULONGEST get_memory_xfer_limit () override;
509 void rcmd (const char *command, struct ui_file *output) override;
511 const char *pid_to_exec_file (int pid) override;
513 void log_command (const char *cmd) override
515 serial_log_command (this, cmd);
518 CORE_ADDR get_thread_local_address (ptid_t ptid,
519 CORE_ADDR load_module_addr,
520 CORE_ADDR offset) override;
522 bool can_execute_reverse () override;
524 std::vector<mem_region> memory_map () override;
526 void flash_erase (ULONGEST address, LONGEST length) override;
528 void flash_done () override;
530 const struct target_desc *read_description () override;
532 int search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
533 const gdb_byte *pattern, ULONGEST pattern_len,
534 CORE_ADDR *found_addrp) override;
536 bool can_async_p () override;
538 bool is_async_p () override;
540 void async (bool) override;
542 int async_wait_fd () override;
544 void thread_events (int) override;
546 int can_do_single_step () override;
548 void terminal_inferior () override;
550 void terminal_ours () override;
552 bool supports_non_stop () override;
554 bool supports_multi_process () override;
556 bool supports_disable_randomization () override;
558 bool filesystem_is_local () override;
561 int fileio_open (struct inferior *inf, const char *filename,
562 int flags, int mode, int warn_if_slow,
563 fileio_error *target_errno) override;
565 int fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
566 ULONGEST offset, fileio_error *target_errno) override;
568 int fileio_pread (int fd, gdb_byte *read_buf, int len,
569 ULONGEST offset, fileio_error *target_errno) override;
571 int fileio_fstat (int fd, struct stat *sb, fileio_error *target_errno) override;
573 int fileio_close (int fd, fileio_error *target_errno) override;
575 int fileio_unlink (struct inferior *inf,
576 const char *filename,
577 fileio_error *target_errno) override;
579 gdb::optional<std::string>
580 fileio_readlink (struct inferior *inf,
581 const char *filename,
582 fileio_error *target_errno) override;
584 bool supports_enable_disable_tracepoint () override;
586 bool supports_string_tracing () override;
588 bool supports_evaluation_of_breakpoint_conditions () override;
590 bool can_run_breakpoint_commands () override;
592 void trace_init () override;
594 void download_tracepoint (struct bp_location *location) override;
596 bool can_download_tracepoint () override;
598 void download_trace_state_variable (const trace_state_variable &tsv) override;
600 void enable_tracepoint (struct bp_location *location) override;
602 void disable_tracepoint (struct bp_location *location) override;
604 void trace_set_readonly_regions () override;
606 void trace_start () override;
608 int get_trace_status (struct trace_status *ts) override;
610 void get_tracepoint_status (struct breakpoint *tp, struct uploaded_tp *utp)
611 override;
613 void trace_stop () override;
615 int trace_find (enum trace_find_type type, int num,
616 CORE_ADDR addr1, CORE_ADDR addr2, int *tpp) override;
618 bool get_trace_state_variable_value (int tsv, LONGEST *val) override;
620 int save_trace_data (const char *filename) override;
622 int upload_tracepoints (struct uploaded_tp **utpp) override;
624 int upload_trace_state_variables (struct uploaded_tsv **utsvp) override;
626 LONGEST get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len) override;
628 int get_min_fast_tracepoint_insn_len () override;
630 void set_disconnected_tracing (int val) override;
632 void set_circular_trace_buffer (int val) override;
634 void set_trace_buffer_size (LONGEST val) override;
636 bool set_trace_notes (const char *user, const char *notes,
637 const char *stopnotes) override;
639 int core_of_thread (ptid_t ptid) override;
641 int verify_memory (const gdb_byte *data,
642 CORE_ADDR memaddr, ULONGEST size) override;
645 bool get_tib_address (ptid_t ptid, CORE_ADDR *addr) override;
647 void set_permissions () override;
649 bool static_tracepoint_marker_at (CORE_ADDR,
650 struct static_tracepoint_marker *marker)
651 override;
653 std::vector<static_tracepoint_marker>
654 static_tracepoint_markers_by_strid (const char *id) override;
656 traceframe_info_up traceframe_info () override;
658 bool use_agent (bool use) override;
659 bool can_use_agent () override;
661 struct btrace_target_info *
662 enable_btrace (thread_info *tp, const struct btrace_config *conf) override;
664 void disable_btrace (struct btrace_target_info *tinfo) override;
666 void teardown_btrace (struct btrace_target_info *tinfo) override;
668 enum btrace_error read_btrace (struct btrace_data *data,
669 struct btrace_target_info *btinfo,
670 enum btrace_read_type type) override;
672 const struct btrace_config *btrace_conf (const struct btrace_target_info *) override;
673 bool augmented_libraries_svr4_read () override;
674 void follow_fork (inferior *, ptid_t, target_waitkind, bool, bool) override;
675 void follow_exec (inferior *, ptid_t, const char *) override;
676 int insert_fork_catchpoint (int) override;
677 int remove_fork_catchpoint (int) override;
678 int insert_vfork_catchpoint (int) override;
679 int remove_vfork_catchpoint (int) override;
680 int insert_exec_catchpoint (int) override;
681 int remove_exec_catchpoint (int) override;
682 enum exec_direction_kind execution_direction () override;
684 bool supports_memory_tagging () override;
686 bool fetch_memtags (CORE_ADDR address, size_t len,
687 gdb::byte_vector &tags, int type) override;
689 bool store_memtags (CORE_ADDR address, size_t len,
690 const gdb::byte_vector &tags, int type) override;
692 public: /* Remote specific methods. */
694 void remote_download_command_source (int num, ULONGEST addr,
695 struct command_line *cmds);
697 void remote_file_put (const char *local_file, const char *remote_file,
698 int from_tty);
699 void remote_file_get (const char *remote_file, const char *local_file,
700 int from_tty);
701 void remote_file_delete (const char *remote_file, int from_tty);
703 int remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
704 ULONGEST offset, fileio_error *remote_errno);
705 int remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
706 ULONGEST offset, fileio_error *remote_errno);
707 int remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
708 ULONGEST offset, fileio_error *remote_errno);
710 int remote_hostio_send_command (int command_bytes, int which_packet,
711 fileio_error *remote_errno, const char **attachment,
712 int *attachment_len);
713 int remote_hostio_set_filesystem (struct inferior *inf,
714 fileio_error *remote_errno);
715 /* We should get rid of this and use fileio_open directly. */
716 int remote_hostio_open (struct inferior *inf, const char *filename,
717 int flags, int mode, int warn_if_slow,
718 fileio_error *remote_errno);
719 int remote_hostio_close (int fd, fileio_error *remote_errno);
721 int remote_hostio_unlink (inferior *inf, const char *filename,
722 fileio_error *remote_errno);
724 struct remote_state *get_remote_state ();
726 long get_remote_packet_size (void);
727 long get_memory_packet_size (struct memory_packet_config *config);
729 long get_memory_write_packet_size ();
730 long get_memory_read_packet_size ();
732 char *append_pending_thread_resumptions (char *p, char *endp,
733 ptid_t ptid);
734 static void open_1 (const char *name, int from_tty, int extended_p);
735 void start_remote (int from_tty, int extended_p);
736 void remote_detach_1 (struct inferior *inf, int from_tty);
738 char *append_resumption (char *p, char *endp,
739 ptid_t ptid, int step, gdb_signal siggnal);
740 int remote_resume_with_vcont (ptid_t scope_ptid, int step,
741 gdb_signal siggnal);
743 thread_info *add_current_inferior_and_thread (const char *wait_status);
745 ptid_t wait_ns (ptid_t ptid, struct target_waitstatus *status,
746 target_wait_flags options);
747 ptid_t wait_as (ptid_t ptid, target_waitstatus *status,
748 target_wait_flags options);
750 ptid_t process_stop_reply (struct stop_reply *stop_reply,
751 target_waitstatus *status);
753 ptid_t select_thread_for_ambiguous_stop_reply
754 (const struct target_waitstatus &status);
756 void remote_notice_new_inferior (ptid_t currthread, bool executing);
758 void print_one_stopped_thread (thread_info *thread);
759 void process_initial_stop_replies (int from_tty);
761 thread_info *remote_add_thread (ptid_t ptid, bool running, bool executing,
762 bool silent_p);
764 void btrace_sync_conf (const btrace_config *conf);
766 void remote_btrace_maybe_reopen ();
768 void remove_new_fork_children (threads_listing_context *context);
769 void kill_new_fork_children (inferior *inf);
770 void discard_pending_stop_replies (struct inferior *inf);
771 int stop_reply_queue_length ();
773 void check_pending_events_prevent_wildcard_vcont
774 (bool *may_global_wildcard_vcont);
776 void discard_pending_stop_replies_in_queue ();
777 struct stop_reply *remote_notif_remove_queued_reply (ptid_t ptid);
778 struct stop_reply *queued_stop_reply (ptid_t ptid);
779 int peek_stop_reply (ptid_t ptid);
780 void remote_parse_stop_reply (const char *buf, stop_reply *event);
782 void remote_stop_ns (ptid_t ptid);
783 void remote_interrupt_as ();
784 void remote_interrupt_ns ();
786 char *remote_get_noisy_reply ();
787 int remote_query_attached (int pid);
788 inferior *remote_add_inferior (bool fake_pid_p, int pid, int attached,
789 int try_open_exec);
791 ptid_t remote_current_thread (ptid_t oldpid);
792 ptid_t get_current_thread (const char *wait_status);
794 void set_thread (ptid_t ptid, int gen);
795 void set_general_thread (ptid_t ptid);
796 void set_continue_thread (ptid_t ptid);
797 void set_general_process ();
799 char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
801 int remote_unpack_thread_info_response (const char *pkt, threadref *expectedref,
802 gdb_ext_thread_info *info);
803 int remote_get_threadinfo (threadref *threadid, int fieldset,
804 gdb_ext_thread_info *info);
806 int parse_threadlist_response (const char *pkt, int result_limit,
807 threadref *original_echo,
808 threadref *resultlist,
809 int *doneflag);
810 int remote_get_threadlist (int startflag, threadref *nextthread,
811 int result_limit, int *done, int *result_count,
812 threadref *threadlist);
814 int remote_threadlist_iterator (rmt_thread_action stepfunction,
815 void *context, int looplimit);
817 int remote_get_threads_with_ql (threads_listing_context *context);
818 int remote_get_threads_with_qxfer (threads_listing_context *context);
819 int remote_get_threads_with_qthreadinfo (threads_listing_context *context);
821 void extended_remote_restart ();
823 void get_offsets ();
825 void remote_check_symbols ();
827 void remote_supported_packet (const struct protocol_feature *feature,
828 enum packet_support support,
829 const char *argument);
831 void remote_query_supported ();
833 void remote_packet_size (const protocol_feature *feature,
834 packet_support support, const char *value);
836 void remote_serial_quit_handler ();
838 void remote_detach_pid (int pid);
840 void remote_vcont_probe ();
842 void remote_resume_with_hc (ptid_t ptid, int step,
843 gdb_signal siggnal);
845 void send_interrupt_sequence ();
846 void interrupt_query ();
848 void remote_notif_get_pending_events (notif_client *nc);
850 int fetch_register_using_p (struct regcache *regcache,
851 packet_reg *reg);
852 int send_g_packet ();
853 void process_g_packet (struct regcache *regcache);
854 void fetch_registers_using_g (struct regcache *regcache);
855 int store_register_using_P (const struct regcache *regcache,
856 packet_reg *reg);
857 void store_registers_using_G (const struct regcache *regcache);
859 void set_remote_traceframe ();
861 void check_binary_download (CORE_ADDR addr);
863 target_xfer_status remote_write_bytes_aux (const char *header,
864 CORE_ADDR memaddr,
865 const gdb_byte *myaddr,
866 ULONGEST len_units,
867 int unit_size,
868 ULONGEST *xfered_len_units,
869 char packet_format,
870 int use_length);
872 target_xfer_status remote_write_bytes (CORE_ADDR memaddr,
873 const gdb_byte *myaddr, ULONGEST len,
874 int unit_size, ULONGEST *xfered_len);
876 target_xfer_status remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
877 ULONGEST len_units,
878 int unit_size, ULONGEST *xfered_len_units);
880 target_xfer_status remote_xfer_live_readonly_partial (gdb_byte *readbuf,
881 ULONGEST memaddr,
882 ULONGEST len,
883 int unit_size,
884 ULONGEST *xfered_len);
886 target_xfer_status remote_read_bytes (CORE_ADDR memaddr,
887 gdb_byte *myaddr, ULONGEST len,
888 int unit_size,
889 ULONGEST *xfered_len);
891 packet_result remote_send_printf (const char *format, ...)
892 ATTRIBUTE_PRINTF (2, 3);
894 target_xfer_status remote_flash_write (ULONGEST address,
895 ULONGEST length, ULONGEST *xfered_len,
896 const gdb_byte *data);
898 int readchar (int timeout);
900 void remote_serial_write (const char *str, int len);
902 int putpkt (const char *buf);
903 int putpkt_binary (const char *buf, int cnt);
905 int putpkt (const gdb::char_vector &buf)
907 return putpkt (buf.data ());
910 void skip_frame ();
911 long read_frame (gdb::char_vector *buf_p);
912 void getpkt (gdb::char_vector *buf, int forever);
913 int getpkt_or_notif_sane_1 (gdb::char_vector *buf, int forever,
914 int expecting_notif, int *is_notif);
915 int getpkt_sane (gdb::char_vector *buf, int forever);
916 int getpkt_or_notif_sane (gdb::char_vector *buf, int forever,
917 int *is_notif);
918 int remote_vkill (int pid);
919 void remote_kill_k ();
921 void extended_remote_disable_randomization (int val);
922 int extended_remote_run (const std::string &args);
924 void send_environment_packet (const char *action,
925 const char *packet,
926 const char *value);
928 void extended_remote_environment_support ();
929 void extended_remote_set_inferior_cwd ();
931 target_xfer_status remote_write_qxfer (const char *object_name,
932 const char *annex,
933 const gdb_byte *writebuf,
934 ULONGEST offset, LONGEST len,
935 ULONGEST *xfered_len,
936 struct packet_config *packet);
938 target_xfer_status remote_read_qxfer (const char *object_name,
939 const char *annex,
940 gdb_byte *readbuf, ULONGEST offset,
941 LONGEST len,
942 ULONGEST *xfered_len,
943 struct packet_config *packet);
945 void push_stop_reply (struct stop_reply *new_event);
947 bool vcont_r_supported ();
949 private:
951 bool start_remote_1 (int from_tty, int extended_p);
953 /* The remote state. Don't reference this directly. Use the
954 get_remote_state method instead. */
955 remote_state m_remote_state;
958 static const target_info extended_remote_target_info = {
959 "extended-remote",
960 N_("Extended remote target using gdb-specific protocol"),
961 remote_doc
964 /* Set up the extended remote target by extending the standard remote
965 target and adding to it. */
967 class extended_remote_target final : public remote_target
969 public:
970 const target_info &info () const override
971 { return extended_remote_target_info; }
973 /* Open an extended-remote connection. */
974 static void open (const char *, int);
976 bool can_create_inferior () override { return true; }
977 void create_inferior (const char *, const std::string &,
978 char **, int) override;
980 void detach (inferior *, int) override;
982 bool can_attach () override { return true; }
983 void attach (const char *, int) override;
985 void post_attach (int) override;
986 bool supports_disable_randomization () override;
989 struct stop_reply : public notif_event
991 ~stop_reply ();
993 /* The identifier of the thread about this event */
994 ptid_t ptid;
996 /* The remote state this event is associated with. When the remote
997 connection, represented by a remote_state object, is closed,
998 all the associated stop_reply events should be released. */
999 struct remote_state *rs;
1001 struct target_waitstatus ws;
1003 /* The architecture associated with the expedited registers. */
1004 gdbarch *arch;
1006 /* Expedited registers. This makes remote debugging a bit more
1007 efficient for those targets that provide critical registers as
1008 part of their normal status mechanism (as another roundtrip to
1009 fetch them is avoided). */
1010 std::vector<cached_reg_t> regcache;
1012 enum target_stop_reason stop_reason;
1014 CORE_ADDR watch_data_address;
1016 int core;
1019 /* Return TARGET as a remote_target if it is one, else nullptr. */
1021 static remote_target *
1022 as_remote_target (process_stratum_target *target)
1024 return dynamic_cast<remote_target *> (target);
1027 /* See remote.h. */
1029 bool
1030 is_remote_target (process_stratum_target *target)
1032 return as_remote_target (target) != nullptr;
1035 /* Per-program-space data key. */
1036 static const registry<program_space>::key<char, gdb::xfree_deleter<char>>
1037 remote_pspace_data;
1039 /* The variable registered as the control variable used by the
1040 remote exec-file commands. While the remote exec-file setting is
1041 per-program-space, the set/show machinery uses this as the
1042 location of the remote exec-file value. */
1043 static std::string remote_exec_file_var;
1045 /* The size to align memory write packets, when practical. The protocol
1046 does not guarantee any alignment, and gdb will generate short
1047 writes and unaligned writes, but even as a best-effort attempt this
1048 can improve bulk transfers. For instance, if a write is misaligned
1049 relative to the target's data bus, the stub may need to make an extra
1050 round trip fetching data from the target. This doesn't make a
1051 huge difference, but it's easy to do, so we try to be helpful.
1053 The alignment chosen is arbitrary; usually data bus width is
1054 important here, not the possibly larger cache line size. */
1055 enum { REMOTE_ALIGN_WRITES = 16 };
1057 /* Prototypes for local functions. */
1059 static int hexnumlen (ULONGEST num);
1061 static int stubhex (int ch);
1063 static int hexnumstr (char *, ULONGEST);
1065 static int hexnumnstr (char *, ULONGEST, int);
1067 static CORE_ADDR remote_address_masked (CORE_ADDR);
1069 static int stub_unpack_int (const char *buff, int fieldlength);
1071 struct packet_config;
1073 static void show_remote_protocol_packet_cmd (struct ui_file *file,
1074 int from_tty,
1075 struct cmd_list_element *c,
1076 const char *value);
1078 static ptid_t read_ptid (const char *buf, const char **obuf);
1080 static void remote_async_inferior_event_handler (gdb_client_data);
1082 static bool remote_read_description_p (struct target_ops *target);
1084 static void remote_console_output (const char *msg);
1086 static void remote_btrace_reset (remote_state *rs);
1088 static void remote_unpush_and_throw (remote_target *target);
1090 /* For "remote". */
1092 static struct cmd_list_element *remote_cmdlist;
1094 /* For "set remote" and "show remote". */
1096 static struct cmd_list_element *remote_set_cmdlist;
1097 static struct cmd_list_element *remote_show_cmdlist;
1099 /* Controls whether GDB is willing to use range stepping. */
1101 static bool use_range_stepping = true;
1103 /* From the remote target's point of view, each thread is in one of these three
1104 states. */
1105 enum class resume_state
1107 /* Not resumed - we haven't been asked to resume this thread. */
1108 NOT_RESUMED,
1110 /* We have been asked to resume this thread, but haven't sent a vCont action
1111 for it yet. We'll need to consider it next time commit_resume is
1112 called. */
1113 RESUMED_PENDING_VCONT,
1115 /* We have been asked to resume this thread, and we have sent a vCont action
1116 for it. */
1117 RESUMED,
1120 /* Information about a thread's pending vCont-resume. Used when a thread is in
1121 the remote_resume_state::RESUMED_PENDING_VCONT state. remote_target::resume
1122 stores this information which is then picked up by
1123 remote_target::commit_resume to know which is the proper action for this
1124 thread to include in the vCont packet. */
1125 struct resumed_pending_vcont_info
1127 /* True if the last resume call for this thread was a step request, false
1128 if a continue request. */
1129 bool step;
1131 /* The signal specified in the last resume call for this thread. */
1132 gdb_signal sig;
1135 /* Private data that we'll store in (struct thread_info)->priv. */
1136 struct remote_thread_info : public private_thread_info
1138 std::string extra;
1139 std::string name;
1140 int core = -1;
1142 /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
1143 sequence of bytes. */
1144 gdb::byte_vector thread_handle;
1146 /* Whether the target stopped for a breakpoint/watchpoint. */
1147 enum target_stop_reason stop_reason = TARGET_STOPPED_BY_NO_REASON;
1149 /* This is set to the data address of the access causing the target
1150 to stop for a watchpoint. */
1151 CORE_ADDR watch_data_address = 0;
1153 /* Get the thread's resume state. */
1154 enum resume_state get_resume_state () const
1156 return m_resume_state;
1159 /* Put the thread in the NOT_RESUMED state. */
1160 void set_not_resumed ()
1162 m_resume_state = resume_state::NOT_RESUMED;
1165 /* Put the thread in the RESUMED_PENDING_VCONT state. */
1166 void set_resumed_pending_vcont (bool step, gdb_signal sig)
1168 m_resume_state = resume_state::RESUMED_PENDING_VCONT;
1169 m_resumed_pending_vcont_info.step = step;
1170 m_resumed_pending_vcont_info.sig = sig;
1173 /* Get the information this thread's pending vCont-resumption.
1175 Must only be called if the thread is in the RESUMED_PENDING_VCONT resume
1176 state. */
1177 const struct resumed_pending_vcont_info &resumed_pending_vcont_info () const
1179 gdb_assert (m_resume_state == resume_state::RESUMED_PENDING_VCONT);
1181 return m_resumed_pending_vcont_info;
1184 /* Put the thread in the VCONT_RESUMED state. */
1185 void set_resumed ()
1187 m_resume_state = resume_state::RESUMED;
1190 private:
1191 /* Resume state for this thread. This is used to implement vCont action
1192 coalescing (only when the target operates in non-stop mode).
1194 remote_target::resume moves the thread to the RESUMED_PENDING_VCONT state,
1195 which notes that this thread must be considered in the next commit_resume
1196 call.
1198 remote_target::commit_resume sends a vCont packet with actions for the
1199 threads in the RESUMED_PENDING_VCONT state and moves them to the
1200 VCONT_RESUMED state.
1202 When reporting a stop to the core for a thread, that thread is moved back
1203 to the NOT_RESUMED state. */
1204 enum resume_state m_resume_state = resume_state::NOT_RESUMED;
1206 /* Extra info used if the thread is in the RESUMED_PENDING_VCONT state. */
1207 struct resumed_pending_vcont_info m_resumed_pending_vcont_info;
1210 remote_state::remote_state ()
1211 : buf (400)
1215 remote_state::~remote_state ()
1217 xfree (this->last_pass_packet);
1218 xfree (this->last_program_signals_packet);
1219 xfree (this->finished_object);
1220 xfree (this->finished_annex);
1223 /* Utility: generate error from an incoming stub packet. */
1224 static void
1225 trace_error (char *buf)
1227 if (*buf++ != 'E')
1228 return; /* not an error msg */
1229 switch (*buf)
1231 case '1': /* malformed packet error */
1232 if (*++buf == '0') /* general case: */
1233 error (_("remote.c: error in outgoing packet."));
1234 else
1235 error (_("remote.c: error in outgoing packet at field #%ld."),
1236 strtol (buf, NULL, 16));
1237 default:
1238 error (_("Target returns error code '%s'."), buf);
1242 /* Utility: wait for reply from stub, while accepting "O" packets. */
1244 char *
1245 remote_target::remote_get_noisy_reply ()
1247 struct remote_state *rs = get_remote_state ();
1249 do /* Loop on reply from remote stub. */
1251 char *buf;
1253 QUIT; /* Allow user to bail out with ^C. */
1254 getpkt (&rs->buf, 0);
1255 buf = rs->buf.data ();
1256 if (buf[0] == 'E')
1257 trace_error (buf);
1258 else if (startswith (buf, "qRelocInsn:"))
1260 ULONGEST ul;
1261 CORE_ADDR from, to, org_to;
1262 const char *p, *pp;
1263 int adjusted_size = 0;
1264 int relocated = 0;
1266 p = buf + strlen ("qRelocInsn:");
1267 pp = unpack_varlen_hex (p, &ul);
1268 if (*pp != ';')
1269 error (_("invalid qRelocInsn packet: %s"), buf);
1270 from = ul;
1272 p = pp + 1;
1273 unpack_varlen_hex (p, &ul);
1274 to = ul;
1276 org_to = to;
1280 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
1281 relocated = 1;
1283 catch (const gdb_exception &ex)
1285 if (ex.error == MEMORY_ERROR)
1287 /* Propagate memory errors silently back to the
1288 target. The stub may have limited the range of
1289 addresses we can write to, for example. */
1291 else
1293 /* Something unexpectedly bad happened. Be verbose
1294 so we can tell what, and propagate the error back
1295 to the stub, so it doesn't get stuck waiting for
1296 a response. */
1297 exception_fprintf (gdb_stderr, ex,
1298 _("warning: relocating instruction: "));
1300 putpkt ("E01");
1303 if (relocated)
1305 adjusted_size = to - org_to;
1307 xsnprintf (buf, rs->buf.size (), "qRelocInsn:%x", adjusted_size);
1308 putpkt (buf);
1311 else if (buf[0] == 'O' && buf[1] != 'K')
1312 remote_console_output (buf + 1); /* 'O' message from stub */
1313 else
1314 return buf; /* Here's the actual reply. */
1316 while (1);
1319 struct remote_arch_state *
1320 remote_state::get_remote_arch_state (struct gdbarch *gdbarch)
1322 remote_arch_state *rsa;
1324 auto it = this->m_arch_states.find (gdbarch);
1325 if (it == this->m_arch_states.end ())
1327 auto p = this->m_arch_states.emplace (std::piecewise_construct,
1328 std::forward_as_tuple (gdbarch),
1329 std::forward_as_tuple (gdbarch));
1330 rsa = &p.first->second;
1332 /* Make sure that the packet buffer is plenty big enough for
1333 this architecture. */
1334 if (this->buf.size () < rsa->remote_packet_size)
1335 this->buf.resize (2 * rsa->remote_packet_size);
1337 else
1338 rsa = &it->second;
1340 return rsa;
1343 /* Fetch the global remote target state. */
1345 remote_state *
1346 remote_target::get_remote_state ()
1348 /* Make sure that the remote architecture state has been
1349 initialized, because doing so might reallocate rs->buf. Any
1350 function which calls getpkt also needs to be mindful of changes
1351 to rs->buf, but this call limits the number of places which run
1352 into trouble. */
1353 m_remote_state.get_remote_arch_state (target_gdbarch ());
1355 return &m_remote_state;
1358 /* Fetch the remote exec-file from the current program space. */
1360 static const char *
1361 get_remote_exec_file (void)
1363 char *remote_exec_file;
1365 remote_exec_file = remote_pspace_data.get (current_program_space);
1366 if (remote_exec_file == NULL)
1367 return "";
1369 return remote_exec_file;
1372 /* Set the remote exec file for PSPACE. */
1374 static void
1375 set_pspace_remote_exec_file (struct program_space *pspace,
1376 const char *remote_exec_file)
1378 char *old_file = remote_pspace_data.get (pspace);
1380 xfree (old_file);
1381 remote_pspace_data.set (pspace, xstrdup (remote_exec_file));
1384 /* The "set/show remote exec-file" set command hook. */
1386 static void
1387 set_remote_exec_file (const char *ignored, int from_tty,
1388 struct cmd_list_element *c)
1390 set_pspace_remote_exec_file (current_program_space,
1391 remote_exec_file_var.c_str ());
1394 /* The "set/show remote exec-file" show command hook. */
1396 static void
1397 show_remote_exec_file (struct ui_file *file, int from_tty,
1398 struct cmd_list_element *cmd, const char *value)
1400 gdb_printf (file, "%s\n", get_remote_exec_file ());
1403 static int
1404 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
1406 int regnum, num_remote_regs, offset;
1407 struct packet_reg **remote_regs;
1409 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
1411 struct packet_reg *r = &regs[regnum];
1413 if (register_size (gdbarch, regnum) == 0)
1414 /* Do not try to fetch zero-sized (placeholder) registers. */
1415 r->pnum = -1;
1416 else
1417 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
1419 r->regnum = regnum;
1422 /* Define the g/G packet format as the contents of each register
1423 with a remote protocol number, in order of ascending protocol
1424 number. */
1426 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
1427 for (num_remote_regs = 0, regnum = 0;
1428 regnum < gdbarch_num_regs (gdbarch);
1429 regnum++)
1430 if (regs[regnum].pnum != -1)
1431 remote_regs[num_remote_regs++] = &regs[regnum];
1433 std::sort (remote_regs, remote_regs + num_remote_regs,
1434 [] (const packet_reg *a, const packet_reg *b)
1435 { return a->pnum < b->pnum; });
1437 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
1439 remote_regs[regnum]->in_g_packet = 1;
1440 remote_regs[regnum]->offset = offset;
1441 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
1444 return offset;
1447 /* Given the architecture described by GDBARCH, return the remote
1448 protocol register's number and the register's offset in the g/G
1449 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
1450 If the target does not have a mapping for REGNUM, return false,
1451 otherwise, return true. */
1454 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
1455 int *pnum, int *poffset)
1457 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
1459 std::vector<packet_reg> regs (gdbarch_num_regs (gdbarch));
1461 map_regcache_remote_table (gdbarch, regs.data ());
1463 *pnum = regs[regnum].pnum;
1464 *poffset = regs[regnum].offset;
1466 return *pnum != -1;
1469 remote_arch_state::remote_arch_state (struct gdbarch *gdbarch)
1471 /* Use the architecture to build a regnum<->pnum table, which will be
1472 1:1 unless a feature set specifies otherwise. */
1473 this->regs.reset (new packet_reg [gdbarch_num_regs (gdbarch)] ());
1475 /* Record the maximum possible size of the g packet - it may turn out
1476 to be smaller. */
1477 this->sizeof_g_packet
1478 = map_regcache_remote_table (gdbarch, this->regs.get ());
1480 /* Default maximum number of characters in a packet body. Many
1481 remote stubs have a hardwired buffer size of 400 bytes
1482 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
1483 as the maximum packet-size to ensure that the packet and an extra
1484 NUL character can always fit in the buffer. This stops GDB
1485 trashing stubs that try to squeeze an extra NUL into what is
1486 already a full buffer (As of 1999-12-04 that was most stubs). */
1487 this->remote_packet_size = 400 - 1;
1489 /* This one is filled in when a ``g'' packet is received. */
1490 this->actual_register_packet_size = 0;
1492 /* Should rsa->sizeof_g_packet needs more space than the
1493 default, adjust the size accordingly. Remember that each byte is
1494 encoded as two characters. 32 is the overhead for the packet
1495 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
1496 (``$NN:G...#NN'') is a better guess, the below has been padded a
1497 little. */
1498 if (this->sizeof_g_packet > ((this->remote_packet_size - 32) / 2))
1499 this->remote_packet_size = (this->sizeof_g_packet * 2 + 32);
1502 /* Get a pointer to the current remote target. If not connected to a
1503 remote target, return NULL. */
1505 static remote_target *
1506 get_current_remote_target ()
1508 target_ops *proc_target = current_inferior ()->process_target ();
1509 return dynamic_cast<remote_target *> (proc_target);
1512 /* Return the current allowed size of a remote packet. This is
1513 inferred from the current architecture, and should be used to
1514 limit the length of outgoing packets. */
1515 long
1516 remote_target::get_remote_packet_size ()
1518 struct remote_state *rs = get_remote_state ();
1519 remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
1521 if (rs->explicit_packet_size)
1522 return rs->explicit_packet_size;
1524 return rsa->remote_packet_size;
1527 static struct packet_reg *
1528 packet_reg_from_regnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1529 long regnum)
1531 if (regnum < 0 && regnum >= gdbarch_num_regs (gdbarch))
1532 return NULL;
1533 else
1535 struct packet_reg *r = &rsa->regs[regnum];
1537 gdb_assert (r->regnum == regnum);
1538 return r;
1542 static struct packet_reg *
1543 packet_reg_from_pnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1544 LONGEST pnum)
1546 int i;
1548 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
1550 struct packet_reg *r = &rsa->regs[i];
1552 if (r->pnum == pnum)
1553 return r;
1555 return NULL;
1558 /* Allow the user to specify what sequence to send to the remote
1559 when he requests a program interruption: Although ^C is usually
1560 what remote systems expect (this is the default, here), it is
1561 sometimes preferable to send a break. On other systems such
1562 as the Linux kernel, a break followed by g, which is Magic SysRq g
1563 is required in order to interrupt the execution. */
1564 const char interrupt_sequence_control_c[] = "Ctrl-C";
1565 const char interrupt_sequence_break[] = "BREAK";
1566 const char interrupt_sequence_break_g[] = "BREAK-g";
1567 static const char *const interrupt_sequence_modes[] =
1569 interrupt_sequence_control_c,
1570 interrupt_sequence_break,
1571 interrupt_sequence_break_g,
1572 NULL
1574 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
1576 static void
1577 show_interrupt_sequence (struct ui_file *file, int from_tty,
1578 struct cmd_list_element *c,
1579 const char *value)
1581 if (interrupt_sequence_mode == interrupt_sequence_control_c)
1582 gdb_printf (file,
1583 _("Send the ASCII ETX character (Ctrl-c) "
1584 "to the remote target to interrupt the "
1585 "execution of the program.\n"));
1586 else if (interrupt_sequence_mode == interrupt_sequence_break)
1587 gdb_printf (file,
1588 _("send a break signal to the remote target "
1589 "to interrupt the execution of the program.\n"));
1590 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
1591 gdb_printf (file,
1592 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
1593 "the remote target to interrupt the execution "
1594 "of Linux kernel.\n"));
1595 else
1596 internal_error (_("Invalid value for interrupt_sequence_mode: %s."),
1597 interrupt_sequence_mode);
1600 /* This boolean variable specifies whether interrupt_sequence is sent
1601 to the remote target when gdb connects to it.
1602 This is mostly needed when you debug the Linux kernel: The Linux kernel
1603 expects BREAK g which is Magic SysRq g for connecting gdb. */
1604 static bool interrupt_on_connect = false;
1606 /* This variable is used to implement the "set/show remotebreak" commands.
1607 Since these commands are now deprecated in favor of "set/show remote
1608 interrupt-sequence", it no longer has any effect on the code. */
1609 static bool remote_break;
1611 static void
1612 set_remotebreak (const char *args, int from_tty, struct cmd_list_element *c)
1614 if (remote_break)
1615 interrupt_sequence_mode = interrupt_sequence_break;
1616 else
1617 interrupt_sequence_mode = interrupt_sequence_control_c;
1620 static void
1621 show_remotebreak (struct ui_file *file, int from_tty,
1622 struct cmd_list_element *c,
1623 const char *value)
1627 /* This variable sets the number of bits in an address that are to be
1628 sent in a memory ("M" or "m") packet. Normally, after stripping
1629 leading zeros, the entire address would be sent. This variable
1630 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
1631 initial implementation of remote.c restricted the address sent in
1632 memory packets to ``host::sizeof long'' bytes - (typically 32
1633 bits). Consequently, for 64 bit targets, the upper 32 bits of an
1634 address was never sent. Since fixing this bug may cause a break in
1635 some remote targets this variable is principally provided to
1636 facilitate backward compatibility. */
1638 static unsigned int remote_address_size;
1641 /* User configurable variables for the number of characters in a
1642 memory read/write packet. MIN (rsa->remote_packet_size,
1643 rsa->sizeof_g_packet) is the default. Some targets need smaller
1644 values (fifo overruns, et.al.) and some users need larger values
1645 (speed up transfers). The variables ``preferred_*'' (the user
1646 request), ``current_*'' (what was actually set) and ``forced_*''
1647 (Positive - a soft limit, negative - a hard limit). */
1649 struct memory_packet_config
1651 const char *name;
1652 long size;
1653 int fixed_p;
1656 /* The default max memory-write-packet-size, when the setting is
1657 "fixed". The 16k is historical. (It came from older GDB's using
1658 alloca for buffers and the knowledge (folklore?) that some hosts
1659 don't cope very well with large alloca calls.) */
1660 #define DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED 16384
1662 /* The minimum remote packet size for memory transfers. Ensures we
1663 can write at least one byte. */
1664 #define MIN_MEMORY_PACKET_SIZE 20
1666 /* Get the memory packet size, assuming it is fixed. */
1668 static long
1669 get_fixed_memory_packet_size (struct memory_packet_config *config)
1671 gdb_assert (config->fixed_p);
1673 if (config->size <= 0)
1674 return DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED;
1675 else
1676 return config->size;
1679 /* Compute the current size of a read/write packet. Since this makes
1680 use of ``actual_register_packet_size'' the computation is dynamic. */
1682 long
1683 remote_target::get_memory_packet_size (struct memory_packet_config *config)
1685 struct remote_state *rs = get_remote_state ();
1686 remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
1688 long what_they_get;
1689 if (config->fixed_p)
1690 what_they_get = get_fixed_memory_packet_size (config);
1691 else
1693 what_they_get = get_remote_packet_size ();
1694 /* Limit the packet to the size specified by the user. */
1695 if (config->size > 0
1696 && what_they_get > config->size)
1697 what_they_get = config->size;
1699 /* Limit it to the size of the targets ``g'' response unless we have
1700 permission from the stub to use a larger packet size. */
1701 if (rs->explicit_packet_size == 0
1702 && rsa->actual_register_packet_size > 0
1703 && what_they_get > rsa->actual_register_packet_size)
1704 what_they_get = rsa->actual_register_packet_size;
1706 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1707 what_they_get = MIN_MEMORY_PACKET_SIZE;
1709 /* Make sure there is room in the global buffer for this packet
1710 (including its trailing NUL byte). */
1711 if (rs->buf.size () < what_they_get + 1)
1712 rs->buf.resize (2 * what_they_get);
1714 return what_they_get;
1717 /* Update the size of a read/write packet. If they user wants
1718 something really big then do a sanity check. */
1720 static void
1721 set_memory_packet_size (const char *args, struct memory_packet_config *config)
1723 int fixed_p = config->fixed_p;
1724 long size = config->size;
1726 if (args == NULL)
1727 error (_("Argument required (integer, `fixed' or `limited')."));
1728 else if (strcmp (args, "hard") == 0
1729 || strcmp (args, "fixed") == 0)
1730 fixed_p = 1;
1731 else if (strcmp (args, "soft") == 0
1732 || strcmp (args, "limit") == 0)
1733 fixed_p = 0;
1734 else
1736 char *end;
1738 size = strtoul (args, &end, 0);
1739 if (args == end)
1740 error (_("Invalid %s (bad syntax)."), config->name);
1742 /* Instead of explicitly capping the size of a packet to or
1743 disallowing it, the user is allowed to set the size to
1744 something arbitrarily large. */
1747 /* Extra checks? */
1748 if (fixed_p && !config->fixed_p)
1750 /* So that the query shows the correct value. */
1751 long query_size = (size <= 0
1752 ? DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED
1753 : size);
1755 if (! query (_("The target may not be able to correctly handle a %s\n"
1756 "of %ld bytes. Change the packet size? "),
1757 config->name, query_size))
1758 error (_("Packet size not changed."));
1760 /* Update the config. */
1761 config->fixed_p = fixed_p;
1762 config->size = size;
1765 static void
1766 show_memory_packet_size (struct memory_packet_config *config)
1768 if (config->size == 0)
1769 gdb_printf (_("The %s is 0 (default). "), config->name);
1770 else
1771 gdb_printf (_("The %s is %ld. "), config->name, config->size);
1772 if (config->fixed_p)
1773 gdb_printf (_("Packets are fixed at %ld bytes.\n"),
1774 get_fixed_memory_packet_size (config));
1775 else
1777 remote_target *remote = get_current_remote_target ();
1779 if (remote != NULL)
1780 gdb_printf (_("Packets are limited to %ld bytes.\n"),
1781 remote->get_memory_packet_size (config));
1782 else
1783 gdb_puts ("The actual limit will be further reduced "
1784 "dependent on the target.\n");
1788 /* FIXME: needs to be per-remote-target. */
1789 static struct memory_packet_config memory_write_packet_config =
1791 "memory-write-packet-size",
1794 static void
1795 set_memory_write_packet_size (const char *args, int from_tty)
1797 set_memory_packet_size (args, &memory_write_packet_config);
1800 static void
1801 show_memory_write_packet_size (const char *args, int from_tty)
1803 show_memory_packet_size (&memory_write_packet_config);
1806 /* Show the number of hardware watchpoints that can be used. */
1808 static void
1809 show_hardware_watchpoint_limit (struct ui_file *file, int from_tty,
1810 struct cmd_list_element *c,
1811 const char *value)
1813 gdb_printf (file, _("The maximum number of target hardware "
1814 "watchpoints is %s.\n"), value);
1817 /* Show the length limit (in bytes) for hardware watchpoints. */
1819 static void
1820 show_hardware_watchpoint_length_limit (struct ui_file *file, int from_tty,
1821 struct cmd_list_element *c,
1822 const char *value)
1824 gdb_printf (file, _("The maximum length (in bytes) of a target "
1825 "hardware watchpoint is %s.\n"), value);
1828 /* Show the number of hardware breakpoints that can be used. */
1830 static void
1831 show_hardware_breakpoint_limit (struct ui_file *file, int from_tty,
1832 struct cmd_list_element *c,
1833 const char *value)
1835 gdb_printf (file, _("The maximum number of target hardware "
1836 "breakpoints is %s.\n"), value);
1839 /* Controls the maximum number of characters to display in the debug output
1840 for each remote packet. The remaining characters are omitted. */
1842 static int remote_packet_max_chars = 512;
1844 /* Show the maximum number of characters to display for each remote packet
1845 when remote debugging is enabled. */
1847 static void
1848 show_remote_packet_max_chars (struct ui_file *file, int from_tty,
1849 struct cmd_list_element *c,
1850 const char *value)
1852 gdb_printf (file, _("Number of remote packet characters to "
1853 "display is %s.\n"), value);
1856 long
1857 remote_target::get_memory_write_packet_size ()
1859 return get_memory_packet_size (&memory_write_packet_config);
1862 /* FIXME: needs to be per-remote-target. */
1863 static struct memory_packet_config memory_read_packet_config =
1865 "memory-read-packet-size",
1868 static void
1869 set_memory_read_packet_size (const char *args, int from_tty)
1871 set_memory_packet_size (args, &memory_read_packet_config);
1874 static void
1875 show_memory_read_packet_size (const char *args, int from_tty)
1877 show_memory_packet_size (&memory_read_packet_config);
1880 long
1881 remote_target::get_memory_read_packet_size ()
1883 long size = get_memory_packet_size (&memory_read_packet_config);
1885 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1886 extra buffer size argument before the memory read size can be
1887 increased beyond this. */
1888 if (size > get_remote_packet_size ())
1889 size = get_remote_packet_size ();
1890 return size;
1895 struct packet_config
1897 const char *name;
1898 const char *title;
1900 /* If auto, GDB auto-detects support for this packet or feature,
1901 either through qSupported, or by trying the packet and looking
1902 at the response. If true, GDB assumes the target supports this
1903 packet. If false, the packet is disabled. Configs that don't
1904 have an associated command always have this set to auto. */
1905 enum auto_boolean detect;
1907 /* The "show remote foo-packet" command created for this packet. */
1908 cmd_list_element *show_cmd;
1910 /* Does the target support this packet? */
1911 enum packet_support support;
1914 static enum packet_support packet_config_support (struct packet_config *config);
1915 static enum packet_support packet_support (int packet);
1917 static void
1918 show_packet_config_cmd (ui_file *file, struct packet_config *config)
1920 const char *support = "internal-error";
1922 switch (packet_config_support (config))
1924 case PACKET_ENABLE:
1925 support = "enabled";
1926 break;
1927 case PACKET_DISABLE:
1928 support = "disabled";
1929 break;
1930 case PACKET_SUPPORT_UNKNOWN:
1931 support = "unknown";
1932 break;
1934 switch (config->detect)
1936 case AUTO_BOOLEAN_AUTO:
1937 gdb_printf (file,
1938 _("Support for the `%s' packet "
1939 "is auto-detected, currently %s.\n"),
1940 config->name, support);
1941 break;
1942 case AUTO_BOOLEAN_TRUE:
1943 case AUTO_BOOLEAN_FALSE:
1944 gdb_printf (file,
1945 _("Support for the `%s' packet is currently %s.\n"),
1946 config->name, support);
1947 break;
1951 static void
1952 add_packet_config_cmd (struct packet_config *config, const char *name,
1953 const char *title, int legacy)
1955 config->name = name;
1956 config->title = title;
1957 gdb::unique_xmalloc_ptr<char> set_doc
1958 = xstrprintf ("Set use of remote protocol `%s' (%s) packet.",
1959 name, title);
1960 gdb::unique_xmalloc_ptr<char> show_doc
1961 = xstrprintf ("Show current use of remote protocol `%s' (%s) packet.",
1962 name, title);
1963 /* set/show TITLE-packet {auto,on,off} */
1964 gdb::unique_xmalloc_ptr<char> cmd_name = xstrprintf ("%s-packet", title);
1965 set_show_commands cmds
1966 = add_setshow_auto_boolean_cmd (cmd_name.release (), class_obscure,
1967 &config->detect, set_doc.get (),
1968 show_doc.get (), NULL, /* help_doc */
1969 NULL,
1970 show_remote_protocol_packet_cmd,
1971 &remote_set_cmdlist, &remote_show_cmdlist);
1972 config->show_cmd = cmds.show;
1974 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
1975 if (legacy)
1977 /* It's not clear who should take ownership of the LEGACY_NAME string
1978 created below, so, for now, place the string into a static vector
1979 which ensures the strings is released when GDB exits. */
1980 static std::vector<gdb::unique_xmalloc_ptr<char>> legacy_names;
1981 gdb::unique_xmalloc_ptr<char> legacy_name
1982 = xstrprintf ("%s-packet", name);
1983 add_alias_cmd (legacy_name.get (), cmds.set, class_obscure, 0,
1984 &remote_set_cmdlist);
1985 add_alias_cmd (legacy_name.get (), cmds.show, class_obscure, 0,
1986 &remote_show_cmdlist);
1987 legacy_names.emplace_back (std::move (legacy_name));
1991 static enum packet_result
1992 packet_check_result (const char *buf)
1994 if (buf[0] != '\0')
1996 /* The stub recognized the packet request. Check that the
1997 operation succeeded. */
1998 if (buf[0] == 'E'
1999 && isxdigit (buf[1]) && isxdigit (buf[2])
2000 && buf[3] == '\0')
2001 /* "Enn" - definitely an error. */
2002 return PACKET_ERROR;
2004 /* Always treat "E." as an error. This will be used for
2005 more verbose error messages, such as E.memtypes. */
2006 if (buf[0] == 'E' && buf[1] == '.')
2007 return PACKET_ERROR;
2009 /* The packet may or may not be OK. Just assume it is. */
2010 return PACKET_OK;
2012 else
2013 /* The stub does not support the packet. */
2014 return PACKET_UNKNOWN;
2017 static enum packet_result
2018 packet_check_result (const gdb::char_vector &buf)
2020 return packet_check_result (buf.data ());
2023 static enum packet_result
2024 packet_ok (const char *buf, struct packet_config *config)
2026 enum packet_result result;
2028 if (config->detect != AUTO_BOOLEAN_TRUE
2029 && config->support == PACKET_DISABLE)
2030 internal_error (_("packet_ok: attempt to use a disabled packet"));
2032 result = packet_check_result (buf);
2033 switch (result)
2035 case PACKET_OK:
2036 case PACKET_ERROR:
2037 /* The stub recognized the packet request. */
2038 if (config->support == PACKET_SUPPORT_UNKNOWN)
2040 remote_debug_printf ("Packet %s (%s) is supported",
2041 config->name, config->title);
2042 config->support = PACKET_ENABLE;
2044 break;
2045 case PACKET_UNKNOWN:
2046 /* The stub does not support the packet. */
2047 if (config->detect == AUTO_BOOLEAN_AUTO
2048 && config->support == PACKET_ENABLE)
2050 /* If the stub previously indicated that the packet was
2051 supported then there is a protocol error. */
2052 error (_("Protocol error: %s (%s) conflicting enabled responses."),
2053 config->name, config->title);
2055 else if (config->detect == AUTO_BOOLEAN_TRUE)
2057 /* The user set it wrong. */
2058 error (_("Enabled packet %s (%s) not recognized by stub"),
2059 config->name, config->title);
2062 remote_debug_printf ("Packet %s (%s) is NOT supported",
2063 config->name, config->title);
2064 config->support = PACKET_DISABLE;
2065 break;
2068 return result;
2071 static enum packet_result
2072 packet_ok (const gdb::char_vector &buf, struct packet_config *config)
2074 return packet_ok (buf.data (), config);
2077 enum {
2078 PACKET_vCont = 0,
2079 PACKET_X,
2080 PACKET_qSymbol,
2081 PACKET_P,
2082 PACKET_p,
2083 PACKET_Z0,
2084 PACKET_Z1,
2085 PACKET_Z2,
2086 PACKET_Z3,
2087 PACKET_Z4,
2088 PACKET_vFile_setfs,
2089 PACKET_vFile_open,
2090 PACKET_vFile_pread,
2091 PACKET_vFile_pwrite,
2092 PACKET_vFile_close,
2093 PACKET_vFile_unlink,
2094 PACKET_vFile_readlink,
2095 PACKET_vFile_fstat,
2096 PACKET_qXfer_auxv,
2097 PACKET_qXfer_features,
2098 PACKET_qXfer_exec_file,
2099 PACKET_qXfer_libraries,
2100 PACKET_qXfer_libraries_svr4,
2101 PACKET_qXfer_memory_map,
2102 PACKET_qXfer_osdata,
2103 PACKET_qXfer_threads,
2104 PACKET_qXfer_statictrace_read,
2105 PACKET_qXfer_traceframe_info,
2106 PACKET_qXfer_uib,
2107 PACKET_qGetTIBAddr,
2108 PACKET_qGetTLSAddr,
2109 PACKET_qSupported,
2110 PACKET_qTStatus,
2111 PACKET_QPassSignals,
2112 PACKET_QCatchSyscalls,
2113 PACKET_QProgramSignals,
2114 PACKET_QSetWorkingDir,
2115 PACKET_QStartupWithShell,
2116 PACKET_QEnvironmentHexEncoded,
2117 PACKET_QEnvironmentReset,
2118 PACKET_QEnvironmentUnset,
2119 PACKET_qCRC,
2120 PACKET_qSearch_memory,
2121 PACKET_vAttach,
2122 PACKET_vRun,
2123 PACKET_QStartNoAckMode,
2124 PACKET_vKill,
2125 PACKET_qXfer_siginfo_read,
2126 PACKET_qXfer_siginfo_write,
2127 PACKET_qAttached,
2129 /* Support for conditional tracepoints. */
2130 PACKET_ConditionalTracepoints,
2132 /* Support for target-side breakpoint conditions. */
2133 PACKET_ConditionalBreakpoints,
2135 /* Support for target-side breakpoint commands. */
2136 PACKET_BreakpointCommands,
2138 /* Support for fast tracepoints. */
2139 PACKET_FastTracepoints,
2141 /* Support for static tracepoints. */
2142 PACKET_StaticTracepoints,
2144 /* Support for installing tracepoints while a trace experiment is
2145 running. */
2146 PACKET_InstallInTrace,
2148 PACKET_bc,
2149 PACKET_bs,
2150 PACKET_TracepointSource,
2151 PACKET_QAllow,
2152 PACKET_qXfer_fdpic,
2153 PACKET_QDisableRandomization,
2154 PACKET_QAgent,
2155 PACKET_QTBuffer_size,
2156 PACKET_Qbtrace_off,
2157 PACKET_Qbtrace_bts,
2158 PACKET_Qbtrace_pt,
2159 PACKET_qXfer_btrace,
2161 /* Support for the QNonStop packet. */
2162 PACKET_QNonStop,
2164 /* Support for the QThreadEvents packet. */
2165 PACKET_QThreadEvents,
2167 /* Support for multi-process extensions. */
2168 PACKET_multiprocess_feature,
2170 /* Support for enabling and disabling tracepoints while a trace
2171 experiment is running. */
2172 PACKET_EnableDisableTracepoints_feature,
2174 /* Support for collecting strings using the tracenz bytecode. */
2175 PACKET_tracenz_feature,
2177 /* Support for continuing to run a trace experiment while GDB is
2178 disconnected. */
2179 PACKET_DisconnectedTracing_feature,
2181 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
2182 PACKET_augmented_libraries_svr4_read_feature,
2184 /* Support for the qXfer:btrace-conf:read packet. */
2185 PACKET_qXfer_btrace_conf,
2187 /* Support for the Qbtrace-conf:bts:size packet. */
2188 PACKET_Qbtrace_conf_bts_size,
2190 /* Support for swbreak+ feature. */
2191 PACKET_swbreak_feature,
2193 /* Support for hwbreak+ feature. */
2194 PACKET_hwbreak_feature,
2196 /* Support for fork events. */
2197 PACKET_fork_event_feature,
2199 /* Support for vfork events. */
2200 PACKET_vfork_event_feature,
2202 /* Support for the Qbtrace-conf:pt:size packet. */
2203 PACKET_Qbtrace_conf_pt_size,
2205 /* Support for exec events. */
2206 PACKET_exec_event_feature,
2208 /* Support for query supported vCont actions. */
2209 PACKET_vContSupported,
2211 /* Support remote CTRL-C. */
2212 PACKET_vCtrlC,
2214 /* Support TARGET_WAITKIND_NO_RESUMED. */
2215 PACKET_no_resumed,
2217 /* Support for memory tagging, allocation tag fetch/store
2218 packets and the tag violation stop replies. */
2219 PACKET_memory_tagging_feature,
2221 PACKET_MAX
2224 /* FIXME: needs to be per-remote-target. Ignoring this for now,
2225 assuming all remote targets are the same server (thus all support
2226 the same packets). */
2227 static struct packet_config remote_protocol_packets[PACKET_MAX];
2229 /* Returns the packet's corresponding "set remote foo-packet" command
2230 state. See struct packet_config for more details. */
2232 static enum auto_boolean
2233 packet_set_cmd_state (int packet)
2235 return remote_protocol_packets[packet].detect;
2238 /* Returns whether a given packet or feature is supported. This takes
2239 into account the state of the corresponding "set remote foo-packet"
2240 command, which may be used to bypass auto-detection. */
2242 static enum packet_support
2243 packet_config_support (struct packet_config *config)
2245 switch (config->detect)
2247 case AUTO_BOOLEAN_TRUE:
2248 return PACKET_ENABLE;
2249 case AUTO_BOOLEAN_FALSE:
2250 return PACKET_DISABLE;
2251 case AUTO_BOOLEAN_AUTO:
2252 return config->support;
2253 default:
2254 gdb_assert_not_reached ("bad switch");
2258 /* Same as packet_config_support, but takes the packet's enum value as
2259 argument. */
2261 static enum packet_support
2262 packet_support (int packet)
2264 struct packet_config *config = &remote_protocol_packets[packet];
2266 return packet_config_support (config);
2269 static void
2270 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
2271 struct cmd_list_element *c,
2272 const char *value)
2274 struct packet_config *packet;
2275 gdb_assert (c->var.has_value ());
2277 for (packet = remote_protocol_packets;
2278 packet < &remote_protocol_packets[PACKET_MAX];
2279 packet++)
2281 if (c == packet->show_cmd)
2283 show_packet_config_cmd (file, packet);
2284 return;
2287 internal_error (_("Could not find config for %s"),
2288 c->name);
2291 /* Should we try one of the 'Z' requests? */
2293 enum Z_packet_type
2295 Z_PACKET_SOFTWARE_BP,
2296 Z_PACKET_HARDWARE_BP,
2297 Z_PACKET_WRITE_WP,
2298 Z_PACKET_READ_WP,
2299 Z_PACKET_ACCESS_WP,
2300 NR_Z_PACKET_TYPES
2303 /* For compatibility with older distributions. Provide a ``set remote
2304 Z-packet ...'' command that updates all the Z packet types. */
2306 static enum auto_boolean remote_Z_packet_detect;
2308 static void
2309 set_remote_protocol_Z_packet_cmd (const char *args, int from_tty,
2310 struct cmd_list_element *c)
2312 int i;
2314 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2315 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
2318 static void
2319 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
2320 struct cmd_list_element *c,
2321 const char *value)
2323 int i;
2325 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2327 show_packet_config_cmd (file, &remote_protocol_packets[PACKET_Z0 + i]);
2331 /* Returns true if the multi-process extensions are in effect. */
2333 static int
2334 remote_multi_process_p (struct remote_state *rs)
2336 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
2339 /* Returns true if fork events are supported. */
2341 static int
2342 remote_fork_event_p (struct remote_state *rs)
2344 return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
2347 /* Returns true if vfork events are supported. */
2349 static int
2350 remote_vfork_event_p (struct remote_state *rs)
2352 return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
2355 /* Returns true if exec events are supported. */
2357 static int
2358 remote_exec_event_p (struct remote_state *rs)
2360 return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
2363 /* Returns true if memory tagging is supported, false otherwise. */
2365 static bool
2366 remote_memory_tagging_p ()
2368 return packet_support (PACKET_memory_tagging_feature) == PACKET_ENABLE;
2371 /* Insert fork catchpoint target routine. If fork events are enabled
2372 then return success, nothing more to do. */
2375 remote_target::insert_fork_catchpoint (int pid)
2377 struct remote_state *rs = get_remote_state ();
2379 return !remote_fork_event_p (rs);
2382 /* Remove fork catchpoint target routine. Nothing to do, just
2383 return success. */
2386 remote_target::remove_fork_catchpoint (int pid)
2388 return 0;
2391 /* Insert vfork catchpoint target routine. If vfork events are enabled
2392 then return success, nothing more to do. */
2395 remote_target::insert_vfork_catchpoint (int pid)
2397 struct remote_state *rs = get_remote_state ();
2399 return !remote_vfork_event_p (rs);
2402 /* Remove vfork catchpoint target routine. Nothing to do, just
2403 return success. */
2406 remote_target::remove_vfork_catchpoint (int pid)
2408 return 0;
2411 /* Insert exec catchpoint target routine. If exec events are
2412 enabled, just return success. */
2415 remote_target::insert_exec_catchpoint (int pid)
2417 struct remote_state *rs = get_remote_state ();
2419 return !remote_exec_event_p (rs);
2422 /* Remove exec catchpoint target routine. Nothing to do, just
2423 return success. */
2426 remote_target::remove_exec_catchpoint (int pid)
2428 return 0;
2433 /* Take advantage of the fact that the TID field is not used, to tag
2434 special ptids with it set to != 0. */
2435 static const ptid_t magic_null_ptid (42000, -1, 1);
2436 static const ptid_t not_sent_ptid (42000, -2, 1);
2437 static const ptid_t any_thread_ptid (42000, 0, 1);
2439 /* Find out if the stub attached to PID (and hence GDB should offer to
2440 detach instead of killing it when bailing out). */
2443 remote_target::remote_query_attached (int pid)
2445 struct remote_state *rs = get_remote_state ();
2446 size_t size = get_remote_packet_size ();
2448 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
2449 return 0;
2451 if (remote_multi_process_p (rs))
2452 xsnprintf (rs->buf.data (), size, "qAttached:%x", pid);
2453 else
2454 xsnprintf (rs->buf.data (), size, "qAttached");
2456 putpkt (rs->buf);
2457 getpkt (&rs->buf, 0);
2459 switch (packet_ok (rs->buf,
2460 &remote_protocol_packets[PACKET_qAttached]))
2462 case PACKET_OK:
2463 if (strcmp (rs->buf.data (), "1") == 0)
2464 return 1;
2465 break;
2466 case PACKET_ERROR:
2467 warning (_("Remote failure reply: %s"), rs->buf.data ());
2468 break;
2469 case PACKET_UNKNOWN:
2470 break;
2473 return 0;
2476 /* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
2477 has been invented by GDB, instead of reported by the target. Since
2478 we can be connected to a remote system before before knowing about
2479 any inferior, mark the target with execution when we find the first
2480 inferior. If ATTACHED is 1, then we had just attached to this
2481 inferior. If it is 0, then we just created this inferior. If it
2482 is -1, then try querying the remote stub to find out if it had
2483 attached to the inferior or not. If TRY_OPEN_EXEC is true then
2484 attempt to open this inferior's executable as the main executable
2485 if no main executable is open already. */
2487 inferior *
2488 remote_target::remote_add_inferior (bool fake_pid_p, int pid, int attached,
2489 int try_open_exec)
2491 struct inferior *inf;
2493 /* Check whether this process we're learning about is to be
2494 considered attached, or if is to be considered to have been
2495 spawned by the stub. */
2496 if (attached == -1)
2497 attached = remote_query_attached (pid);
2499 if (gdbarch_has_global_solist (target_gdbarch ()))
2501 /* If the target shares code across all inferiors, then every
2502 attach adds a new inferior. */
2503 inf = add_inferior (pid);
2505 /* ... and every inferior is bound to the same program space.
2506 However, each inferior may still have its own address
2507 space. */
2508 inf->aspace = maybe_new_address_space ();
2509 inf->pspace = current_program_space;
2511 else
2513 /* In the traditional debugging scenario, there's a 1-1 match
2514 between program/address spaces. We simply bind the inferior
2515 to the program space's address space. */
2516 inf = current_inferior ();
2518 /* However, if the current inferior is already bound to a
2519 process, find some other empty inferior. */
2520 if (inf->pid != 0)
2522 inf = nullptr;
2523 for (inferior *it : all_inferiors ())
2524 if (it->pid == 0)
2526 inf = it;
2527 break;
2530 if (inf == nullptr)
2532 /* Since all inferiors were already bound to a process, add
2533 a new inferior. */
2534 inf = add_inferior_with_spaces ();
2536 switch_to_inferior_no_thread (inf);
2537 inf->push_target (this);
2538 inferior_appeared (inf, pid);
2541 inf->attach_flag = attached;
2542 inf->fake_pid_p = fake_pid_p;
2544 /* If no main executable is currently open then attempt to
2545 open the file that was executed to create this inferior. */
2546 if (try_open_exec && get_exec_file (0) == NULL)
2547 exec_file_locate_attach (pid, 0, 1);
2549 /* Check for exec file mismatch, and let the user solve it. */
2550 validate_exec_file (1);
2552 return inf;
2555 static remote_thread_info *get_remote_thread_info (thread_info *thread);
2556 static remote_thread_info *get_remote_thread_info (remote_target *target,
2557 ptid_t ptid);
2559 /* Add thread PTID to GDB's thread list. Tag it as executing/running
2560 according to EXECUTING and RUNNING respectively. If SILENT_P (or the
2561 remote_state::starting_up flag) is true then the new thread is added
2562 silently, otherwise the new thread will be announced to the user. */
2564 thread_info *
2565 remote_target::remote_add_thread (ptid_t ptid, bool running, bool executing,
2566 bool silent_p)
2568 struct remote_state *rs = get_remote_state ();
2569 struct thread_info *thread;
2571 /* GDB historically didn't pull threads in the initial connection
2572 setup. If the remote target doesn't even have a concept of
2573 threads (e.g., a bare-metal target), even if internally we
2574 consider that a single-threaded target, mentioning a new thread
2575 might be confusing to the user. Be silent then, preserving the
2576 age old behavior. */
2577 if (rs->starting_up || silent_p)
2578 thread = add_thread_silent (this, ptid);
2579 else
2580 thread = add_thread (this, ptid);
2582 /* We start by assuming threads are resumed. That state then gets updated
2583 when we process a matching stop reply. */
2584 get_remote_thread_info (thread)->set_resumed ();
2586 set_executing (this, ptid, executing);
2587 set_running (this, ptid, running);
2589 return thread;
2592 /* Come here when we learn about a thread id from the remote target.
2593 It may be the first time we hear about such thread, so take the
2594 opportunity to add it to GDB's thread list. In case this is the
2595 first time we're noticing its corresponding inferior, add it to
2596 GDB's inferior list as well. EXECUTING indicates whether the
2597 thread is (internally) executing or stopped. */
2599 void
2600 remote_target::remote_notice_new_inferior (ptid_t currthread, bool executing)
2602 /* In non-stop mode, we assume new found threads are (externally)
2603 running until proven otherwise with a stop reply. In all-stop,
2604 we can only get here if all threads are stopped. */
2605 bool running = target_is_non_stop_p ();
2607 /* If this is a new thread, add it to GDB's thread list.
2608 If we leave it up to WFI to do this, bad things will happen. */
2610 thread_info *tp = find_thread_ptid (this, currthread);
2611 if (tp != NULL && tp->state == THREAD_EXITED)
2613 /* We're seeing an event on a thread id we knew had exited.
2614 This has to be a new thread reusing the old id. Add it. */
2615 remote_add_thread (currthread, running, executing, false);
2616 return;
2619 if (!in_thread_list (this, currthread))
2621 struct inferior *inf = NULL;
2622 int pid = currthread.pid ();
2624 if (inferior_ptid.is_pid ()
2625 && pid == inferior_ptid.pid ())
2627 /* inferior_ptid has no thread member yet. This can happen
2628 with the vAttach -> remote_wait,"TAAthread:" path if the
2629 stub doesn't support qC. This is the first stop reported
2630 after an attach, so this is the main thread. Update the
2631 ptid in the thread list. */
2632 if (in_thread_list (this, ptid_t (pid)))
2633 thread_change_ptid (this, inferior_ptid, currthread);
2634 else
2636 thread_info *thr
2637 = remote_add_thread (currthread, running, executing, false);
2638 switch_to_thread (thr);
2640 return;
2643 if (magic_null_ptid == inferior_ptid)
2645 /* inferior_ptid is not set yet. This can happen with the
2646 vRun -> remote_wait,"TAAthread:" path if the stub
2647 doesn't support qC. This is the first stop reported
2648 after an attach, so this is the main thread. Update the
2649 ptid in the thread list. */
2650 thread_change_ptid (this, inferior_ptid, currthread);
2651 return;
2654 /* When connecting to a target remote, or to a target
2655 extended-remote which already was debugging an inferior, we
2656 may not know about it yet. Add it before adding its child
2657 thread, so notifications are emitted in a sensible order. */
2658 if (find_inferior_pid (this, currthread.pid ()) == NULL)
2660 struct remote_state *rs = get_remote_state ();
2661 bool fake_pid_p = !remote_multi_process_p (rs);
2663 inf = remote_add_inferior (fake_pid_p,
2664 currthread.pid (), -1, 1);
2667 /* This is really a new thread. Add it. */
2668 thread_info *new_thr
2669 = remote_add_thread (currthread, running, executing, false);
2671 /* If we found a new inferior, let the common code do whatever
2672 it needs to with it (e.g., read shared libraries, insert
2673 breakpoints), unless we're just setting up an all-stop
2674 connection. */
2675 if (inf != NULL)
2677 struct remote_state *rs = get_remote_state ();
2679 if (!rs->starting_up)
2680 notice_new_inferior (new_thr, executing, 0);
2685 /* Return THREAD's private thread data, creating it if necessary. */
2687 static remote_thread_info *
2688 get_remote_thread_info (thread_info *thread)
2690 gdb_assert (thread != NULL);
2692 if (thread->priv == NULL)
2693 thread->priv.reset (new remote_thread_info);
2695 return gdb::checked_static_cast<remote_thread_info *> (thread->priv.get ());
2698 /* Return PTID's private thread data, creating it if necessary. */
2700 static remote_thread_info *
2701 get_remote_thread_info (remote_target *target, ptid_t ptid)
2703 thread_info *thr = find_thread_ptid (target, ptid);
2704 return get_remote_thread_info (thr);
2707 /* Call this function as a result of
2708 1) A halt indication (T packet) containing a thread id
2709 2) A direct query of currthread
2710 3) Successful execution of set thread */
2712 static void
2713 record_currthread (struct remote_state *rs, ptid_t currthread)
2715 rs->general_thread = currthread;
2718 /* If 'QPassSignals' is supported, tell the remote stub what signals
2719 it can simply pass through to the inferior without reporting. */
2721 void
2722 remote_target::pass_signals (gdb::array_view<const unsigned char> pass_signals)
2724 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
2726 char *pass_packet, *p;
2727 int count = 0;
2728 struct remote_state *rs = get_remote_state ();
2730 gdb_assert (pass_signals.size () < 256);
2731 for (size_t i = 0; i < pass_signals.size (); i++)
2733 if (pass_signals[i])
2734 count++;
2736 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
2737 strcpy (pass_packet, "QPassSignals:");
2738 p = pass_packet + strlen (pass_packet);
2739 for (size_t i = 0; i < pass_signals.size (); i++)
2741 if (pass_signals[i])
2743 if (i >= 16)
2744 *p++ = tohex (i >> 4);
2745 *p++ = tohex (i & 15);
2746 if (count)
2747 *p++ = ';';
2748 else
2749 break;
2750 count--;
2753 *p = 0;
2754 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
2756 putpkt (pass_packet);
2757 getpkt (&rs->buf, 0);
2758 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
2759 xfree (rs->last_pass_packet);
2760 rs->last_pass_packet = pass_packet;
2762 else
2763 xfree (pass_packet);
2767 /* If 'QCatchSyscalls' is supported, tell the remote stub
2768 to report syscalls to GDB. */
2771 remote_target::set_syscall_catchpoint (int pid, bool needed, int any_count,
2772 gdb::array_view<const int> syscall_counts)
2774 const char *catch_packet;
2775 enum packet_result result;
2776 int n_sysno = 0;
2778 if (packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2780 /* Not supported. */
2781 return 1;
2784 if (needed && any_count == 0)
2786 /* Count how many syscalls are to be caught. */
2787 for (size_t i = 0; i < syscall_counts.size (); i++)
2789 if (syscall_counts[i] != 0)
2790 n_sysno++;
2794 remote_debug_printf ("pid %d needed %d any_count %d n_sysno %d",
2795 pid, needed, any_count, n_sysno);
2797 std::string built_packet;
2798 if (needed)
2800 /* Prepare a packet with the sysno list, assuming max 8+1
2801 characters for a sysno. If the resulting packet size is too
2802 big, fallback on the non-selective packet. */
2803 const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
2804 built_packet.reserve (maxpktsz);
2805 built_packet = "QCatchSyscalls:1";
2806 if (any_count == 0)
2808 /* Add in each syscall to be caught. */
2809 for (size_t i = 0; i < syscall_counts.size (); i++)
2811 if (syscall_counts[i] != 0)
2812 string_appendf (built_packet, ";%zx", i);
2815 if (built_packet.size () > get_remote_packet_size ())
2817 /* catch_packet too big. Fallback to less efficient
2818 non selective mode, with GDB doing the filtering. */
2819 catch_packet = "QCatchSyscalls:1";
2821 else
2822 catch_packet = built_packet.c_str ();
2824 else
2825 catch_packet = "QCatchSyscalls:0";
2827 struct remote_state *rs = get_remote_state ();
2829 putpkt (catch_packet);
2830 getpkt (&rs->buf, 0);
2831 result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_QCatchSyscalls]);
2832 if (result == PACKET_OK)
2833 return 0;
2834 else
2835 return -1;
2838 /* If 'QProgramSignals' is supported, tell the remote stub what
2839 signals it should pass through to the inferior when detaching. */
2841 void
2842 remote_target::program_signals (gdb::array_view<const unsigned char> signals)
2844 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
2846 char *packet, *p;
2847 int count = 0;
2848 struct remote_state *rs = get_remote_state ();
2850 gdb_assert (signals.size () < 256);
2851 for (size_t i = 0; i < signals.size (); i++)
2853 if (signals[i])
2854 count++;
2856 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
2857 strcpy (packet, "QProgramSignals:");
2858 p = packet + strlen (packet);
2859 for (size_t i = 0; i < signals.size (); i++)
2861 if (signal_pass_state (i))
2863 if (i >= 16)
2864 *p++ = tohex (i >> 4);
2865 *p++ = tohex (i & 15);
2866 if (count)
2867 *p++ = ';';
2868 else
2869 break;
2870 count--;
2873 *p = 0;
2874 if (!rs->last_program_signals_packet
2875 || strcmp (rs->last_program_signals_packet, packet) != 0)
2877 putpkt (packet);
2878 getpkt (&rs->buf, 0);
2879 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
2880 xfree (rs->last_program_signals_packet);
2881 rs->last_program_signals_packet = packet;
2883 else
2884 xfree (packet);
2888 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
2889 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2890 thread. If GEN is set, set the general thread, if not, then set
2891 the step/continue thread. */
2892 void
2893 remote_target::set_thread (ptid_t ptid, int gen)
2895 struct remote_state *rs = get_remote_state ();
2896 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
2897 char *buf = rs->buf.data ();
2898 char *endbuf = buf + get_remote_packet_size ();
2900 if (state == ptid)
2901 return;
2903 *buf++ = 'H';
2904 *buf++ = gen ? 'g' : 'c';
2905 if (ptid == magic_null_ptid)
2906 xsnprintf (buf, endbuf - buf, "0");
2907 else if (ptid == any_thread_ptid)
2908 xsnprintf (buf, endbuf - buf, "0");
2909 else if (ptid == minus_one_ptid)
2910 xsnprintf (buf, endbuf - buf, "-1");
2911 else
2912 write_ptid (buf, endbuf, ptid);
2913 putpkt (rs->buf);
2914 getpkt (&rs->buf, 0);
2915 if (gen)
2916 rs->general_thread = ptid;
2917 else
2918 rs->continue_thread = ptid;
2921 void
2922 remote_target::set_general_thread (ptid_t ptid)
2924 set_thread (ptid, 1);
2927 void
2928 remote_target::set_continue_thread (ptid_t ptid)
2930 set_thread (ptid, 0);
2933 /* Change the remote current process. Which thread within the process
2934 ends up selected isn't important, as long as it is the same process
2935 as what INFERIOR_PTID points to.
2937 This comes from that fact that there is no explicit notion of
2938 "selected process" in the protocol. The selected process for
2939 general operations is the process the selected general thread
2940 belongs to. */
2942 void
2943 remote_target::set_general_process ()
2945 struct remote_state *rs = get_remote_state ();
2947 /* If the remote can't handle multiple processes, don't bother. */
2948 if (!remote_multi_process_p (rs))
2949 return;
2951 /* We only need to change the remote current thread if it's pointing
2952 at some other process. */
2953 if (rs->general_thread.pid () != inferior_ptid.pid ())
2954 set_general_thread (inferior_ptid);
2958 /* Return nonzero if this is the main thread that we made up ourselves
2959 to model non-threaded targets as single-threaded. */
2961 static int
2962 remote_thread_always_alive (ptid_t ptid)
2964 if (ptid == magic_null_ptid)
2965 /* The main thread is always alive. */
2966 return 1;
2968 if (ptid.pid () != 0 && ptid.lwp () == 0)
2969 /* The main thread is always alive. This can happen after a
2970 vAttach, if the remote side doesn't support
2971 multi-threading. */
2972 return 1;
2974 return 0;
2977 /* Return nonzero if the thread PTID is still alive on the remote
2978 system. */
2980 bool
2981 remote_target::thread_alive (ptid_t ptid)
2983 struct remote_state *rs = get_remote_state ();
2984 char *p, *endp;
2986 /* Check if this is a thread that we made up ourselves to model
2987 non-threaded targets as single-threaded. */
2988 if (remote_thread_always_alive (ptid))
2989 return 1;
2991 p = rs->buf.data ();
2992 endp = p + get_remote_packet_size ();
2994 *p++ = 'T';
2995 write_ptid (p, endp, ptid);
2997 putpkt (rs->buf);
2998 getpkt (&rs->buf, 0);
2999 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
3002 /* Return a pointer to a thread name if we know it and NULL otherwise.
3003 The thread_info object owns the memory for the name. */
3005 const char *
3006 remote_target::thread_name (struct thread_info *info)
3008 if (info->priv != NULL)
3010 const std::string &name = get_remote_thread_info (info)->name;
3011 return !name.empty () ? name.c_str () : NULL;
3014 return NULL;
3017 /* About these extended threadlist and threadinfo packets. They are
3018 variable length packets but, the fields within them are often fixed
3019 length. They are redundant enough to send over UDP as is the
3020 remote protocol in general. There is a matching unit test module
3021 in libstub. */
3023 /* WARNING: This threadref data structure comes from the remote O.S.,
3024 libstub protocol encoding, and remote.c. It is not particularly
3025 changable. */
3027 /* Right now, the internal structure is int. We want it to be bigger.
3028 Plan to fix this. */
3030 typedef int gdb_threadref; /* Internal GDB thread reference. */
3032 /* gdb_ext_thread_info is an internal GDB data structure which is
3033 equivalent to the reply of the remote threadinfo packet. */
3035 struct gdb_ext_thread_info
3037 threadref threadid; /* External form of thread reference. */
3038 int active; /* Has state interesting to GDB?
3039 regs, stack. */
3040 char display[256]; /* Brief state display, name,
3041 blocked/suspended. */
3042 char shortname[32]; /* To be used to name threads. */
3043 char more_display[256]; /* Long info, statistics, queue depth,
3044 whatever. */
3047 /* The volume of remote transfers can be limited by submitting
3048 a mask containing bits specifying the desired information.
3049 Use a union of these values as the 'selection' parameter to
3050 get_thread_info. FIXME: Make these TAG names more thread specific. */
3052 #define TAG_THREADID 1
3053 #define TAG_EXISTS 2
3054 #define TAG_DISPLAY 4
3055 #define TAG_THREADNAME 8
3056 #define TAG_MOREDISPLAY 16
3058 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
3060 static const char *unpack_nibble (const char *buf, int *val);
3062 static const char *unpack_byte (const char *buf, int *value);
3064 static char *pack_int (char *buf, int value);
3066 static const char *unpack_int (const char *buf, int *value);
3068 static const char *unpack_string (const char *src, char *dest, int length);
3070 static char *pack_threadid (char *pkt, threadref *id);
3072 static const char *unpack_threadid (const char *inbuf, threadref *id);
3074 void int_to_threadref (threadref *id, int value);
3076 static int threadref_to_int (threadref *ref);
3078 static void copy_threadref (threadref *dest, threadref *src);
3080 static int threadmatch (threadref *dest, threadref *src);
3082 static char *pack_threadinfo_request (char *pkt, int mode,
3083 threadref *id);
3085 static char *pack_threadlist_request (char *pkt, int startflag,
3086 int threadcount,
3087 threadref *nextthread);
3089 static int remote_newthread_step (threadref *ref, void *context);
3092 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
3093 buffer we're allowed to write to. Returns
3094 BUF+CHARACTERS_WRITTEN. */
3096 char *
3097 remote_target::write_ptid (char *buf, const char *endbuf, ptid_t ptid)
3099 int pid, tid;
3100 struct remote_state *rs = get_remote_state ();
3102 if (remote_multi_process_p (rs))
3104 pid = ptid.pid ();
3105 if (pid < 0)
3106 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
3107 else
3108 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
3110 tid = ptid.lwp ();
3111 if (tid < 0)
3112 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
3113 else
3114 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
3116 return buf;
3119 /* Extract a PTID from BUF. If non-null, OBUF is set to one past the
3120 last parsed char. Returns null_ptid if no thread id is found, and
3121 throws an error if the thread id has an invalid format. */
3123 static ptid_t
3124 read_ptid (const char *buf, const char **obuf)
3126 const char *p = buf;
3127 const char *pp;
3128 ULONGEST pid = 0, tid = 0;
3130 if (*p == 'p')
3132 /* Multi-process ptid. */
3133 pp = unpack_varlen_hex (p + 1, &pid);
3134 if (*pp != '.')
3135 error (_("invalid remote ptid: %s"), p);
3137 p = pp;
3138 pp = unpack_varlen_hex (p + 1, &tid);
3139 if (obuf)
3140 *obuf = pp;
3141 return ptid_t (pid, tid);
3144 /* No multi-process. Just a tid. */
3145 pp = unpack_varlen_hex (p, &tid);
3147 /* Return null_ptid when no thread id is found. */
3148 if (p == pp)
3150 if (obuf)
3151 *obuf = pp;
3152 return null_ptid;
3155 /* Since the stub is not sending a process id, default to what's
3156 current_inferior, unless it doesn't have a PID yet. If so,
3157 then since there's no way to know the pid of the reported
3158 threads, use the magic number. */
3159 inferior *inf = current_inferior ();
3160 if (inf->pid == 0)
3161 pid = magic_null_ptid.pid ();
3162 else
3163 pid = inf->pid;
3165 if (obuf)
3166 *obuf = pp;
3167 return ptid_t (pid, tid);
3170 static int
3171 stubhex (int ch)
3173 if (ch >= 'a' && ch <= 'f')
3174 return ch - 'a' + 10;
3175 if (ch >= '0' && ch <= '9')
3176 return ch - '0';
3177 if (ch >= 'A' && ch <= 'F')
3178 return ch - 'A' + 10;
3179 return -1;
3182 static int
3183 stub_unpack_int (const char *buff, int fieldlength)
3185 int nibble;
3186 int retval = 0;
3188 while (fieldlength)
3190 nibble = stubhex (*buff++);
3191 retval |= nibble;
3192 fieldlength--;
3193 if (fieldlength)
3194 retval = retval << 4;
3196 return retval;
3199 static const char *
3200 unpack_nibble (const char *buf, int *val)
3202 *val = fromhex (*buf++);
3203 return buf;
3206 static const char *
3207 unpack_byte (const char *buf, int *value)
3209 *value = stub_unpack_int (buf, 2);
3210 return buf + 2;
3213 static char *
3214 pack_int (char *buf, int value)
3216 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
3217 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
3218 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
3219 buf = pack_hex_byte (buf, (value & 0xff));
3220 return buf;
3223 static const char *
3224 unpack_int (const char *buf, int *value)
3226 *value = stub_unpack_int (buf, 8);
3227 return buf + 8;
3230 #if 0 /* Currently unused, uncomment when needed. */
3231 static char *pack_string (char *pkt, char *string);
3233 static char *
3234 pack_string (char *pkt, char *string)
3236 char ch;
3237 int len;
3239 len = strlen (string);
3240 if (len > 200)
3241 len = 200; /* Bigger than most GDB packets, junk??? */
3242 pkt = pack_hex_byte (pkt, len);
3243 while (len-- > 0)
3245 ch = *string++;
3246 if ((ch == '\0') || (ch == '#'))
3247 ch = '*'; /* Protect encapsulation. */
3248 *pkt++ = ch;
3250 return pkt;
3252 #endif /* 0 (unused) */
3254 static const char *
3255 unpack_string (const char *src, char *dest, int length)
3257 while (length--)
3258 *dest++ = *src++;
3259 *dest = '\0';
3260 return src;
3263 static char *
3264 pack_threadid (char *pkt, threadref *id)
3266 char *limit;
3267 unsigned char *altid;
3269 altid = (unsigned char *) id;
3270 limit = pkt + BUF_THREAD_ID_SIZE;
3271 while (pkt < limit)
3272 pkt = pack_hex_byte (pkt, *altid++);
3273 return pkt;
3277 static const char *
3278 unpack_threadid (const char *inbuf, threadref *id)
3280 char *altref;
3281 const char *limit = inbuf + BUF_THREAD_ID_SIZE;
3282 int x, y;
3284 altref = (char *) id;
3286 while (inbuf < limit)
3288 x = stubhex (*inbuf++);
3289 y = stubhex (*inbuf++);
3290 *altref++ = (x << 4) | y;
3292 return inbuf;
3295 /* Externally, threadrefs are 64 bits but internally, they are still
3296 ints. This is due to a mismatch of specifications. We would like
3297 to use 64bit thread references internally. This is an adapter
3298 function. */
3300 void
3301 int_to_threadref (threadref *id, int value)
3303 unsigned char *scan;
3305 scan = (unsigned char *) id;
3307 int i = 4;
3308 while (i--)
3309 *scan++ = 0;
3311 *scan++ = (value >> 24) & 0xff;
3312 *scan++ = (value >> 16) & 0xff;
3313 *scan++ = (value >> 8) & 0xff;
3314 *scan++ = (value & 0xff);
3317 static int
3318 threadref_to_int (threadref *ref)
3320 int i, value = 0;
3321 unsigned char *scan;
3323 scan = *ref;
3324 scan += 4;
3325 i = 4;
3326 while (i-- > 0)
3327 value = (value << 8) | ((*scan++) & 0xff);
3328 return value;
3331 static void
3332 copy_threadref (threadref *dest, threadref *src)
3334 int i;
3335 unsigned char *csrc, *cdest;
3337 csrc = (unsigned char *) src;
3338 cdest = (unsigned char *) dest;
3339 i = 8;
3340 while (i--)
3341 *cdest++ = *csrc++;
3344 static int
3345 threadmatch (threadref *dest, threadref *src)
3347 /* Things are broken right now, so just assume we got a match. */
3348 #if 0
3349 unsigned char *srcp, *destp;
3350 int i, result;
3351 srcp = (char *) src;
3352 destp = (char *) dest;
3354 result = 1;
3355 while (i-- > 0)
3356 result &= (*srcp++ == *destp++) ? 1 : 0;
3357 return result;
3358 #endif
3359 return 1;
3363 threadid:1, # always request threadid
3364 context_exists:2,
3365 display:4,
3366 unique_name:8,
3367 more_display:16
3370 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
3372 static char *
3373 pack_threadinfo_request (char *pkt, int mode, threadref *id)
3375 *pkt++ = 'q'; /* Info Query */
3376 *pkt++ = 'P'; /* process or thread info */
3377 pkt = pack_int (pkt, mode); /* mode */
3378 pkt = pack_threadid (pkt, id); /* threadid */
3379 *pkt = '\0'; /* terminate */
3380 return pkt;
3383 /* These values tag the fields in a thread info response packet. */
3384 /* Tagging the fields allows us to request specific fields and to
3385 add more fields as time goes by. */
3387 #define TAG_THREADID 1 /* Echo the thread identifier. */
3388 #define TAG_EXISTS 2 /* Is this process defined enough to
3389 fetch registers and its stack? */
3390 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
3391 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
3392 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
3393 the process. */
3396 remote_target::remote_unpack_thread_info_response (const char *pkt,
3397 threadref *expectedref,
3398 gdb_ext_thread_info *info)
3400 struct remote_state *rs = get_remote_state ();
3401 int mask, length;
3402 int tag;
3403 threadref ref;
3404 const char *limit = pkt + rs->buf.size (); /* Plausible parsing limit. */
3405 int retval = 1;
3407 /* info->threadid = 0; FIXME: implement zero_threadref. */
3408 info->active = 0;
3409 info->display[0] = '\0';
3410 info->shortname[0] = '\0';
3411 info->more_display[0] = '\0';
3413 /* Assume the characters indicating the packet type have been
3414 stripped. */
3415 pkt = unpack_int (pkt, &mask); /* arg mask */
3416 pkt = unpack_threadid (pkt, &ref);
3418 if (mask == 0)
3419 warning (_("Incomplete response to threadinfo request."));
3420 if (!threadmatch (&ref, expectedref))
3421 { /* This is an answer to a different request. */
3422 warning (_("ERROR RMT Thread info mismatch."));
3423 return 0;
3425 copy_threadref (&info->threadid, &ref);
3427 /* Loop on tagged fields , try to bail if something goes wrong. */
3429 /* Packets are terminated with nulls. */
3430 while ((pkt < limit) && mask && *pkt)
3432 pkt = unpack_int (pkt, &tag); /* tag */
3433 pkt = unpack_byte (pkt, &length); /* length */
3434 if (!(tag & mask)) /* Tags out of synch with mask. */
3436 warning (_("ERROR RMT: threadinfo tag mismatch."));
3437 retval = 0;
3438 break;
3440 if (tag == TAG_THREADID)
3442 if (length != 16)
3444 warning (_("ERROR RMT: length of threadid is not 16."));
3445 retval = 0;
3446 break;
3448 pkt = unpack_threadid (pkt, &ref);
3449 mask = mask & ~TAG_THREADID;
3450 continue;
3452 if (tag == TAG_EXISTS)
3454 info->active = stub_unpack_int (pkt, length);
3455 pkt += length;
3456 mask = mask & ~(TAG_EXISTS);
3457 if (length > 8)
3459 warning (_("ERROR RMT: 'exists' length too long."));
3460 retval = 0;
3461 break;
3463 continue;
3465 if (tag == TAG_THREADNAME)
3467 pkt = unpack_string (pkt, &info->shortname[0], length);
3468 mask = mask & ~TAG_THREADNAME;
3469 continue;
3471 if (tag == TAG_DISPLAY)
3473 pkt = unpack_string (pkt, &info->display[0], length);
3474 mask = mask & ~TAG_DISPLAY;
3475 continue;
3477 if (tag == TAG_MOREDISPLAY)
3479 pkt = unpack_string (pkt, &info->more_display[0], length);
3480 mask = mask & ~TAG_MOREDISPLAY;
3481 continue;
3483 warning (_("ERROR RMT: unknown thread info tag."));
3484 break; /* Not a tag we know about. */
3486 return retval;
3490 remote_target::remote_get_threadinfo (threadref *threadid,
3491 int fieldset,
3492 gdb_ext_thread_info *info)
3494 struct remote_state *rs = get_remote_state ();
3495 int result;
3497 pack_threadinfo_request (rs->buf.data (), fieldset, threadid);
3498 putpkt (rs->buf);
3499 getpkt (&rs->buf, 0);
3501 if (rs->buf[0] == '\0')
3502 return 0;
3504 result = remote_unpack_thread_info_response (&rs->buf[2],
3505 threadid, info);
3506 return result;
3509 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
3511 static char *
3512 pack_threadlist_request (char *pkt, int startflag, int threadcount,
3513 threadref *nextthread)
3515 *pkt++ = 'q'; /* info query packet */
3516 *pkt++ = 'L'; /* Process LIST or threadLIST request */
3517 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
3518 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
3519 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
3520 *pkt = '\0';
3521 return pkt;
3524 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
3527 remote_target::parse_threadlist_response (const char *pkt, int result_limit,
3528 threadref *original_echo,
3529 threadref *resultlist,
3530 int *doneflag)
3532 struct remote_state *rs = get_remote_state ();
3533 int count, resultcount, done;
3535 resultcount = 0;
3536 /* Assume the 'q' and 'M chars have been stripped. */
3537 const char *limit = pkt + (rs->buf.size () - BUF_THREAD_ID_SIZE);
3538 /* done parse past here */
3539 pkt = unpack_byte (pkt, &count); /* count field */
3540 pkt = unpack_nibble (pkt, &done);
3541 /* The first threadid is the argument threadid. */
3542 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
3543 while ((count-- > 0) && (pkt < limit))
3545 pkt = unpack_threadid (pkt, resultlist++);
3546 if (resultcount++ >= result_limit)
3547 break;
3549 if (doneflag)
3550 *doneflag = done;
3551 return resultcount;
3554 /* Fetch the next batch of threads from the remote. Returns -1 if the
3555 qL packet is not supported, 0 on error and 1 on success. */
3558 remote_target::remote_get_threadlist (int startflag, threadref *nextthread,
3559 int result_limit, int *done, int *result_count,
3560 threadref *threadlist)
3562 struct remote_state *rs = get_remote_state ();
3563 int result = 1;
3565 /* Truncate result limit to be smaller than the packet size. */
3566 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
3567 >= get_remote_packet_size ())
3568 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
3570 pack_threadlist_request (rs->buf.data (), startflag, result_limit,
3571 nextthread);
3572 putpkt (rs->buf);
3573 getpkt (&rs->buf, 0);
3574 if (rs->buf[0] == '\0')
3576 /* Packet not supported. */
3577 return -1;
3580 *result_count =
3581 parse_threadlist_response (&rs->buf[2], result_limit,
3582 &rs->echo_nextthread, threadlist, done);
3584 if (!threadmatch (&rs->echo_nextthread, nextthread))
3586 /* FIXME: This is a good reason to drop the packet. */
3587 /* Possibly, there is a duplicate response. */
3588 /* Possibilities :
3589 retransmit immediatly - race conditions
3590 retransmit after timeout - yes
3591 exit
3592 wait for packet, then exit
3594 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
3595 return 0; /* I choose simply exiting. */
3597 if (*result_count <= 0)
3599 if (*done != 1)
3601 warning (_("RMT ERROR : failed to get remote thread list."));
3602 result = 0;
3604 return result; /* break; */
3606 if (*result_count > result_limit)
3608 *result_count = 0;
3609 warning (_("RMT ERROR: threadlist response longer than requested."));
3610 return 0;
3612 return result;
3615 /* Fetch the list of remote threads, with the qL packet, and call
3616 STEPFUNCTION for each thread found. Stops iterating and returns 1
3617 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
3618 STEPFUNCTION returns false. If the packet is not supported,
3619 returns -1. */
3622 remote_target::remote_threadlist_iterator (rmt_thread_action stepfunction,
3623 void *context, int looplimit)
3625 struct remote_state *rs = get_remote_state ();
3626 int done, i, result_count;
3627 int startflag = 1;
3628 int result = 1;
3629 int loopcount = 0;
3631 done = 0;
3632 while (!done)
3634 if (loopcount++ > looplimit)
3636 result = 0;
3637 warning (_("Remote fetch threadlist -infinite loop-."));
3638 break;
3640 result = remote_get_threadlist (startflag, &rs->nextthread,
3641 MAXTHREADLISTRESULTS,
3642 &done, &result_count,
3643 rs->resultthreadlist);
3644 if (result <= 0)
3645 break;
3646 /* Clear for later iterations. */
3647 startflag = 0;
3648 /* Setup to resume next batch of thread references, set nextthread. */
3649 if (result_count >= 1)
3650 copy_threadref (&rs->nextthread,
3651 &rs->resultthreadlist[result_count - 1]);
3652 i = 0;
3653 while (result_count--)
3655 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
3657 result = 0;
3658 break;
3662 return result;
3665 /* A thread found on the remote target. */
3667 struct thread_item
3669 explicit thread_item (ptid_t ptid_)
3670 : ptid (ptid_)
3673 thread_item (thread_item &&other) = default;
3674 thread_item &operator= (thread_item &&other) = default;
3676 DISABLE_COPY_AND_ASSIGN (thread_item);
3678 /* The thread's PTID. */
3679 ptid_t ptid;
3681 /* The thread's extra info. */
3682 std::string extra;
3684 /* The thread's name. */
3685 std::string name;
3687 /* The core the thread was running on. -1 if not known. */
3688 int core = -1;
3690 /* The thread handle associated with the thread. */
3691 gdb::byte_vector thread_handle;
3694 /* Context passed around to the various methods listing remote
3695 threads. As new threads are found, they're added to the ITEMS
3696 vector. */
3698 struct threads_listing_context
3700 /* Return true if this object contains an entry for a thread with ptid
3701 PTID. */
3703 bool contains_thread (ptid_t ptid) const
3705 auto match_ptid = [&] (const thread_item &item)
3707 return item.ptid == ptid;
3710 auto it = std::find_if (this->items.begin (),
3711 this->items.end (),
3712 match_ptid);
3714 return it != this->items.end ();
3717 /* Remove the thread with ptid PTID. */
3719 void remove_thread (ptid_t ptid)
3721 auto match_ptid = [&] (const thread_item &item)
3723 return item.ptid == ptid;
3726 auto it = std::remove_if (this->items.begin (),
3727 this->items.end (),
3728 match_ptid);
3730 if (it != this->items.end ())
3731 this->items.erase (it);
3734 /* The threads found on the remote target. */
3735 std::vector<thread_item> items;
3738 static int
3739 remote_newthread_step (threadref *ref, void *data)
3741 struct threads_listing_context *context
3742 = (struct threads_listing_context *) data;
3743 int pid = inferior_ptid.pid ();
3744 int lwp = threadref_to_int (ref);
3745 ptid_t ptid (pid, lwp);
3747 context->items.emplace_back (ptid);
3749 return 1; /* continue iterator */
3752 #define CRAZY_MAX_THREADS 1000
3754 ptid_t
3755 remote_target::remote_current_thread (ptid_t oldpid)
3757 struct remote_state *rs = get_remote_state ();
3759 putpkt ("qC");
3760 getpkt (&rs->buf, 0);
3761 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
3763 const char *obuf;
3764 ptid_t result;
3766 result = read_ptid (&rs->buf[2], &obuf);
3767 if (*obuf != '\0')
3768 remote_debug_printf ("warning: garbage in qC reply");
3770 return result;
3772 else
3773 return oldpid;
3776 /* List remote threads using the deprecated qL packet. */
3779 remote_target::remote_get_threads_with_ql (threads_listing_context *context)
3781 if (remote_threadlist_iterator (remote_newthread_step, context,
3782 CRAZY_MAX_THREADS) >= 0)
3783 return 1;
3785 return 0;
3788 #if defined(HAVE_LIBEXPAT)
3790 static void
3791 start_thread (struct gdb_xml_parser *parser,
3792 const struct gdb_xml_element *element,
3793 void *user_data,
3794 std::vector<gdb_xml_value> &attributes)
3796 struct threads_listing_context *data
3797 = (struct threads_listing_context *) user_data;
3798 struct gdb_xml_value *attr;
3800 char *id = (char *) xml_find_attribute (attributes, "id")->value.get ();
3801 ptid_t ptid = read_ptid (id, NULL);
3803 data->items.emplace_back (ptid);
3804 thread_item &item = data->items.back ();
3806 attr = xml_find_attribute (attributes, "core");
3807 if (attr != NULL)
3808 item.core = *(ULONGEST *) attr->value.get ();
3810 attr = xml_find_attribute (attributes, "name");
3811 if (attr != NULL)
3812 item.name = (const char *) attr->value.get ();
3814 attr = xml_find_attribute (attributes, "handle");
3815 if (attr != NULL)
3816 item.thread_handle = hex2bin ((const char *) attr->value.get ());
3819 static void
3820 end_thread (struct gdb_xml_parser *parser,
3821 const struct gdb_xml_element *element,
3822 void *user_data, const char *body_text)
3824 struct threads_listing_context *data
3825 = (struct threads_listing_context *) user_data;
3827 if (body_text != NULL && *body_text != '\0')
3828 data->items.back ().extra = body_text;
3831 const struct gdb_xml_attribute thread_attributes[] = {
3832 { "id", GDB_XML_AF_NONE, NULL, NULL },
3833 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
3834 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
3835 { "handle", GDB_XML_AF_OPTIONAL, NULL, NULL },
3836 { NULL, GDB_XML_AF_NONE, NULL, NULL }
3839 const struct gdb_xml_element thread_children[] = {
3840 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3843 const struct gdb_xml_element threads_children[] = {
3844 { "thread", thread_attributes, thread_children,
3845 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3846 start_thread, end_thread },
3847 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3850 const struct gdb_xml_element threads_elements[] = {
3851 { "threads", NULL, threads_children,
3852 GDB_XML_EF_NONE, NULL, NULL },
3853 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3856 #endif
3858 /* List remote threads using qXfer:threads:read. */
3861 remote_target::remote_get_threads_with_qxfer (threads_listing_context *context)
3863 #if defined(HAVE_LIBEXPAT)
3864 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3866 gdb::optional<gdb::char_vector> xml
3867 = target_read_stralloc (this, TARGET_OBJECT_THREADS, NULL);
3869 if (xml && (*xml)[0] != '\0')
3871 gdb_xml_parse_quick (_("threads"), "threads.dtd",
3872 threads_elements, xml->data (), context);
3875 return 1;
3877 #endif
3879 return 0;
3882 /* List remote threads using qfThreadInfo/qsThreadInfo. */
3885 remote_target::remote_get_threads_with_qthreadinfo (threads_listing_context *context)
3887 struct remote_state *rs = get_remote_state ();
3889 if (rs->use_threadinfo_query)
3891 const char *bufp;
3893 putpkt ("qfThreadInfo");
3894 getpkt (&rs->buf, 0);
3895 bufp = rs->buf.data ();
3896 if (bufp[0] != '\0') /* q packet recognized */
3898 while (*bufp++ == 'm') /* reply contains one or more TID */
3902 ptid_t ptid = read_ptid (bufp, &bufp);
3903 context->items.emplace_back (ptid);
3905 while (*bufp++ == ','); /* comma-separated list */
3906 putpkt ("qsThreadInfo");
3907 getpkt (&rs->buf, 0);
3908 bufp = rs->buf.data ();
3910 return 1;
3912 else
3914 /* Packet not recognized. */
3915 rs->use_threadinfo_query = 0;
3919 return 0;
3922 /* Return true if INF only has one non-exited thread. */
3924 static bool
3925 has_single_non_exited_thread (inferior *inf)
3927 int count = 0;
3928 for (thread_info *tp ATTRIBUTE_UNUSED : inf->non_exited_threads ())
3929 if (++count > 1)
3930 break;
3931 return count == 1;
3934 /* Implement the to_update_thread_list function for the remote
3935 targets. */
3937 void
3938 remote_target::update_thread_list ()
3940 struct threads_listing_context context;
3941 int got_list = 0;
3943 /* We have a few different mechanisms to fetch the thread list. Try
3944 them all, starting with the most preferred one first, falling
3945 back to older methods. */
3946 if (remote_get_threads_with_qxfer (&context)
3947 || remote_get_threads_with_qthreadinfo (&context)
3948 || remote_get_threads_with_ql (&context))
3950 got_list = 1;
3952 if (context.items.empty ()
3953 && remote_thread_always_alive (inferior_ptid))
3955 /* Some targets don't really support threads, but still
3956 reply an (empty) thread list in response to the thread
3957 listing packets, instead of replying "packet not
3958 supported". Exit early so we don't delete the main
3959 thread. */
3960 return;
3963 /* CONTEXT now holds the current thread list on the remote
3964 target end. Delete GDB-side threads no longer found on the
3965 target. */
3966 for (thread_info *tp : all_threads_safe ())
3968 if (tp->inf->process_target () != this)
3969 continue;
3971 if (!context.contains_thread (tp->ptid))
3973 /* Do not remove the thread if it is the last thread in
3974 the inferior. This situation happens when we have a
3975 pending exit process status to process. Otherwise we
3976 may end up with a seemingly live inferior (i.e. pid
3977 != 0) that has no threads. */
3978 if (has_single_non_exited_thread (tp->inf))
3979 continue;
3981 /* Not found. */
3982 delete_thread (tp);
3986 /* Remove any unreported fork child threads from CONTEXT so
3987 that we don't interfere with follow fork, which is where
3988 creation of such threads is handled. */
3989 remove_new_fork_children (&context);
3991 /* And now add threads we don't know about yet to our list. */
3992 for (thread_item &item : context.items)
3994 if (item.ptid != null_ptid)
3996 /* In non-stop mode, we assume new found threads are
3997 executing until proven otherwise with a stop reply.
3998 In all-stop, we can only get here if all threads are
3999 stopped. */
4000 bool executing = target_is_non_stop_p ();
4002 remote_notice_new_inferior (item.ptid, executing);
4004 thread_info *tp = find_thread_ptid (this, item.ptid);
4005 remote_thread_info *info = get_remote_thread_info (tp);
4006 info->core = item.core;
4007 info->extra = std::move (item.extra);
4008 info->name = std::move (item.name);
4009 info->thread_handle = std::move (item.thread_handle);
4014 if (!got_list)
4016 /* If no thread listing method is supported, then query whether
4017 each known thread is alive, one by one, with the T packet.
4018 If the target doesn't support threads at all, then this is a
4019 no-op. See remote_thread_alive. */
4020 prune_threads ();
4025 * Collect a descriptive string about the given thread.
4026 * The target may say anything it wants to about the thread
4027 * (typically info about its blocked / runnable state, name, etc.).
4028 * This string will appear in the info threads display.
4030 * Optional: targets are not required to implement this function.
4033 const char *
4034 remote_target::extra_thread_info (thread_info *tp)
4036 struct remote_state *rs = get_remote_state ();
4037 int set;
4038 threadref id;
4039 struct gdb_ext_thread_info threadinfo;
4041 if (rs->remote_desc == 0) /* paranoia */
4042 internal_error (_("remote_threads_extra_info"));
4044 if (tp->ptid == magic_null_ptid
4045 || (tp->ptid.pid () != 0 && tp->ptid.lwp () == 0))
4046 /* This is the main thread which was added by GDB. The remote
4047 server doesn't know about it. */
4048 return NULL;
4050 std::string &extra = get_remote_thread_info (tp)->extra;
4052 /* If already have cached info, use it. */
4053 if (!extra.empty ())
4054 return extra.c_str ();
4056 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
4058 /* If we're using qXfer:threads:read, then the extra info is
4059 included in the XML. So if we didn't have anything cached,
4060 it's because there's really no extra info. */
4061 return NULL;
4064 if (rs->use_threadextra_query)
4066 char *b = rs->buf.data ();
4067 char *endb = b + get_remote_packet_size ();
4069 xsnprintf (b, endb - b, "qThreadExtraInfo,");
4070 b += strlen (b);
4071 write_ptid (b, endb, tp->ptid);
4073 putpkt (rs->buf);
4074 getpkt (&rs->buf, 0);
4075 if (rs->buf[0] != 0)
4077 extra.resize (strlen (rs->buf.data ()) / 2);
4078 hex2bin (rs->buf.data (), (gdb_byte *) &extra[0], extra.size ());
4079 return extra.c_str ();
4083 /* If the above query fails, fall back to the old method. */
4084 rs->use_threadextra_query = 0;
4085 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
4086 | TAG_MOREDISPLAY | TAG_DISPLAY;
4087 int_to_threadref (&id, tp->ptid.lwp ());
4088 if (remote_get_threadinfo (&id, set, &threadinfo))
4089 if (threadinfo.active)
4091 if (*threadinfo.shortname)
4092 string_appendf (extra, " Name: %s", threadinfo.shortname);
4093 if (*threadinfo.display)
4095 if (!extra.empty ())
4096 extra += ',';
4097 string_appendf (extra, " State: %s", threadinfo.display);
4099 if (*threadinfo.more_display)
4101 if (!extra.empty ())
4102 extra += ',';
4103 string_appendf (extra, " Priority: %s", threadinfo.more_display);
4105 return extra.c_str ();
4107 return NULL;
4111 bool
4112 remote_target::static_tracepoint_marker_at (CORE_ADDR addr,
4113 struct static_tracepoint_marker *marker)
4115 struct remote_state *rs = get_remote_state ();
4116 char *p = rs->buf.data ();
4118 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
4119 p += strlen (p);
4120 p += hexnumstr (p, addr);
4121 putpkt (rs->buf);
4122 getpkt (&rs->buf, 0);
4123 p = rs->buf.data ();
4125 if (*p == 'E')
4126 error (_("Remote failure reply: %s"), p);
4128 if (*p++ == 'm')
4130 parse_static_tracepoint_marker_definition (p, NULL, marker);
4131 return true;
4134 return false;
4137 std::vector<static_tracepoint_marker>
4138 remote_target::static_tracepoint_markers_by_strid (const char *strid)
4140 struct remote_state *rs = get_remote_state ();
4141 std::vector<static_tracepoint_marker> markers;
4142 const char *p;
4143 static_tracepoint_marker marker;
4145 /* Ask for a first packet of static tracepoint marker
4146 definition. */
4147 putpkt ("qTfSTM");
4148 getpkt (&rs->buf, 0);
4149 p = rs->buf.data ();
4150 if (*p == 'E')
4151 error (_("Remote failure reply: %s"), p);
4153 while (*p++ == 'm')
4157 parse_static_tracepoint_marker_definition (p, &p, &marker);
4159 if (strid == NULL || marker.str_id == strid)
4160 markers.push_back (std::move (marker));
4162 while (*p++ == ','); /* comma-separated list */
4163 /* Ask for another packet of static tracepoint definition. */
4164 putpkt ("qTsSTM");
4165 getpkt (&rs->buf, 0);
4166 p = rs->buf.data ();
4169 return markers;
4173 /* Implement the to_get_ada_task_ptid function for the remote targets. */
4175 ptid_t
4176 remote_target::get_ada_task_ptid (long lwp, ULONGEST thread)
4178 return ptid_t (inferior_ptid.pid (), lwp);
4182 /* Restart the remote side; this is an extended protocol operation. */
4184 void
4185 remote_target::extended_remote_restart ()
4187 struct remote_state *rs = get_remote_state ();
4189 /* Send the restart command; for reasons I don't understand the
4190 remote side really expects a number after the "R". */
4191 xsnprintf (rs->buf.data (), get_remote_packet_size (), "R%x", 0);
4192 putpkt (rs->buf);
4194 remote_fileio_reset ();
4197 /* Clean up connection to a remote debugger. */
4199 void
4200 remote_target::close ()
4202 /* Make sure we leave stdin registered in the event loop. */
4203 terminal_ours ();
4205 trace_reset_local_state ();
4207 delete this;
4210 remote_target::~remote_target ()
4212 struct remote_state *rs = get_remote_state ();
4214 /* Check for NULL because we may get here with a partially
4215 constructed target/connection. */
4216 if (rs->remote_desc == nullptr)
4217 return;
4219 serial_close (rs->remote_desc);
4221 /* We are destroying the remote target, so we should discard
4222 everything of this target. */
4223 discard_pending_stop_replies_in_queue ();
4225 if (rs->remote_async_inferior_event_token)
4226 delete_async_event_handler (&rs->remote_async_inferior_event_token);
4228 delete rs->notif_state;
4231 /* Query the remote side for the text, data and bss offsets. */
4233 void
4234 remote_target::get_offsets ()
4236 struct remote_state *rs = get_remote_state ();
4237 char *buf;
4238 char *ptr;
4239 int lose, num_segments = 0, do_sections, do_segments;
4240 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
4242 if (current_program_space->symfile_object_file == NULL)
4243 return;
4245 putpkt ("qOffsets");
4246 getpkt (&rs->buf, 0);
4247 buf = rs->buf.data ();
4249 if (buf[0] == '\000')
4250 return; /* Return silently. Stub doesn't support
4251 this command. */
4252 if (buf[0] == 'E')
4254 warning (_("Remote failure reply: %s"), buf);
4255 return;
4258 /* Pick up each field in turn. This used to be done with scanf, but
4259 scanf will make trouble if CORE_ADDR size doesn't match
4260 conversion directives correctly. The following code will work
4261 with any size of CORE_ADDR. */
4262 text_addr = data_addr = bss_addr = 0;
4263 ptr = buf;
4264 lose = 0;
4266 if (startswith (ptr, "Text="))
4268 ptr += 5;
4269 /* Don't use strtol, could lose on big values. */
4270 while (*ptr && *ptr != ';')
4271 text_addr = (text_addr << 4) + fromhex (*ptr++);
4273 if (startswith (ptr, ";Data="))
4275 ptr += 6;
4276 while (*ptr && *ptr != ';')
4277 data_addr = (data_addr << 4) + fromhex (*ptr++);
4279 else
4280 lose = 1;
4282 if (!lose && startswith (ptr, ";Bss="))
4284 ptr += 5;
4285 while (*ptr && *ptr != ';')
4286 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
4288 if (bss_addr != data_addr)
4289 warning (_("Target reported unsupported offsets: %s"), buf);
4291 else
4292 lose = 1;
4294 else if (startswith (ptr, "TextSeg="))
4296 ptr += 8;
4297 /* Don't use strtol, could lose on big values. */
4298 while (*ptr && *ptr != ';')
4299 text_addr = (text_addr << 4) + fromhex (*ptr++);
4300 num_segments = 1;
4302 if (startswith (ptr, ";DataSeg="))
4304 ptr += 9;
4305 while (*ptr && *ptr != ';')
4306 data_addr = (data_addr << 4) + fromhex (*ptr++);
4307 num_segments++;
4310 else
4311 lose = 1;
4313 if (lose)
4314 error (_("Malformed response to offset query, %s"), buf);
4315 else if (*ptr != '\0')
4316 warning (_("Target reported unsupported offsets: %s"), buf);
4318 objfile *objf = current_program_space->symfile_object_file;
4319 section_offsets offs = objf->section_offsets;
4321 symfile_segment_data_up data = get_symfile_segment_data (objf->obfd.get ());
4322 do_segments = (data != NULL);
4323 do_sections = num_segments == 0;
4325 if (num_segments > 0)
4327 segments[0] = text_addr;
4328 segments[1] = data_addr;
4330 /* If we have two segments, we can still try to relocate everything
4331 by assuming that the .text and .data offsets apply to the whole
4332 text and data segments. Convert the offsets given in the packet
4333 to base addresses for symfile_map_offsets_to_segments. */
4334 else if (data != nullptr && data->segments.size () == 2)
4336 segments[0] = data->segments[0].base + text_addr;
4337 segments[1] = data->segments[1].base + data_addr;
4338 num_segments = 2;
4340 /* If the object file has only one segment, assume that it is text
4341 rather than data; main programs with no writable data are rare,
4342 but programs with no code are useless. Of course the code might
4343 have ended up in the data segment... to detect that we would need
4344 the permissions here. */
4345 else if (data && data->segments.size () == 1)
4347 segments[0] = data->segments[0].base + text_addr;
4348 num_segments = 1;
4350 /* There's no way to relocate by segment. */
4351 else
4352 do_segments = 0;
4354 if (do_segments)
4356 int ret = symfile_map_offsets_to_segments (objf->obfd.get (),
4357 data.get (), offs,
4358 num_segments, segments);
4360 if (ret == 0 && !do_sections)
4361 error (_("Can not handle qOffsets TextSeg "
4362 "response with this symbol file"));
4364 if (ret > 0)
4365 do_sections = 0;
4368 if (do_sections)
4370 offs[SECT_OFF_TEXT (objf)] = text_addr;
4372 /* This is a temporary kludge to force data and bss to use the
4373 same offsets because that's what nlmconv does now. The real
4374 solution requires changes to the stub and remote.c that I
4375 don't have time to do right now. */
4377 offs[SECT_OFF_DATA (objf)] = data_addr;
4378 offs[SECT_OFF_BSS (objf)] = data_addr;
4381 objfile_relocate (objf, offs);
4384 /* Send interrupt_sequence to remote target. */
4386 void
4387 remote_target::send_interrupt_sequence ()
4389 struct remote_state *rs = get_remote_state ();
4391 if (interrupt_sequence_mode == interrupt_sequence_control_c)
4392 remote_serial_write ("\x03", 1);
4393 else if (interrupt_sequence_mode == interrupt_sequence_break)
4394 serial_send_break (rs->remote_desc);
4395 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
4397 serial_send_break (rs->remote_desc);
4398 remote_serial_write ("g", 1);
4400 else
4401 internal_error (_("Invalid value for interrupt_sequence_mode: %s."),
4402 interrupt_sequence_mode);
4406 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
4407 and extract the PTID. Returns NULL_PTID if not found. */
4409 static ptid_t
4410 stop_reply_extract_thread (const char *stop_reply)
4412 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
4414 const char *p;
4416 /* Txx r:val ; r:val (...) */
4417 p = &stop_reply[3];
4419 /* Look for "register" named "thread". */
4420 while (*p != '\0')
4422 const char *p1;
4424 p1 = strchr (p, ':');
4425 if (p1 == NULL)
4426 return null_ptid;
4428 if (strncmp (p, "thread", p1 - p) == 0)
4429 return read_ptid (++p1, &p);
4431 p1 = strchr (p, ';');
4432 if (p1 == NULL)
4433 return null_ptid;
4434 p1++;
4436 p = p1;
4440 return null_ptid;
4443 /* Determine the remote side's current thread. If we have a stop
4444 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
4445 "thread" register we can extract the current thread from. If not,
4446 ask the remote which is the current thread with qC. The former
4447 method avoids a roundtrip. */
4449 ptid_t
4450 remote_target::get_current_thread (const char *wait_status)
4452 ptid_t ptid = null_ptid;
4454 /* Note we don't use remote_parse_stop_reply as that makes use of
4455 the target architecture, which we haven't yet fully determined at
4456 this point. */
4457 if (wait_status != NULL)
4458 ptid = stop_reply_extract_thread (wait_status);
4459 if (ptid == null_ptid)
4460 ptid = remote_current_thread (inferior_ptid);
4462 return ptid;
4465 /* Query the remote target for which is the current thread/process,
4466 add it to our tables, and update INFERIOR_PTID. The caller is
4467 responsible for setting the state such that the remote end is ready
4468 to return the current thread.
4470 This function is called after handling the '?' or 'vRun' packets,
4471 whose response is a stop reply from which we can also try
4472 extracting the thread. If the target doesn't support the explicit
4473 qC query, we infer the current thread from that stop reply, passed
4474 in in WAIT_STATUS, which may be NULL.
4476 The function returns pointer to the main thread of the inferior. */
4478 thread_info *
4479 remote_target::add_current_inferior_and_thread (const char *wait_status)
4481 struct remote_state *rs = get_remote_state ();
4482 bool fake_pid_p = false;
4484 switch_to_no_thread ();
4486 /* Now, if we have thread information, update the current thread's
4487 ptid. */
4488 ptid_t curr_ptid = get_current_thread (wait_status);
4490 if (curr_ptid != null_ptid)
4492 if (!remote_multi_process_p (rs))
4493 fake_pid_p = true;
4495 else
4497 /* Without this, some commands which require an active target
4498 (such as kill) won't work. This variable serves (at least)
4499 double duty as both the pid of the target process (if it has
4500 such), and as a flag indicating that a target is active. */
4501 curr_ptid = magic_null_ptid;
4502 fake_pid_p = true;
4505 remote_add_inferior (fake_pid_p, curr_ptid.pid (), -1, 1);
4507 /* Add the main thread and switch to it. Don't try reading
4508 registers yet, since we haven't fetched the target description
4509 yet. */
4510 thread_info *tp = add_thread_silent (this, curr_ptid);
4511 switch_to_thread_no_regs (tp);
4513 return tp;
4516 /* Print info about a thread that was found already stopped on
4517 connection. */
4519 void
4520 remote_target::print_one_stopped_thread (thread_info *thread)
4522 target_waitstatus ws;
4524 /* If there is a pending waitstatus, use it. If there isn't it's because
4525 the thread's stop was reported with TARGET_WAITKIND_STOPPED / GDB_SIGNAL_0
4526 and process_initial_stop_replies decided it wasn't interesting to save
4527 and report to the core. */
4528 if (thread->has_pending_waitstatus ())
4530 ws = thread->pending_waitstatus ();
4531 thread->clear_pending_waitstatus ();
4533 else
4535 ws.set_stopped (GDB_SIGNAL_0);
4538 switch_to_thread (thread);
4539 thread->set_stop_pc (get_frame_pc (get_current_frame ()));
4540 set_current_sal_from_frame (get_current_frame ());
4542 /* For "info program". */
4543 set_last_target_status (this, thread->ptid, ws);
4545 if (ws.kind () == TARGET_WAITKIND_STOPPED)
4547 enum gdb_signal sig = ws.sig ();
4549 if (signal_print_state (sig))
4550 gdb::observers::signal_received.notify (sig);
4552 gdb::observers::normal_stop.notify (NULL, 1);
4555 /* Process all initial stop replies the remote side sent in response
4556 to the ? packet. These indicate threads that were already stopped
4557 on initial connection. We mark these threads as stopped and print
4558 their current frame before giving the user the prompt. */
4560 void
4561 remote_target::process_initial_stop_replies (int from_tty)
4563 int pending_stop_replies = stop_reply_queue_length ();
4564 struct thread_info *selected = NULL;
4565 struct thread_info *lowest_stopped = NULL;
4566 struct thread_info *first = NULL;
4568 /* This is only used when the target is non-stop. */
4569 gdb_assert (target_is_non_stop_p ());
4571 /* Consume the initial pending events. */
4572 while (pending_stop_replies-- > 0)
4574 ptid_t waiton_ptid = minus_one_ptid;
4575 ptid_t event_ptid;
4576 struct target_waitstatus ws;
4577 int ignore_event = 0;
4579 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
4580 if (remote_debug)
4581 print_target_wait_results (waiton_ptid, event_ptid, ws);
4583 switch (ws.kind ())
4585 case TARGET_WAITKIND_IGNORE:
4586 case TARGET_WAITKIND_NO_RESUMED:
4587 case TARGET_WAITKIND_SIGNALLED:
4588 case TARGET_WAITKIND_EXITED:
4589 /* We shouldn't see these, but if we do, just ignore. */
4590 remote_debug_printf ("event ignored");
4591 ignore_event = 1;
4592 break;
4594 default:
4595 break;
4598 if (ignore_event)
4599 continue;
4601 thread_info *evthread = find_thread_ptid (this, event_ptid);
4603 if (ws.kind () == TARGET_WAITKIND_STOPPED)
4605 enum gdb_signal sig = ws.sig ();
4607 /* Stubs traditionally report SIGTRAP as initial signal,
4608 instead of signal 0. Suppress it. */
4609 if (sig == GDB_SIGNAL_TRAP)
4610 sig = GDB_SIGNAL_0;
4611 evthread->set_stop_signal (sig);
4612 ws.set_stopped (sig);
4615 if (ws.kind () != TARGET_WAITKIND_STOPPED
4616 || ws.sig () != GDB_SIGNAL_0)
4617 evthread->set_pending_waitstatus (ws);
4619 set_executing (this, event_ptid, false);
4620 set_running (this, event_ptid, false);
4621 get_remote_thread_info (evthread)->set_not_resumed ();
4624 /* "Notice" the new inferiors before anything related to
4625 registers/memory. */
4626 for (inferior *inf : all_non_exited_inferiors (this))
4628 inf->needs_setup = true;
4630 if (non_stop)
4632 thread_info *thread = any_live_thread_of_inferior (inf);
4633 notice_new_inferior (thread, thread->state == THREAD_RUNNING,
4634 from_tty);
4638 /* If all-stop on top of non-stop, pause all threads. Note this
4639 records the threads' stop pc, so must be done after "noticing"
4640 the inferiors. */
4641 if (!non_stop)
4644 /* At this point, the remote target is not async. It needs to be for
4645 the poll in stop_all_threads to consider events from it, so enable
4646 it temporarily. */
4647 gdb_assert (!this->is_async_p ());
4648 SCOPE_EXIT { target_async (false); };
4649 target_async (true);
4650 stop_all_threads ("remote connect in all-stop");
4653 /* If all threads of an inferior were already stopped, we
4654 haven't setup the inferior yet. */
4655 for (inferior *inf : all_non_exited_inferiors (this))
4657 if (inf->needs_setup)
4659 thread_info *thread = any_live_thread_of_inferior (inf);
4660 switch_to_thread_no_regs (thread);
4661 setup_inferior (0);
4666 /* Now go over all threads that are stopped, and print their current
4667 frame. If all-stop, then if there's a signalled thread, pick
4668 that as current. */
4669 for (thread_info *thread : all_non_exited_threads (this))
4671 if (first == NULL)
4672 first = thread;
4674 if (!non_stop)
4675 thread->set_running (false);
4676 else if (thread->state != THREAD_STOPPED)
4677 continue;
4679 if (selected == nullptr && thread->has_pending_waitstatus ())
4680 selected = thread;
4682 if (lowest_stopped == NULL
4683 || thread->inf->num < lowest_stopped->inf->num
4684 || thread->per_inf_num < lowest_stopped->per_inf_num)
4685 lowest_stopped = thread;
4687 if (non_stop)
4688 print_one_stopped_thread (thread);
4691 /* In all-stop, we only print the status of one thread, and leave
4692 others with their status pending. */
4693 if (!non_stop)
4695 thread_info *thread = selected;
4696 if (thread == NULL)
4697 thread = lowest_stopped;
4698 if (thread == NULL)
4699 thread = first;
4701 print_one_stopped_thread (thread);
4705 /* Mark a remote_target as starting (by setting the starting_up flag within
4706 its remote_state) for the lifetime of this object. The reference count
4707 on the remote target is temporarily incremented, to prevent the target
4708 being deleted under our feet. */
4710 struct scoped_mark_target_starting
4712 /* Constructor, TARGET is the target to be marked as starting, its
4713 reference count will be incremented. */
4714 scoped_mark_target_starting (remote_target *target)
4715 : m_remote_target (remote_target_ref::new_reference (target)),
4716 m_restore_starting_up (set_starting_up_flag (target))
4717 { /* Nothing. */ }
4719 private:
4721 /* Helper function, set the starting_up flag on TARGET and return an
4722 object which, when it goes out of scope, will restore the previous
4723 value of the starting_up flag. */
4724 static scoped_restore_tmpl<bool>
4725 set_starting_up_flag (remote_target *target)
4727 remote_state *rs = target->get_remote_state ();
4728 gdb_assert (!rs->starting_up);
4729 return make_scoped_restore (&rs->starting_up, true);
4732 /* A gdb::ref_ptr pointer to a remote_target. */
4733 using remote_target_ref = gdb::ref_ptr<remote_target, target_ops_ref_policy>;
4735 /* A reference to the target on which we are operating. */
4736 remote_target_ref m_remote_target;
4738 /* An object which restores the previous value of the starting_up flag
4739 when it goes out of scope. */
4740 scoped_restore_tmpl<bool> m_restore_starting_up;
4743 /* Helper for remote_target::start_remote, start the remote connection and
4744 sync state. Return true if everything goes OK, otherwise, return false.
4745 This function exists so that the scoped_restore created within it will
4746 expire before we return to remote_target::start_remote. */
4748 bool
4749 remote_target::start_remote_1 (int from_tty, int extended_p)
4751 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
4753 struct remote_state *rs = get_remote_state ();
4754 struct packet_config *noack_config;
4756 /* Signal other parts that we're going through the initial setup,
4757 and so things may not be stable yet. E.g., we don't try to
4758 install tracepoints until we've relocated symbols. Also, a
4759 Ctrl-C before we're connected and synced up can't interrupt the
4760 target. Instead, it offers to drop the (potentially wedged)
4761 connection. */
4762 scoped_mark_target_starting target_is_starting (this);
4764 QUIT;
4766 if (interrupt_on_connect)
4767 send_interrupt_sequence ();
4769 /* Ack any packet which the remote side has already sent. */
4770 remote_serial_write ("+", 1);
4772 /* The first packet we send to the target is the optional "supported
4773 packets" request. If the target can answer this, it will tell us
4774 which later probes to skip. */
4775 remote_query_supported ();
4777 /* If the stub wants to get a QAllow, compose one and send it. */
4778 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
4779 set_permissions ();
4781 /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
4782 unknown 'v' packet with string "OK". "OK" gets interpreted by GDB
4783 as a reply to known packet. For packet "vFile:setfs:" it is an
4784 invalid reply and GDB would return error in
4785 remote_hostio_set_filesystem, making remote files access impossible.
4786 Disable "vFile:setfs:" in such case. Do not disable other 'v' packets as
4787 other "vFile" packets get correctly detected even on gdbserver < 7.7. */
4789 const char v_mustreplyempty[] = "vMustReplyEmpty";
4791 putpkt (v_mustreplyempty);
4792 getpkt (&rs->buf, 0);
4793 if (strcmp (rs->buf.data (), "OK") == 0)
4794 remote_protocol_packets[PACKET_vFile_setfs].support = PACKET_DISABLE;
4795 else if (strcmp (rs->buf.data (), "") != 0)
4796 error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
4797 rs->buf.data ());
4800 /* Next, we possibly activate noack mode.
4802 If the QStartNoAckMode packet configuration is set to AUTO,
4803 enable noack mode if the stub reported a wish for it with
4804 qSupported.
4806 If set to TRUE, then enable noack mode even if the stub didn't
4807 report it in qSupported. If the stub doesn't reply OK, the
4808 session ends with an error.
4810 If FALSE, then don't activate noack mode, regardless of what the
4811 stub claimed should be the default with qSupported. */
4813 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4814 if (packet_config_support (noack_config) != PACKET_DISABLE)
4816 putpkt ("QStartNoAckMode");
4817 getpkt (&rs->buf, 0);
4818 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
4819 rs->noack_mode = 1;
4822 if (extended_p)
4824 /* Tell the remote that we are using the extended protocol. */
4825 putpkt ("!");
4826 getpkt (&rs->buf, 0);
4829 /* Let the target know which signals it is allowed to pass down to
4830 the program. */
4831 update_signals_program_target ();
4833 /* Next, if the target can specify a description, read it. We do
4834 this before anything involving memory or registers. */
4835 target_find_description ();
4837 /* Next, now that we know something about the target, update the
4838 address spaces in the program spaces. */
4839 update_address_spaces ();
4841 /* On OSs where the list of libraries is global to all
4842 processes, we fetch them early. */
4843 if (gdbarch_has_global_solist (target_gdbarch ()))
4844 solib_add (NULL, from_tty, auto_solib_add);
4846 if (target_is_non_stop_p ())
4848 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
4849 error (_("Non-stop mode requested, but remote "
4850 "does not support non-stop"));
4852 putpkt ("QNonStop:1");
4853 getpkt (&rs->buf, 0);
4855 if (strcmp (rs->buf.data (), "OK") != 0)
4856 error (_("Remote refused setting non-stop mode with: %s"),
4857 rs->buf.data ());
4859 /* Find about threads and processes the stub is already
4860 controlling. We default to adding them in the running state.
4861 The '?' query below will then tell us about which threads are
4862 stopped. */
4863 this->update_thread_list ();
4865 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
4867 /* Don't assume that the stub can operate in all-stop mode.
4868 Request it explicitly. */
4869 putpkt ("QNonStop:0");
4870 getpkt (&rs->buf, 0);
4872 if (strcmp (rs->buf.data (), "OK") != 0)
4873 error (_("Remote refused setting all-stop mode with: %s"),
4874 rs->buf.data ());
4877 /* Upload TSVs regardless of whether the target is running or not. The
4878 remote stub, such as GDBserver, may have some predefined or builtin
4879 TSVs, even if the target is not running. */
4880 if (get_trace_status (current_trace_status ()) != -1)
4882 struct uploaded_tsv *uploaded_tsvs = NULL;
4884 upload_trace_state_variables (&uploaded_tsvs);
4885 merge_uploaded_trace_state_variables (&uploaded_tsvs);
4888 /* Check whether the target is running now. */
4889 putpkt ("?");
4890 getpkt (&rs->buf, 0);
4892 if (!target_is_non_stop_p ())
4894 char *wait_status = NULL;
4896 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
4898 if (!extended_p)
4899 error (_("The target is not running (try extended-remote?)"));
4900 return false;
4902 else
4904 /* Save the reply for later. */
4905 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
4906 strcpy (wait_status, rs->buf.data ());
4909 /* Fetch thread list. */
4910 target_update_thread_list ();
4912 /* Let the stub know that we want it to return the thread. */
4913 set_continue_thread (minus_one_ptid);
4915 if (thread_count (this) == 0)
4917 /* Target has no concept of threads at all. GDB treats
4918 non-threaded target as single-threaded; add a main
4919 thread. */
4920 thread_info *tp = add_current_inferior_and_thread (wait_status);
4921 get_remote_thread_info (tp)->set_resumed ();
4923 else
4925 /* We have thread information; select the thread the target
4926 says should be current. If we're reconnecting to a
4927 multi-threaded program, this will ideally be the thread
4928 that last reported an event before GDB disconnected. */
4929 ptid_t curr_thread = get_current_thread (wait_status);
4930 if (curr_thread == null_ptid)
4932 /* Odd... The target was able to list threads, but not
4933 tell us which thread was current (no "thread"
4934 register in T stop reply?). Just pick the first
4935 thread in the thread list then. */
4937 remote_debug_printf ("warning: couldn't determine remote "
4938 "current thread; picking first in list.");
4940 for (thread_info *tp : all_non_exited_threads (this,
4941 minus_one_ptid))
4943 switch_to_thread (tp);
4944 break;
4947 else
4948 switch_to_thread (find_thread_ptid (this, curr_thread));
4951 /* init_wait_for_inferior should be called before get_offsets in order
4952 to manage `inserted' flag in bp loc in a correct state.
4953 breakpoint_init_inferior, called from init_wait_for_inferior, set
4954 `inserted' flag to 0, while before breakpoint_re_set, called from
4955 start_remote, set `inserted' flag to 1. In the initialization of
4956 inferior, breakpoint_init_inferior should be called first, and then
4957 breakpoint_re_set can be called. If this order is broken, state of
4958 `inserted' flag is wrong, and cause some problems on breakpoint
4959 manipulation. */
4960 init_wait_for_inferior ();
4962 get_offsets (); /* Get text, data & bss offsets. */
4964 /* If we could not find a description using qXfer, and we know
4965 how to do it some other way, try again. This is not
4966 supported for non-stop; it could be, but it is tricky if
4967 there are no stopped threads when we connect. */
4968 if (remote_read_description_p (this)
4969 && gdbarch_target_desc (target_gdbarch ()) == NULL)
4971 target_clear_description ();
4972 target_find_description ();
4975 /* Use the previously fetched status. */
4976 gdb_assert (wait_status != NULL);
4977 struct notif_event *reply
4978 = remote_notif_parse (this, &notif_client_stop, wait_status);
4979 push_stop_reply ((struct stop_reply *) reply);
4981 ::start_remote (from_tty); /* Initialize gdb process mechanisms. */
4983 else
4985 /* Clear WFI global state. Do this before finding about new
4986 threads and inferiors, and setting the current inferior.
4987 Otherwise we would clear the proceed status of the current
4988 inferior when we want its stop_soon state to be preserved
4989 (see notice_new_inferior). */
4990 init_wait_for_inferior ();
4992 /* In non-stop, we will either get an "OK", meaning that there
4993 are no stopped threads at this time; or, a regular stop
4994 reply. In the latter case, there may be more than one thread
4995 stopped --- we pull them all out using the vStopped
4996 mechanism. */
4997 if (strcmp (rs->buf.data (), "OK") != 0)
4999 struct notif_client *notif = &notif_client_stop;
5001 /* remote_notif_get_pending_replies acks this one, and gets
5002 the rest out. */
5003 rs->notif_state->pending_event[notif_client_stop.id]
5004 = remote_notif_parse (this, notif, rs->buf.data ());
5005 remote_notif_get_pending_events (notif);
5008 if (thread_count (this) == 0)
5010 if (!extended_p)
5011 error (_("The target is not running (try extended-remote?)"));
5012 return false;
5015 /* Report all signals during attach/startup. */
5016 pass_signals ({});
5018 /* If there are already stopped threads, mark them stopped and
5019 report their stops before giving the prompt to the user. */
5020 process_initial_stop_replies (from_tty);
5022 if (target_can_async_p ())
5023 target_async (true);
5026 /* Give the target a chance to look up symbols. */
5027 for (inferior *inf : all_inferiors (this))
5029 /* The inferiors that exist at this point were created from what
5030 was found already running on the remote side, so we know they
5031 have execution. */
5032 gdb_assert (this->has_execution (inf));
5034 /* No use without a symbol-file. */
5035 if (inf->pspace->symfile_object_file == nullptr)
5036 continue;
5038 /* Need to switch to a specific thread, because remote_check_symbols
5039 uses INFERIOR_PTID to set the general thread. */
5040 scoped_restore_current_thread restore_thread;
5041 thread_info *thread = any_thread_of_inferior (inf);
5042 switch_to_thread (thread);
5043 this->remote_check_symbols ();
5046 /* Possibly the target has been engaged in a trace run started
5047 previously; find out where things are at. */
5048 if (get_trace_status (current_trace_status ()) != -1)
5050 struct uploaded_tp *uploaded_tps = NULL;
5052 if (current_trace_status ()->running)
5053 gdb_printf (_("Trace is already running on the target.\n"));
5055 upload_tracepoints (&uploaded_tps);
5057 merge_uploaded_tracepoints (&uploaded_tps);
5060 /* Possibly the target has been engaged in a btrace record started
5061 previously; find out where things are at. */
5062 remote_btrace_maybe_reopen ();
5064 return true;
5067 /* Start the remote connection and sync state. */
5069 void
5070 remote_target::start_remote (int from_tty, int extended_p)
5072 if (start_remote_1 (from_tty, extended_p)
5073 && breakpoints_should_be_inserted_now ())
5074 insert_breakpoints ();
5077 const char *
5078 remote_target::connection_string ()
5080 remote_state *rs = get_remote_state ();
5082 if (rs->remote_desc->name != NULL)
5083 return rs->remote_desc->name;
5084 else
5085 return NULL;
5088 /* Open a connection to a remote debugger.
5089 NAME is the filename used for communication. */
5091 void
5092 remote_target::open (const char *name, int from_tty)
5094 open_1 (name, from_tty, 0);
5097 /* Open a connection to a remote debugger using the extended
5098 remote gdb protocol. NAME is the filename used for communication. */
5100 void
5101 extended_remote_target::open (const char *name, int from_tty)
5103 open_1 (name, from_tty, 1 /*extended_p */);
5106 /* Reset all packets back to "unknown support". Called when opening a
5107 new connection to a remote target. */
5109 static void
5110 reset_all_packet_configs_support (void)
5112 int i;
5114 for (i = 0; i < PACKET_MAX; i++)
5115 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
5118 /* Initialize all packet configs. */
5120 static void
5121 init_all_packet_configs (void)
5123 int i;
5125 for (i = 0; i < PACKET_MAX; i++)
5127 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
5128 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
5132 /* Symbol look-up. */
5134 void
5135 remote_target::remote_check_symbols ()
5137 char *tmp;
5138 int end;
5140 /* It doesn't make sense to send a qSymbol packet for an inferior that
5141 doesn't have execution, because the remote side doesn't know about
5142 inferiors without execution. */
5143 gdb_assert (target_has_execution ());
5145 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
5146 return;
5148 /* Make sure the remote is pointing at the right process. Note
5149 there's no way to select "no process". */
5150 set_general_process ();
5152 /* Allocate a message buffer. We can't reuse the input buffer in RS,
5153 because we need both at the same time. */
5154 gdb::char_vector msg (get_remote_packet_size ());
5155 gdb::char_vector reply (get_remote_packet_size ());
5157 /* Invite target to request symbol lookups. */
5159 putpkt ("qSymbol::");
5160 getpkt (&reply, 0);
5161 packet_ok (reply, &remote_protocol_packets[PACKET_qSymbol]);
5163 while (startswith (reply.data (), "qSymbol:"))
5165 struct bound_minimal_symbol sym;
5167 tmp = &reply[8];
5168 end = hex2bin (tmp, reinterpret_cast <gdb_byte *> (msg.data ()),
5169 strlen (tmp) / 2);
5170 msg[end] = '\0';
5171 sym = lookup_minimal_symbol (msg.data (), NULL, NULL);
5172 if (sym.minsym == NULL)
5173 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol::%s",
5174 &reply[8]);
5175 else
5177 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5178 CORE_ADDR sym_addr = sym.value_address ();
5180 /* If this is a function address, return the start of code
5181 instead of any data function descriptor. */
5182 sym_addr = gdbarch_convert_from_func_ptr_addr
5183 (target_gdbarch (), sym_addr, current_inferior ()->top_target ());
5185 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol:%s:%s",
5186 phex_nz (sym_addr, addr_size), &reply[8]);
5189 putpkt (msg.data ());
5190 getpkt (&reply, 0);
5194 static struct serial *
5195 remote_serial_open (const char *name)
5197 static int udp_warning = 0;
5199 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
5200 of in ser-tcp.c, because it is the remote protocol assuming that the
5201 serial connection is reliable and not the serial connection promising
5202 to be. */
5203 if (!udp_warning && startswith (name, "udp:"))
5205 warning (_("The remote protocol may be unreliable over UDP.\n"
5206 "Some events may be lost, rendering further debugging "
5207 "impossible."));
5208 udp_warning = 1;
5211 return serial_open (name);
5214 /* Inform the target of our permission settings. The permission flags
5215 work without this, but if the target knows the settings, it can do
5216 a couple things. First, it can add its own check, to catch cases
5217 that somehow manage to get by the permissions checks in target
5218 methods. Second, if the target is wired to disallow particular
5219 settings (for instance, a system in the field that is not set up to
5220 be able to stop at a breakpoint), it can object to any unavailable
5221 permissions. */
5223 void
5224 remote_target::set_permissions ()
5226 struct remote_state *rs = get_remote_state ();
5228 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAllow:"
5229 "WriteReg:%x;WriteMem:%x;"
5230 "InsertBreak:%x;InsertTrace:%x;"
5231 "InsertFastTrace:%x;Stop:%x",
5232 may_write_registers, may_write_memory,
5233 may_insert_breakpoints, may_insert_tracepoints,
5234 may_insert_fast_tracepoints, may_stop);
5235 putpkt (rs->buf);
5236 getpkt (&rs->buf, 0);
5238 /* If the target didn't like the packet, warn the user. Do not try
5239 to undo the user's settings, that would just be maddening. */
5240 if (strcmp (rs->buf.data (), "OK") != 0)
5241 warning (_("Remote refused setting permissions with: %s"),
5242 rs->buf.data ());
5245 /* This type describes each known response to the qSupported
5246 packet. */
5247 struct protocol_feature
5249 /* The name of this protocol feature. */
5250 const char *name;
5252 /* The default for this protocol feature. */
5253 enum packet_support default_support;
5255 /* The function to call when this feature is reported, or after
5256 qSupported processing if the feature is not supported.
5257 The first argument points to this structure. The second
5258 argument indicates whether the packet requested support be
5259 enabled, disabled, or probed (or the default, if this function
5260 is being called at the end of processing and this feature was
5261 not reported). The third argument may be NULL; if not NULL, it
5262 is a NUL-terminated string taken from the packet following
5263 this feature's name and an equals sign. */
5264 void (*func) (remote_target *remote, const struct protocol_feature *,
5265 enum packet_support, const char *);
5267 /* The corresponding packet for this feature. Only used if
5268 FUNC is remote_supported_packet. */
5269 int packet;
5272 static void
5273 remote_supported_packet (remote_target *remote,
5274 const struct protocol_feature *feature,
5275 enum packet_support support,
5276 const char *argument)
5278 if (argument)
5280 warning (_("Remote qSupported response supplied an unexpected value for"
5281 " \"%s\"."), feature->name);
5282 return;
5285 remote_protocol_packets[feature->packet].support = support;
5288 void
5289 remote_target::remote_packet_size (const protocol_feature *feature,
5290 enum packet_support support, const char *value)
5292 struct remote_state *rs = get_remote_state ();
5294 int packet_size;
5295 char *value_end;
5297 if (support != PACKET_ENABLE)
5298 return;
5300 if (value == NULL || *value == '\0')
5302 warning (_("Remote target reported \"%s\" without a size."),
5303 feature->name);
5304 return;
5307 errno = 0;
5308 packet_size = strtol (value, &value_end, 16);
5309 if (errno != 0 || *value_end != '\0' || packet_size < 0)
5311 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
5312 feature->name, value);
5313 return;
5316 /* Record the new maximum packet size. */
5317 rs->explicit_packet_size = packet_size;
5320 static void
5321 remote_packet_size (remote_target *remote, const protocol_feature *feature,
5322 enum packet_support support, const char *value)
5324 remote->remote_packet_size (feature, support, value);
5327 static const struct protocol_feature remote_protocol_features[] = {
5328 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
5329 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
5330 PACKET_qXfer_auxv },
5331 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
5332 PACKET_qXfer_exec_file },
5333 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
5334 PACKET_qXfer_features },
5335 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
5336 PACKET_qXfer_libraries },
5337 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
5338 PACKET_qXfer_libraries_svr4 },
5339 { "augmented-libraries-svr4-read", PACKET_DISABLE,
5340 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
5341 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
5342 PACKET_qXfer_memory_map },
5343 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
5344 PACKET_qXfer_osdata },
5345 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
5346 PACKET_qXfer_threads },
5347 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
5348 PACKET_qXfer_traceframe_info },
5349 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
5350 PACKET_QPassSignals },
5351 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
5352 PACKET_QCatchSyscalls },
5353 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
5354 PACKET_QProgramSignals },
5355 { "QSetWorkingDir", PACKET_DISABLE, remote_supported_packet,
5356 PACKET_QSetWorkingDir },
5357 { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
5358 PACKET_QStartupWithShell },
5359 { "QEnvironmentHexEncoded", PACKET_DISABLE, remote_supported_packet,
5360 PACKET_QEnvironmentHexEncoded },
5361 { "QEnvironmentReset", PACKET_DISABLE, remote_supported_packet,
5362 PACKET_QEnvironmentReset },
5363 { "QEnvironmentUnset", PACKET_DISABLE, remote_supported_packet,
5364 PACKET_QEnvironmentUnset },
5365 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
5366 PACKET_QStartNoAckMode },
5367 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
5368 PACKET_multiprocess_feature },
5369 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
5370 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
5371 PACKET_qXfer_siginfo_read },
5372 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
5373 PACKET_qXfer_siginfo_write },
5374 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
5375 PACKET_ConditionalTracepoints },
5376 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
5377 PACKET_ConditionalBreakpoints },
5378 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
5379 PACKET_BreakpointCommands },
5380 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
5381 PACKET_FastTracepoints },
5382 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
5383 PACKET_StaticTracepoints },
5384 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
5385 PACKET_InstallInTrace},
5386 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
5387 PACKET_DisconnectedTracing_feature },
5388 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
5389 PACKET_bc },
5390 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
5391 PACKET_bs },
5392 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
5393 PACKET_TracepointSource },
5394 { "QAllow", PACKET_DISABLE, remote_supported_packet,
5395 PACKET_QAllow },
5396 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
5397 PACKET_EnableDisableTracepoints_feature },
5398 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
5399 PACKET_qXfer_fdpic },
5400 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
5401 PACKET_qXfer_uib },
5402 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
5403 PACKET_QDisableRandomization },
5404 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
5405 { "QTBuffer:size", PACKET_DISABLE,
5406 remote_supported_packet, PACKET_QTBuffer_size},
5407 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
5408 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
5409 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
5410 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
5411 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
5412 PACKET_qXfer_btrace },
5413 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
5414 PACKET_qXfer_btrace_conf },
5415 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
5416 PACKET_Qbtrace_conf_bts_size },
5417 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
5418 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
5419 { "fork-events", PACKET_DISABLE, remote_supported_packet,
5420 PACKET_fork_event_feature },
5421 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
5422 PACKET_vfork_event_feature },
5423 { "exec-events", PACKET_DISABLE, remote_supported_packet,
5424 PACKET_exec_event_feature },
5425 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
5426 PACKET_Qbtrace_conf_pt_size },
5427 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
5428 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
5429 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
5430 { "memory-tagging", PACKET_DISABLE, remote_supported_packet,
5431 PACKET_memory_tagging_feature },
5434 static char *remote_support_xml;
5436 /* Register string appended to "xmlRegisters=" in qSupported query. */
5438 void
5439 register_remote_support_xml (const char *xml)
5441 #if defined(HAVE_LIBEXPAT)
5442 if (remote_support_xml == NULL)
5443 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
5444 else
5446 char *copy = xstrdup (remote_support_xml + 13);
5447 char *saveptr;
5448 char *p = strtok_r (copy, ",", &saveptr);
5452 if (strcmp (p, xml) == 0)
5454 /* already there */
5455 xfree (copy);
5456 return;
5459 while ((p = strtok_r (NULL, ",", &saveptr)) != NULL);
5460 xfree (copy);
5462 remote_support_xml = reconcat (remote_support_xml,
5463 remote_support_xml, ",", xml,
5464 (char *) NULL);
5466 #endif
5469 static void
5470 remote_query_supported_append (std::string *msg, const char *append)
5472 if (!msg->empty ())
5473 msg->append (";");
5474 msg->append (append);
5477 void
5478 remote_target::remote_query_supported ()
5480 struct remote_state *rs = get_remote_state ();
5481 char *next;
5482 int i;
5483 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
5485 /* The packet support flags are handled differently for this packet
5486 than for most others. We treat an error, a disabled packet, and
5487 an empty response identically: any features which must be reported
5488 to be used will be automatically disabled. An empty buffer
5489 accomplishes this, since that is also the representation for a list
5490 containing no features. */
5492 rs->buf[0] = 0;
5493 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
5495 std::string q;
5497 if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
5498 remote_query_supported_append (&q, "multiprocess+");
5500 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
5501 remote_query_supported_append (&q, "swbreak+");
5502 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
5503 remote_query_supported_append (&q, "hwbreak+");
5505 remote_query_supported_append (&q, "qRelocInsn+");
5507 if (packet_set_cmd_state (PACKET_fork_event_feature)
5508 != AUTO_BOOLEAN_FALSE)
5509 remote_query_supported_append (&q, "fork-events+");
5510 if (packet_set_cmd_state (PACKET_vfork_event_feature)
5511 != AUTO_BOOLEAN_FALSE)
5512 remote_query_supported_append (&q, "vfork-events+");
5513 if (packet_set_cmd_state (PACKET_exec_event_feature)
5514 != AUTO_BOOLEAN_FALSE)
5515 remote_query_supported_append (&q, "exec-events+");
5517 if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
5518 remote_query_supported_append (&q, "vContSupported+");
5520 if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
5521 remote_query_supported_append (&q, "QThreadEvents+");
5523 if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
5524 remote_query_supported_append (&q, "no-resumed+");
5526 if (packet_set_cmd_state (PACKET_memory_tagging_feature)
5527 != AUTO_BOOLEAN_FALSE)
5528 remote_query_supported_append (&q, "memory-tagging+");
5530 /* Keep this one last to work around a gdbserver <= 7.10 bug in
5531 the qSupported:xmlRegisters=i386 handling. */
5532 if (remote_support_xml != NULL
5533 && packet_support (PACKET_qXfer_features) != PACKET_DISABLE)
5534 remote_query_supported_append (&q, remote_support_xml);
5536 q = "qSupported:" + q;
5537 putpkt (q.c_str ());
5539 getpkt (&rs->buf, 0);
5541 /* If an error occured, warn, but do not return - just reset the
5542 buffer to empty and go on to disable features. */
5543 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
5544 == PACKET_ERROR)
5546 warning (_("Remote failure reply: %s"), rs->buf.data ());
5547 rs->buf[0] = 0;
5551 memset (seen, 0, sizeof (seen));
5553 next = rs->buf.data ();
5554 while (*next)
5556 enum packet_support is_supported;
5557 char *p, *end, *name_end, *value;
5559 /* First separate out this item from the rest of the packet. If
5560 there's another item after this, we overwrite the separator
5561 (terminated strings are much easier to work with). */
5562 p = next;
5563 end = strchr (p, ';');
5564 if (end == NULL)
5566 end = p + strlen (p);
5567 next = end;
5569 else
5571 *end = '\0';
5572 next = end + 1;
5574 if (end == p)
5576 warning (_("empty item in \"qSupported\" response"));
5577 continue;
5581 name_end = strchr (p, '=');
5582 if (name_end)
5584 /* This is a name=value entry. */
5585 is_supported = PACKET_ENABLE;
5586 value = name_end + 1;
5587 *name_end = '\0';
5589 else
5591 value = NULL;
5592 switch (end[-1])
5594 case '+':
5595 is_supported = PACKET_ENABLE;
5596 break;
5598 case '-':
5599 is_supported = PACKET_DISABLE;
5600 break;
5602 case '?':
5603 is_supported = PACKET_SUPPORT_UNKNOWN;
5604 break;
5606 default:
5607 warning (_("unrecognized item \"%s\" "
5608 "in \"qSupported\" response"), p);
5609 continue;
5611 end[-1] = '\0';
5614 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5615 if (strcmp (remote_protocol_features[i].name, p) == 0)
5617 const struct protocol_feature *feature;
5619 seen[i] = 1;
5620 feature = &remote_protocol_features[i];
5621 feature->func (this, feature, is_supported, value);
5622 break;
5626 /* If we increased the packet size, make sure to increase the global
5627 buffer size also. We delay this until after parsing the entire
5628 qSupported packet, because this is the same buffer we were
5629 parsing. */
5630 if (rs->buf.size () < rs->explicit_packet_size)
5631 rs->buf.resize (rs->explicit_packet_size);
5633 /* Handle the defaults for unmentioned features. */
5634 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5635 if (!seen[i])
5637 const struct protocol_feature *feature;
5639 feature = &remote_protocol_features[i];
5640 feature->func (this, feature, feature->default_support, NULL);
5644 /* Serial QUIT handler for the remote serial descriptor.
5646 Defers handling a Ctrl-C until we're done with the current
5647 command/response packet sequence, unless:
5649 - We're setting up the connection. Don't send a remote interrupt
5650 request, as we're not fully synced yet. Quit immediately
5651 instead.
5653 - The target has been resumed in the foreground
5654 (target_terminal::is_ours is false) with a synchronous resume
5655 packet, and we're blocked waiting for the stop reply, thus a
5656 Ctrl-C should be immediately sent to the target.
5658 - We get a second Ctrl-C while still within the same serial read or
5659 write. In that case the serial is seemingly wedged --- offer to
5660 quit/disconnect.
5662 - We see a second Ctrl-C without target response, after having
5663 previously interrupted the target. In that case the target/stub
5664 is probably wedged --- offer to quit/disconnect.
5667 void
5668 remote_target::remote_serial_quit_handler ()
5670 struct remote_state *rs = get_remote_state ();
5672 if (check_quit_flag ())
5674 /* If we're starting up, we're not fully synced yet. Quit
5675 immediately. */
5676 if (rs->starting_up)
5677 quit ();
5678 else if (rs->got_ctrlc_during_io)
5680 if (query (_("The target is not responding to GDB commands.\n"
5681 "Stop debugging it? ")))
5682 remote_unpush_and_throw (this);
5684 /* If ^C has already been sent once, offer to disconnect. */
5685 else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
5686 interrupt_query ();
5687 /* All-stop protocol, and blocked waiting for stop reply. Send
5688 an interrupt request. */
5689 else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
5690 target_interrupt ();
5691 else
5692 rs->got_ctrlc_during_io = 1;
5696 /* The remote_target that is current while the quit handler is
5697 overridden with remote_serial_quit_handler. */
5698 static remote_target *curr_quit_handler_target;
5700 static void
5701 remote_serial_quit_handler ()
5703 curr_quit_handler_target->remote_serial_quit_handler ();
5706 /* Remove the remote target from the target stack of each inferior
5707 that is using it. Upper targets depend on it so remove them
5708 first. */
5710 static void
5711 remote_unpush_target (remote_target *target)
5713 /* We have to unpush the target from all inferiors, even those that
5714 aren't running. */
5715 scoped_restore_current_inferior restore_current_inferior;
5717 for (inferior *inf : all_inferiors (target))
5719 switch_to_inferior_no_thread (inf);
5720 inf->pop_all_targets_at_and_above (process_stratum);
5721 generic_mourn_inferior ();
5724 /* Don't rely on target_close doing this when the target is popped
5725 from the last remote inferior above, because something may be
5726 holding a reference to the target higher up on the stack, meaning
5727 target_close won't be called yet. We lost the connection to the
5728 target, so clear these now, otherwise we may later throw
5729 TARGET_CLOSE_ERROR while trying to tell the remote target to
5730 close the file. */
5731 fileio_handles_invalidate_target (target);
5734 static void
5735 remote_unpush_and_throw (remote_target *target)
5737 remote_unpush_target (target);
5738 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5741 void
5742 remote_target::open_1 (const char *name, int from_tty, int extended_p)
5744 remote_target *curr_remote = get_current_remote_target ();
5746 if (name == 0)
5747 error (_("To open a remote debug connection, you need to specify what\n"
5748 "serial device is attached to the remote system\n"
5749 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
5751 /* If we're connected to a running target, target_preopen will kill it.
5752 Ask this question first, before target_preopen has a chance to kill
5753 anything. */
5754 if (curr_remote != NULL && !target_has_execution ())
5756 if (from_tty
5757 && !query (_("Already connected to a remote target. Disconnect? ")))
5758 error (_("Still connected."));
5761 /* Here the possibly existing remote target gets unpushed. */
5762 target_preopen (from_tty);
5764 remote_fileio_reset ();
5765 reopen_exec_file ();
5766 reread_symbols (from_tty);
5768 remote_target *remote
5769 = (extended_p ? new extended_remote_target () : new remote_target ());
5770 target_ops_up target_holder (remote);
5772 remote_state *rs = remote->get_remote_state ();
5774 /* See FIXME above. */
5775 if (!target_async_permitted)
5776 rs->wait_forever_enabled_p = 1;
5778 rs->remote_desc = remote_serial_open (name);
5779 if (!rs->remote_desc)
5780 perror_with_name (name);
5782 if (baud_rate != -1)
5784 if (serial_setbaudrate (rs->remote_desc, baud_rate))
5786 /* The requested speed could not be set. Error out to
5787 top level after closing remote_desc. Take care to
5788 set remote_desc to NULL to avoid closing remote_desc
5789 more than once. */
5790 serial_close (rs->remote_desc);
5791 rs->remote_desc = NULL;
5792 perror_with_name (name);
5796 serial_setparity (rs->remote_desc, serial_parity);
5797 serial_raw (rs->remote_desc);
5799 /* If there is something sitting in the buffer we might take it as a
5800 response to a command, which would be bad. */
5801 serial_flush_input (rs->remote_desc);
5803 if (from_tty)
5805 gdb_puts ("Remote debugging using ");
5806 gdb_puts (name);
5807 gdb_puts ("\n");
5810 /* Switch to using the remote target now. */
5811 current_inferior ()->push_target (std::move (target_holder));
5813 /* Register extra event sources in the event loop. */
5814 rs->remote_async_inferior_event_token
5815 = create_async_event_handler (remote_async_inferior_event_handler, nullptr,
5816 "remote");
5817 rs->notif_state = remote_notif_state_allocate (remote);
5819 /* Reset the target state; these things will be queried either by
5820 remote_query_supported or as they are needed. */
5821 reset_all_packet_configs_support ();
5822 rs->explicit_packet_size = 0;
5823 rs->noack_mode = 0;
5824 rs->extended = extended_p;
5825 rs->waiting_for_stop_reply = 0;
5826 rs->ctrlc_pending_p = 0;
5827 rs->got_ctrlc_during_io = 0;
5829 rs->general_thread = not_sent_ptid;
5830 rs->continue_thread = not_sent_ptid;
5831 rs->remote_traceframe_number = -1;
5833 rs->last_resume_exec_dir = EXEC_FORWARD;
5835 /* Probe for ability to use "ThreadInfo" query, as required. */
5836 rs->use_threadinfo_query = 1;
5837 rs->use_threadextra_query = 1;
5839 rs->readahead_cache.invalidate ();
5841 if (target_async_permitted)
5843 /* FIXME: cagney/1999-09-23: During the initial connection it is
5844 assumed that the target is already ready and able to respond to
5845 requests. Unfortunately remote_start_remote() eventually calls
5846 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
5847 around this. Eventually a mechanism that allows
5848 wait_for_inferior() to expect/get timeouts will be
5849 implemented. */
5850 rs->wait_forever_enabled_p = 0;
5853 /* First delete any symbols previously loaded from shared libraries. */
5854 no_shared_libraries (NULL, 0);
5856 /* Start the remote connection. If error() or QUIT, discard this
5857 target (we'd otherwise be in an inconsistent state) and then
5858 propogate the error on up the exception chain. This ensures that
5859 the caller doesn't stumble along blindly assuming that the
5860 function succeeded. The CLI doesn't have this problem but other
5861 UI's, such as MI do.
5863 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
5864 this function should return an error indication letting the
5865 caller restore the previous state. Unfortunately the command
5866 ``target remote'' is directly wired to this function making that
5867 impossible. On a positive note, the CLI side of this problem has
5868 been fixed - the function set_cmd_context() makes it possible for
5869 all the ``target ....'' commands to share a common callback
5870 function. See cli-dump.c. */
5875 remote->start_remote (from_tty, extended_p);
5877 catch (const gdb_exception &ex)
5879 /* Pop the partially set up target - unless something else did
5880 already before throwing the exception. */
5881 if (ex.error != TARGET_CLOSE_ERROR)
5882 remote_unpush_target (remote);
5883 throw;
5887 remote_btrace_reset (rs);
5889 if (target_async_permitted)
5890 rs->wait_forever_enabled_p = 1;
5893 /* Determine if WS represents a fork status. */
5895 static bool
5896 is_fork_status (target_waitkind kind)
5898 return (kind == TARGET_WAITKIND_FORKED
5899 || kind == TARGET_WAITKIND_VFORKED);
5902 /* Return THREAD's pending status if it is a pending fork parent, else
5903 return nullptr. */
5905 static const target_waitstatus *
5906 thread_pending_fork_status (struct thread_info *thread)
5908 const target_waitstatus &ws
5909 = (thread->has_pending_waitstatus ()
5910 ? thread->pending_waitstatus ()
5911 : thread->pending_follow);
5913 if (!is_fork_status (ws.kind ()))
5914 return nullptr;
5916 return &ws;
5919 /* Detach the specified process. */
5921 void
5922 remote_target::remote_detach_pid (int pid)
5924 struct remote_state *rs = get_remote_state ();
5926 /* This should not be necessary, but the handling for D;PID in
5927 GDBserver versions prior to 8.2 incorrectly assumes that the
5928 selected process points to the same process we're detaching,
5929 leading to misbehavior (and possibly GDBserver crashing) when it
5930 does not. Since it's easy and cheap, work around it by forcing
5931 GDBserver to select GDB's current process. */
5932 set_general_process ();
5934 if (remote_multi_process_p (rs))
5935 xsnprintf (rs->buf.data (), get_remote_packet_size (), "D;%x", pid);
5936 else
5937 strcpy (rs->buf.data (), "D");
5939 putpkt (rs->buf);
5940 getpkt (&rs->buf, 0);
5942 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
5944 else if (rs->buf[0] == '\0')
5945 error (_("Remote doesn't know how to detach"));
5946 else
5947 error (_("Can't detach process."));
5950 /* This detaches a program to which we previously attached, using
5951 inferior_ptid to identify the process. After this is done, GDB
5952 can be used to debug some other program. We better not have left
5953 any breakpoints in the target program or it'll die when it hits
5954 one. */
5956 void
5957 remote_target::remote_detach_1 (inferior *inf, int from_tty)
5959 int pid = inferior_ptid.pid ();
5960 struct remote_state *rs = get_remote_state ();
5961 int is_fork_parent;
5963 if (!target_has_execution ())
5964 error (_("No process to detach from."));
5966 target_announce_detach (from_tty);
5968 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
5970 /* If we're in breakpoints-always-inserted mode, or the inferior
5971 is running, we have to remove breakpoints before detaching.
5972 We don't do this in common code instead because not all
5973 targets support removing breakpoints while the target is
5974 running. The remote target / gdbserver does, though. */
5975 remove_breakpoints_inf (current_inferior ());
5978 /* Tell the remote target to detach. */
5979 remote_detach_pid (pid);
5981 /* Exit only if this is the only active inferior. */
5982 if (from_tty && !rs->extended && number_of_live_inferiors (this) == 1)
5983 gdb_puts (_("Ending remote debugging.\n"));
5985 /* See if any thread of the inferior we are detaching has a pending fork
5986 status. In that case, we must detach from the child resulting from
5987 that fork. */
5988 for (thread_info *thread : inf->non_exited_threads ())
5990 const target_waitstatus *ws = thread_pending_fork_status (thread);
5992 if (ws == nullptr)
5993 continue;
5995 remote_detach_pid (ws->child_ptid ().pid ());
5998 /* Check also for any pending fork events in the stop reply queue. */
5999 remote_notif_get_pending_events (&notif_client_stop);
6000 for (stop_reply_up &reply : rs->stop_reply_queue)
6002 if (reply->ptid.pid () != pid)
6003 continue;
6005 if (!is_fork_status (reply->ws.kind ()))
6006 continue;
6008 remote_detach_pid (reply->ws.child_ptid ().pid ());
6011 thread_info *tp = find_thread_ptid (this, inferior_ptid);
6013 /* Check to see if we are detaching a fork parent. Note that if we
6014 are detaching a fork child, tp == NULL. */
6015 is_fork_parent = (tp != NULL
6016 && tp->pending_follow.kind () == TARGET_WAITKIND_FORKED);
6018 /* If doing detach-on-fork, we don't mourn, because that will delete
6019 breakpoints that should be available for the followed inferior. */
6020 if (!is_fork_parent)
6022 /* Save the pid as a string before mourning, since that will
6023 unpush the remote target, and we need the string after. */
6024 std::string infpid = target_pid_to_str (ptid_t (pid));
6026 target_mourn_inferior (inferior_ptid);
6027 if (print_inferior_events)
6028 gdb_printf (_("[Inferior %d (%s) detached]\n"),
6029 inf->num, infpid.c_str ());
6031 else
6033 switch_to_no_thread ();
6034 detach_inferior (current_inferior ());
6038 void
6039 remote_target::detach (inferior *inf, int from_tty)
6041 remote_detach_1 (inf, from_tty);
6044 void
6045 extended_remote_target::detach (inferior *inf, int from_tty)
6047 remote_detach_1 (inf, from_tty);
6050 /* Target follow-fork function for remote targets. On entry, and
6051 at return, the current inferior is the fork parent.
6053 Note that although this is currently only used for extended-remote,
6054 it is named remote_follow_fork in anticipation of using it for the
6055 remote target as well. */
6057 void
6058 remote_target::follow_fork (inferior *child_inf, ptid_t child_ptid,
6059 target_waitkind fork_kind, bool follow_child,
6060 bool detach_fork)
6062 process_stratum_target::follow_fork (child_inf, child_ptid,
6063 fork_kind, follow_child, detach_fork);
6065 struct remote_state *rs = get_remote_state ();
6067 if ((fork_kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
6068 || (fork_kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
6070 /* When following the parent and detaching the child, we detach
6071 the child here. For the case of following the child and
6072 detaching the parent, the detach is done in the target-
6073 independent follow fork code in infrun.c. We can't use
6074 target_detach when detaching an unfollowed child because
6075 the client side doesn't know anything about the child. */
6076 if (detach_fork && !follow_child)
6078 /* Detach the fork child. */
6079 remote_detach_pid (child_ptid.pid ());
6084 /* Target follow-exec function for remote targets. Save EXECD_PATHNAME
6085 in the program space of the new inferior. */
6087 void
6088 remote_target::follow_exec (inferior *follow_inf, ptid_t ptid,
6089 const char *execd_pathname)
6091 process_stratum_target::follow_exec (follow_inf, ptid, execd_pathname);
6093 /* We know that this is a target file name, so if it has the "target:"
6094 prefix we strip it off before saving it in the program space. */
6095 if (is_target_filename (execd_pathname))
6096 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
6098 set_pspace_remote_exec_file (follow_inf->pspace, execd_pathname);
6101 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
6103 void
6104 remote_target::disconnect (const char *args, int from_tty)
6106 if (args)
6107 error (_("Argument given to \"disconnect\" when remotely debugging."));
6109 /* Make sure we unpush even the extended remote targets. Calling
6110 target_mourn_inferior won't unpush, and
6111 remote_target::mourn_inferior won't unpush if there is more than
6112 one inferior left. */
6113 remote_unpush_target (this);
6115 if (from_tty)
6116 gdb_puts ("Ending remote debugging.\n");
6119 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
6120 be chatty about it. */
6122 void
6123 extended_remote_target::attach (const char *args, int from_tty)
6125 struct remote_state *rs = get_remote_state ();
6126 int pid;
6127 char *wait_status = NULL;
6129 pid = parse_pid_to_attach (args);
6131 /* Remote PID can be freely equal to getpid, do not check it here the same
6132 way as in other targets. */
6134 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
6135 error (_("This target does not support attaching to a process"));
6137 target_announce_attach (from_tty, pid);
6139 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vAttach;%x", pid);
6140 putpkt (rs->buf);
6141 getpkt (&rs->buf, 0);
6143 switch (packet_ok (rs->buf,
6144 &remote_protocol_packets[PACKET_vAttach]))
6146 case PACKET_OK:
6147 if (!target_is_non_stop_p ())
6149 /* Save the reply for later. */
6150 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
6151 strcpy (wait_status, rs->buf.data ());
6153 else if (strcmp (rs->buf.data (), "OK") != 0)
6154 error (_("Attaching to %s failed with: %s"),
6155 target_pid_to_str (ptid_t (pid)).c_str (),
6156 rs->buf.data ());
6157 break;
6158 case PACKET_UNKNOWN:
6159 error (_("This target does not support attaching to a process"));
6160 default:
6161 error (_("Attaching to %s failed"),
6162 target_pid_to_str (ptid_t (pid)).c_str ());
6165 switch_to_inferior_no_thread (remote_add_inferior (false, pid, 1, 0));
6167 inferior_ptid = ptid_t (pid);
6169 if (target_is_non_stop_p ())
6171 /* Get list of threads. */
6172 update_thread_list ();
6174 thread_info *thread = first_thread_of_inferior (current_inferior ());
6175 if (thread != nullptr)
6176 switch_to_thread (thread);
6178 /* Invalidate our notion of the remote current thread. */
6179 record_currthread (rs, minus_one_ptid);
6181 else
6183 /* Now, if we have thread information, update the main thread's
6184 ptid. */
6185 ptid_t curr_ptid = remote_current_thread (ptid_t (pid));
6187 /* Add the main thread to the thread list. We add the thread
6188 silently in this case (the final true parameter). */
6189 thread_info *thr = remote_add_thread (curr_ptid, true, true, true);
6191 switch_to_thread (thr);
6194 /* Next, if the target can specify a description, read it. We do
6195 this before anything involving memory or registers. */
6196 target_find_description ();
6198 if (!target_is_non_stop_p ())
6200 /* Use the previously fetched status. */
6201 gdb_assert (wait_status != NULL);
6203 struct notif_event *reply
6204 = remote_notif_parse (this, &notif_client_stop, wait_status);
6206 push_stop_reply ((struct stop_reply *) reply);
6208 else
6210 gdb_assert (wait_status == NULL);
6212 gdb_assert (target_can_async_p ());
6216 /* Implementation of the to_post_attach method. */
6218 void
6219 extended_remote_target::post_attach (int pid)
6221 /* Get text, data & bss offsets. */
6222 get_offsets ();
6224 /* In certain cases GDB might not have had the chance to start
6225 symbol lookup up until now. This could happen if the debugged
6226 binary is not using shared libraries, the vsyscall page is not
6227 present (on Linux) and the binary itself hadn't changed since the
6228 debugging process was started. */
6229 if (current_program_space->symfile_object_file != NULL)
6230 remote_check_symbols();
6234 /* Check for the availability of vCont. This function should also check
6235 the response. */
6237 void
6238 remote_target::remote_vcont_probe ()
6240 remote_state *rs = get_remote_state ();
6241 char *buf;
6243 strcpy (rs->buf.data (), "vCont?");
6244 putpkt (rs->buf);
6245 getpkt (&rs->buf, 0);
6246 buf = rs->buf.data ();
6248 /* Make sure that the features we assume are supported. */
6249 if (startswith (buf, "vCont"))
6251 char *p = &buf[5];
6252 int support_c, support_C;
6254 rs->supports_vCont.s = 0;
6255 rs->supports_vCont.S = 0;
6256 support_c = 0;
6257 support_C = 0;
6258 rs->supports_vCont.t = 0;
6259 rs->supports_vCont.r = 0;
6260 while (p && *p == ';')
6262 p++;
6263 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
6264 rs->supports_vCont.s = 1;
6265 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
6266 rs->supports_vCont.S = 1;
6267 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
6268 support_c = 1;
6269 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
6270 support_C = 1;
6271 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
6272 rs->supports_vCont.t = 1;
6273 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
6274 rs->supports_vCont.r = 1;
6276 p = strchr (p, ';');
6279 /* If c, and C are not all supported, we can't use vCont. Clearing
6280 BUF will make packet_ok disable the packet. */
6281 if (!support_c || !support_C)
6282 buf[0] = 0;
6285 packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCont]);
6286 rs->supports_vCont_probed = true;
6289 /* Helper function for building "vCont" resumptions. Write a
6290 resumption to P. ENDP points to one-passed-the-end of the buffer
6291 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
6292 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
6293 resumed thread should be single-stepped and/or signalled. If PTID
6294 equals minus_one_ptid, then all threads are resumed; if PTID
6295 represents a process, then all threads of the process are
6296 resumed. */
6298 char *
6299 remote_target::append_resumption (char *p, char *endp,
6300 ptid_t ptid, int step, gdb_signal siggnal)
6302 struct remote_state *rs = get_remote_state ();
6304 if (step && siggnal != GDB_SIGNAL_0)
6305 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
6306 else if (step
6307 /* GDB is willing to range step. */
6308 && use_range_stepping
6309 /* Target supports range stepping. */
6310 && rs->supports_vCont.r
6311 /* We don't currently support range stepping multiple
6312 threads with a wildcard (though the protocol allows it,
6313 so stubs shouldn't make an active effort to forbid
6314 it). */
6315 && !(remote_multi_process_p (rs) && ptid.is_pid ()))
6317 struct thread_info *tp;
6319 if (ptid == minus_one_ptid)
6321 /* If we don't know about the target thread's tid, then
6322 we're resuming magic_null_ptid (see caller). */
6323 tp = find_thread_ptid (this, magic_null_ptid);
6325 else
6326 tp = find_thread_ptid (this, ptid);
6327 gdb_assert (tp != NULL);
6329 if (tp->control.may_range_step)
6331 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
6333 p += xsnprintf (p, endp - p, ";r%s,%s",
6334 phex_nz (tp->control.step_range_start,
6335 addr_size),
6336 phex_nz (tp->control.step_range_end,
6337 addr_size));
6339 else
6340 p += xsnprintf (p, endp - p, ";s");
6342 else if (step)
6343 p += xsnprintf (p, endp - p, ";s");
6344 else if (siggnal != GDB_SIGNAL_0)
6345 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
6346 else
6347 p += xsnprintf (p, endp - p, ";c");
6349 if (remote_multi_process_p (rs) && ptid.is_pid ())
6351 ptid_t nptid;
6353 /* All (-1) threads of process. */
6354 nptid = ptid_t (ptid.pid (), -1);
6356 p += xsnprintf (p, endp - p, ":");
6357 p = write_ptid (p, endp, nptid);
6359 else if (ptid != minus_one_ptid)
6361 p += xsnprintf (p, endp - p, ":");
6362 p = write_ptid (p, endp, ptid);
6365 return p;
6368 /* Clear the thread's private info on resume. */
6370 static void
6371 resume_clear_thread_private_info (struct thread_info *thread)
6373 if (thread->priv != NULL)
6375 remote_thread_info *priv = get_remote_thread_info (thread);
6377 priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6378 priv->watch_data_address = 0;
6382 /* Append a vCont continue-with-signal action for threads that have a
6383 non-zero stop signal. */
6385 char *
6386 remote_target::append_pending_thread_resumptions (char *p, char *endp,
6387 ptid_t ptid)
6389 for (thread_info *thread : all_non_exited_threads (this, ptid))
6390 if (inferior_ptid != thread->ptid
6391 && thread->stop_signal () != GDB_SIGNAL_0)
6393 p = append_resumption (p, endp, thread->ptid,
6394 0, thread->stop_signal ());
6395 thread->set_stop_signal (GDB_SIGNAL_0);
6396 resume_clear_thread_private_info (thread);
6399 return p;
6402 /* Set the target running, using the packets that use Hc
6403 (c/s/C/S). */
6405 void
6406 remote_target::remote_resume_with_hc (ptid_t ptid, int step,
6407 gdb_signal siggnal)
6409 struct remote_state *rs = get_remote_state ();
6410 char *buf;
6412 rs->last_sent_signal = siggnal;
6413 rs->last_sent_step = step;
6415 /* The c/s/C/S resume packets use Hc, so set the continue
6416 thread. */
6417 if (ptid == minus_one_ptid)
6418 set_continue_thread (any_thread_ptid);
6419 else
6420 set_continue_thread (ptid);
6422 for (thread_info *thread : all_non_exited_threads (this))
6423 resume_clear_thread_private_info (thread);
6425 buf = rs->buf.data ();
6426 if (::execution_direction == EXEC_REVERSE)
6428 /* We don't pass signals to the target in reverse exec mode. */
6429 if (info_verbose && siggnal != GDB_SIGNAL_0)
6430 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
6431 siggnal);
6433 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
6434 error (_("Remote reverse-step not supported."));
6435 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
6436 error (_("Remote reverse-continue not supported."));
6438 strcpy (buf, step ? "bs" : "bc");
6440 else if (siggnal != GDB_SIGNAL_0)
6442 buf[0] = step ? 'S' : 'C';
6443 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
6444 buf[2] = tohex (((int) siggnal) & 0xf);
6445 buf[3] = '\0';
6447 else
6448 strcpy (buf, step ? "s" : "c");
6450 putpkt (buf);
6453 /* Resume the remote inferior by using a "vCont" packet. SCOPE_PTID,
6454 STEP, and SIGGNAL have the same meaning as in target_resume. This
6455 function returns non-zero iff it resumes the inferior.
6457 This function issues a strict subset of all possible vCont commands
6458 at the moment. */
6461 remote_target::remote_resume_with_vcont (ptid_t scope_ptid, int step,
6462 enum gdb_signal siggnal)
6464 struct remote_state *rs = get_remote_state ();
6465 char *p;
6466 char *endp;
6468 /* No reverse execution actions defined for vCont. */
6469 if (::execution_direction == EXEC_REVERSE)
6470 return 0;
6472 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6473 remote_vcont_probe ();
6475 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
6476 return 0;
6478 p = rs->buf.data ();
6479 endp = p + get_remote_packet_size ();
6481 /* If we could generate a wider range of packets, we'd have to worry
6482 about overflowing BUF. Should there be a generic
6483 "multi-part-packet" packet? */
6485 p += xsnprintf (p, endp - p, "vCont");
6487 if (scope_ptid == magic_null_ptid)
6489 /* MAGIC_NULL_PTID means that we don't have any active threads,
6490 so we don't have any TID numbers the inferior will
6491 understand. Make sure to only send forms that do not specify
6492 a TID. */
6493 append_resumption (p, endp, minus_one_ptid, step, siggnal);
6495 else if (scope_ptid == minus_one_ptid || scope_ptid.is_pid ())
6497 /* Resume all threads (of all processes, or of a single
6498 process), with preference for INFERIOR_PTID. This assumes
6499 inferior_ptid belongs to the set of all threads we are about
6500 to resume. */
6501 if (step || siggnal != GDB_SIGNAL_0)
6503 /* Step inferior_ptid, with or without signal. */
6504 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
6507 /* Also pass down any pending signaled resumption for other
6508 threads not the current. */
6509 p = append_pending_thread_resumptions (p, endp, scope_ptid);
6511 /* And continue others without a signal. */
6512 append_resumption (p, endp, scope_ptid, /*step=*/ 0, GDB_SIGNAL_0);
6514 else
6516 /* Scheduler locking; resume only SCOPE_PTID. */
6517 append_resumption (p, endp, scope_ptid, step, siggnal);
6520 gdb_assert (strlen (rs->buf.data ()) < get_remote_packet_size ());
6521 putpkt (rs->buf);
6523 if (target_is_non_stop_p ())
6525 /* In non-stop, the stub replies to vCont with "OK". The stop
6526 reply will be reported asynchronously by means of a `%Stop'
6527 notification. */
6528 getpkt (&rs->buf, 0);
6529 if (strcmp (rs->buf.data (), "OK") != 0)
6530 error (_("Unexpected vCont reply in non-stop mode: %s"),
6531 rs->buf.data ());
6534 return 1;
6537 /* Tell the remote machine to resume. */
6539 void
6540 remote_target::resume (ptid_t scope_ptid, int step, enum gdb_signal siggnal)
6542 struct remote_state *rs = get_remote_state ();
6544 /* When connected in non-stop mode, the core resumes threads
6545 individually. Resuming remote threads directly in target_resume
6546 would thus result in sending one packet per thread. Instead, to
6547 minimize roundtrip latency, here we just store the resume
6548 request (put the thread in RESUMED_PENDING_VCONT state); the actual remote
6549 resumption will be done in remote_target::commit_resume, where we'll be
6550 able to do vCont action coalescing. */
6551 if (target_is_non_stop_p () && ::execution_direction != EXEC_REVERSE)
6553 remote_thread_info *remote_thr
6554 = get_remote_thread_info (inferior_thread ());
6556 /* We don't expect the core to ask to resume an already resumed (from
6557 its point of view) thread. */
6558 gdb_assert (remote_thr->get_resume_state () == resume_state::NOT_RESUMED);
6560 remote_thr->set_resumed_pending_vcont (step, siggnal);
6562 /* There's actually nothing that says that the core can't
6563 request a wildcard resume in non-stop mode, though. It's
6564 just that we know it doesn't currently, so we don't bother
6565 with it. */
6566 gdb_assert (scope_ptid == inferior_ptid);
6567 return;
6570 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
6571 (explained in remote-notif.c:handle_notification) so
6572 remote_notif_process is not called. We need find a place where
6573 it is safe to start a 'vNotif' sequence. It is good to do it
6574 before resuming inferior, because inferior was stopped and no RSP
6575 traffic at that moment. */
6576 if (!target_is_non_stop_p ())
6577 remote_notif_process (rs->notif_state, &notif_client_stop);
6579 rs->last_resume_exec_dir = ::execution_direction;
6581 /* Prefer vCont, and fallback to s/c/S/C, which use Hc. */
6582 if (!remote_resume_with_vcont (scope_ptid, step, siggnal))
6583 remote_resume_with_hc (scope_ptid, step, siggnal);
6585 /* Update resumed state tracked by the remote target. */
6586 for (thread_info *tp : all_non_exited_threads (this, scope_ptid))
6587 get_remote_thread_info (tp)->set_resumed ();
6589 /* We've just told the target to resume. The remote server will
6590 wait for the inferior to stop, and then send a stop reply. In
6591 the mean time, we can't start another command/query ourselves
6592 because the stub wouldn't be ready to process it. This applies
6593 only to the base all-stop protocol, however. In non-stop (which
6594 only supports vCont), the stub replies with an "OK", and is
6595 immediate able to process further serial input. */
6596 if (!target_is_non_stop_p ())
6597 rs->waiting_for_stop_reply = 1;
6600 /* Private per-inferior info for target remote processes. */
6602 struct remote_inferior : public private_inferior
6604 /* Whether we can send a wildcard vCont for this process. */
6605 bool may_wildcard_vcont = true;
6608 /* Get the remote private inferior data associated to INF. */
6610 static remote_inferior *
6611 get_remote_inferior (inferior *inf)
6613 if (inf->priv == NULL)
6614 inf->priv.reset (new remote_inferior);
6616 return gdb::checked_static_cast<remote_inferior *> (inf->priv.get ());
6619 /* Class used to track the construction of a vCont packet in the
6620 outgoing packet buffer. This is used to send multiple vCont
6621 packets if we have more actions than would fit a single packet. */
6623 class vcont_builder
6625 public:
6626 explicit vcont_builder (remote_target *remote)
6627 : m_remote (remote)
6629 restart ();
6632 void flush ();
6633 void push_action (ptid_t ptid, bool step, gdb_signal siggnal);
6635 private:
6636 void restart ();
6638 /* The remote target. */
6639 remote_target *m_remote;
6641 /* Pointer to the first action. P points here if no action has been
6642 appended yet. */
6643 char *m_first_action;
6645 /* Where the next action will be appended. */
6646 char *m_p;
6648 /* The end of the buffer. Must never write past this. */
6649 char *m_endp;
6652 /* Prepare the outgoing buffer for a new vCont packet. */
6654 void
6655 vcont_builder::restart ()
6657 struct remote_state *rs = m_remote->get_remote_state ();
6659 m_p = rs->buf.data ();
6660 m_endp = m_p + m_remote->get_remote_packet_size ();
6661 m_p += xsnprintf (m_p, m_endp - m_p, "vCont");
6662 m_first_action = m_p;
6665 /* If the vCont packet being built has any action, send it to the
6666 remote end. */
6668 void
6669 vcont_builder::flush ()
6671 struct remote_state *rs;
6673 if (m_p == m_first_action)
6674 return;
6676 rs = m_remote->get_remote_state ();
6677 m_remote->putpkt (rs->buf);
6678 m_remote->getpkt (&rs->buf, 0);
6679 if (strcmp (rs->buf.data (), "OK") != 0)
6680 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf.data ());
6683 /* The largest action is range-stepping, with its two addresses. This
6684 is more than sufficient. If a new, bigger action is created, it'll
6685 quickly trigger a failed assertion in append_resumption (and we'll
6686 just bump this). */
6687 #define MAX_ACTION_SIZE 200
6689 /* Append a new vCont action in the outgoing packet being built. If
6690 the action doesn't fit the packet along with previous actions, push
6691 what we've got so far to the remote end and start over a new vCont
6692 packet (with the new action). */
6694 void
6695 vcont_builder::push_action (ptid_t ptid, bool step, gdb_signal siggnal)
6697 char buf[MAX_ACTION_SIZE + 1];
6699 char *endp = m_remote->append_resumption (buf, buf + sizeof (buf),
6700 ptid, step, siggnal);
6702 /* Check whether this new action would fit in the vCont packet along
6703 with previous actions. If not, send what we've got so far and
6704 start a new vCont packet. */
6705 size_t rsize = endp - buf;
6706 if (rsize > m_endp - m_p)
6708 flush ();
6709 restart ();
6711 /* Should now fit. */
6712 gdb_assert (rsize <= m_endp - m_p);
6715 memcpy (m_p, buf, rsize);
6716 m_p += rsize;
6717 *m_p = '\0';
6720 /* to_commit_resume implementation. */
6722 void
6723 remote_target::commit_resumed ()
6725 /* If connected in all-stop mode, we'd send the remote resume
6726 request directly from remote_resume. Likewise if
6727 reverse-debugging, as there are no defined vCont actions for
6728 reverse execution. */
6729 if (!target_is_non_stop_p () || ::execution_direction == EXEC_REVERSE)
6730 return;
6732 /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
6733 instead of resuming all threads of each process individually.
6734 However, if any thread of a process must remain halted, we can't
6735 send wildcard resumes and must send one action per thread.
6737 Care must be taken to not resume threads/processes the server
6738 side already told us are stopped, but the core doesn't know about
6739 yet, because the events are still in the vStopped notification
6740 queue. For example:
6742 #1 => vCont s:p1.1;c
6743 #2 <= OK
6744 #3 <= %Stopped T05 p1.1
6745 #4 => vStopped
6746 #5 <= T05 p1.2
6747 #6 => vStopped
6748 #7 <= OK
6749 #8 (infrun handles the stop for p1.1 and continues stepping)
6750 #9 => vCont s:p1.1;c
6752 The last vCont above would resume thread p1.2 by mistake, because
6753 the server has no idea that the event for p1.2 had not been
6754 handled yet.
6756 The server side must similarly ignore resume actions for the
6757 thread that has a pending %Stopped notification (and any other
6758 threads with events pending), until GDB acks the notification
6759 with vStopped. Otherwise, e.g., the following case is
6760 mishandled:
6762 #1 => g (or any other packet)
6763 #2 <= [registers]
6764 #3 <= %Stopped T05 p1.2
6765 #4 => vCont s:p1.1;c
6766 #5 <= OK
6768 Above, the server must not resume thread p1.2. GDB can't know
6769 that p1.2 stopped until it acks the %Stopped notification, and
6770 since from GDB's perspective all threads should be running, it
6771 sends a "c" action.
6773 Finally, special care must also be given to handling fork/vfork
6774 events. A (v)fork event actually tells us that two processes
6775 stopped -- the parent and the child. Until we follow the fork,
6776 we must not resume the child. Therefore, if we have a pending
6777 fork follow, we must not send a global wildcard resume action
6778 (vCont;c). We can still send process-wide wildcards though. */
6780 /* Start by assuming a global wildcard (vCont;c) is possible. */
6781 bool may_global_wildcard_vcont = true;
6783 /* And assume every process is individually wildcard-able too. */
6784 for (inferior *inf : all_non_exited_inferiors (this))
6786 remote_inferior *priv = get_remote_inferior (inf);
6788 priv->may_wildcard_vcont = true;
6791 /* Check for any pending events (not reported or processed yet) and
6792 disable process and global wildcard resumes appropriately. */
6793 check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
6795 bool any_pending_vcont_resume = false;
6797 for (thread_info *tp : all_non_exited_threads (this))
6799 remote_thread_info *priv = get_remote_thread_info (tp);
6801 /* If a thread of a process is not meant to be resumed, then we
6802 can't wildcard that process. */
6803 if (priv->get_resume_state () == resume_state::NOT_RESUMED)
6805 get_remote_inferior (tp->inf)->may_wildcard_vcont = false;
6807 /* And if we can't wildcard a process, we can't wildcard
6808 everything either. */
6809 may_global_wildcard_vcont = false;
6810 continue;
6813 if (priv->get_resume_state () == resume_state::RESUMED_PENDING_VCONT)
6814 any_pending_vcont_resume = true;
6816 /* If a thread is the parent of an unfollowed fork, then we
6817 can't do a global wildcard, as that would resume the fork
6818 child. */
6819 if (thread_pending_fork_status (tp) != nullptr)
6820 may_global_wildcard_vcont = false;
6823 /* We didn't have any resumed thread pending a vCont resume, so nothing to
6824 do. */
6825 if (!any_pending_vcont_resume)
6826 return;
6828 /* Now let's build the vCont packet(s). Actions must be appended
6829 from narrower to wider scopes (thread -> process -> global). If
6830 we end up with too many actions for a single packet vcont_builder
6831 flushes the current vCont packet to the remote side and starts a
6832 new one. */
6833 struct vcont_builder vcont_builder (this);
6835 /* Threads first. */
6836 for (thread_info *tp : all_non_exited_threads (this))
6838 remote_thread_info *remote_thr = get_remote_thread_info (tp);
6840 /* If the thread was previously vCont-resumed, no need to send a specific
6841 action for it. If we didn't receive a resume request for it, don't
6842 send an action for it either. */
6843 if (remote_thr->get_resume_state () != resume_state::RESUMED_PENDING_VCONT)
6844 continue;
6846 gdb_assert (!thread_is_in_step_over_chain (tp));
6848 /* We should never be commit-resuming a thread that has a stop reply.
6849 Otherwise, we would end up reporting a stop event for a thread while
6850 it is running on the remote target. */
6851 remote_state *rs = get_remote_state ();
6852 for (const auto &stop_reply : rs->stop_reply_queue)
6853 gdb_assert (stop_reply->ptid != tp->ptid);
6855 const resumed_pending_vcont_info &info
6856 = remote_thr->resumed_pending_vcont_info ();
6858 /* Check if we need to send a specific action for this thread. If not,
6859 it will be included in a wildcard resume instead. */
6860 if (info.step || info.sig != GDB_SIGNAL_0
6861 || !get_remote_inferior (tp->inf)->may_wildcard_vcont)
6862 vcont_builder.push_action (tp->ptid, info.step, info.sig);
6864 remote_thr->set_resumed ();
6867 /* Now check whether we can send any process-wide wildcard. This is
6868 to avoid sending a global wildcard in the case nothing is
6869 supposed to be resumed. */
6870 bool any_process_wildcard = false;
6872 for (inferior *inf : all_non_exited_inferiors (this))
6874 if (get_remote_inferior (inf)->may_wildcard_vcont)
6876 any_process_wildcard = true;
6877 break;
6881 if (any_process_wildcard)
6883 /* If all processes are wildcard-able, then send a single "c"
6884 action, otherwise, send an "all (-1) threads of process"
6885 continue action for each running process, if any. */
6886 if (may_global_wildcard_vcont)
6888 vcont_builder.push_action (minus_one_ptid,
6889 false, GDB_SIGNAL_0);
6891 else
6893 for (inferior *inf : all_non_exited_inferiors (this))
6895 if (get_remote_inferior (inf)->may_wildcard_vcont)
6897 vcont_builder.push_action (ptid_t (inf->pid),
6898 false, GDB_SIGNAL_0);
6904 vcont_builder.flush ();
6907 /* Implementation of target_has_pending_events. */
6909 bool
6910 remote_target::has_pending_events ()
6912 if (target_can_async_p ())
6914 remote_state *rs = get_remote_state ();
6916 if (async_event_handler_marked (rs->remote_async_inferior_event_token))
6917 return true;
6919 /* Note that BUFCNT can be negative, indicating sticky
6920 error. */
6921 if (rs->remote_desc->bufcnt != 0)
6922 return true;
6924 return false;
6929 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
6930 thread, all threads of a remote process, or all threads of all
6931 processes. */
6933 void
6934 remote_target::remote_stop_ns (ptid_t ptid)
6936 struct remote_state *rs = get_remote_state ();
6937 char *p = rs->buf.data ();
6938 char *endp = p + get_remote_packet_size ();
6940 /* If any thread that needs to stop was resumed but pending a vCont
6941 resume, generate a phony stop_reply. However, first check
6942 whether the thread wasn't resumed with a signal. Generating a
6943 phony stop in that case would result in losing the signal. */
6944 bool needs_commit = false;
6945 for (thread_info *tp : all_non_exited_threads (this, ptid))
6947 remote_thread_info *remote_thr = get_remote_thread_info (tp);
6949 if (remote_thr->get_resume_state ()
6950 == resume_state::RESUMED_PENDING_VCONT)
6952 const resumed_pending_vcont_info &info
6953 = remote_thr->resumed_pending_vcont_info ();
6954 if (info.sig != GDB_SIGNAL_0)
6956 /* This signal must be forwarded to the inferior. We
6957 could commit-resume just this thread, but its simpler
6958 to just commit-resume everything. */
6959 needs_commit = true;
6960 break;
6965 if (needs_commit)
6966 commit_resumed ();
6967 else
6968 for (thread_info *tp : all_non_exited_threads (this, ptid))
6970 remote_thread_info *remote_thr = get_remote_thread_info (tp);
6972 if (remote_thr->get_resume_state ()
6973 == resume_state::RESUMED_PENDING_VCONT)
6975 remote_debug_printf ("Enqueueing phony stop reply for thread pending "
6976 "vCont-resume (%d, %ld, %s)", tp->ptid.pid(),
6977 tp->ptid.lwp (),
6978 pulongest (tp->ptid.tid ()));
6980 /* Check that the thread wasn't resumed with a signal.
6981 Generating a phony stop would result in losing the
6982 signal. */
6983 const resumed_pending_vcont_info &info
6984 = remote_thr->resumed_pending_vcont_info ();
6985 gdb_assert (info.sig == GDB_SIGNAL_0);
6987 stop_reply *sr = new stop_reply ();
6988 sr->ptid = tp->ptid;
6989 sr->rs = rs;
6990 sr->ws.set_stopped (GDB_SIGNAL_0);
6991 sr->arch = tp->inf->gdbarch;
6992 sr->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6993 sr->watch_data_address = 0;
6994 sr->core = 0;
6995 this->push_stop_reply (sr);
6997 /* Pretend that this thread was actually resumed on the
6998 remote target, then stopped. If we leave it in the
6999 RESUMED_PENDING_VCONT state and the commit_resumed
7000 method is called while the stop reply is still in the
7001 queue, we'll end up reporting a stop event to the core
7002 for that thread while it is running on the remote
7003 target... that would be bad. */
7004 remote_thr->set_resumed ();
7008 /* FIXME: This supports_vCont_probed check is a workaround until
7009 packet_support is per-connection. */
7010 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN
7011 || !rs->supports_vCont_probed)
7012 remote_vcont_probe ();
7014 if (!rs->supports_vCont.t)
7015 error (_("Remote server does not support stopping threads"));
7017 if (ptid == minus_one_ptid
7018 || (!remote_multi_process_p (rs) && ptid.is_pid ()))
7019 p += xsnprintf (p, endp - p, "vCont;t");
7020 else
7022 ptid_t nptid;
7024 p += xsnprintf (p, endp - p, "vCont;t:");
7026 if (ptid.is_pid ())
7027 /* All (-1) threads of process. */
7028 nptid = ptid_t (ptid.pid (), -1);
7029 else
7031 /* Small optimization: if we already have a stop reply for
7032 this thread, no use in telling the stub we want this
7033 stopped. */
7034 if (peek_stop_reply (ptid))
7035 return;
7037 nptid = ptid;
7040 write_ptid (p, endp, nptid);
7043 /* In non-stop, we get an immediate OK reply. The stop reply will
7044 come in asynchronously by notification. */
7045 putpkt (rs->buf);
7046 getpkt (&rs->buf, 0);
7047 if (strcmp (rs->buf.data (), "OK") != 0)
7048 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid).c_str (),
7049 rs->buf.data ());
7052 /* All-stop version of target_interrupt. Sends a break or a ^C to
7053 interrupt the remote target. It is undefined which thread of which
7054 process reports the interrupt. */
7056 void
7057 remote_target::remote_interrupt_as ()
7059 struct remote_state *rs = get_remote_state ();
7061 rs->ctrlc_pending_p = 1;
7063 /* If the inferior is stopped already, but the core didn't know
7064 about it yet, just ignore the request. The pending stop events
7065 will be collected in remote_wait. */
7066 if (stop_reply_queue_length () > 0)
7067 return;
7069 /* Send interrupt_sequence to remote target. */
7070 send_interrupt_sequence ();
7073 /* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
7074 the remote target. It is undefined which thread of which process
7075 reports the interrupt. Throws an error if the packet is not
7076 supported by the server. */
7078 void
7079 remote_target::remote_interrupt_ns ()
7081 struct remote_state *rs = get_remote_state ();
7082 char *p = rs->buf.data ();
7083 char *endp = p + get_remote_packet_size ();
7085 xsnprintf (p, endp - p, "vCtrlC");
7087 /* In non-stop, we get an immediate OK reply. The stop reply will
7088 come in asynchronously by notification. */
7089 putpkt (rs->buf);
7090 getpkt (&rs->buf, 0);
7092 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
7094 case PACKET_OK:
7095 break;
7096 case PACKET_UNKNOWN:
7097 error (_("No support for interrupting the remote target."));
7098 case PACKET_ERROR:
7099 error (_("Interrupting target failed: %s"), rs->buf.data ());
7103 /* Implement the to_stop function for the remote targets. */
7105 void
7106 remote_target::stop (ptid_t ptid)
7108 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7110 if (target_is_non_stop_p ())
7111 remote_stop_ns (ptid);
7112 else
7114 /* We don't currently have a way to transparently pause the
7115 remote target in all-stop mode. Interrupt it instead. */
7116 remote_interrupt_as ();
7120 /* Implement the to_interrupt function for the remote targets. */
7122 void
7123 remote_target::interrupt ()
7125 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7127 if (target_is_non_stop_p ())
7128 remote_interrupt_ns ();
7129 else
7130 remote_interrupt_as ();
7133 /* Implement the to_pass_ctrlc function for the remote targets. */
7135 void
7136 remote_target::pass_ctrlc ()
7138 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7140 struct remote_state *rs = get_remote_state ();
7142 /* If we're starting up, we're not fully synced yet. Quit
7143 immediately. */
7144 if (rs->starting_up)
7145 quit ();
7146 /* If ^C has already been sent once, offer to disconnect. */
7147 else if (rs->ctrlc_pending_p)
7148 interrupt_query ();
7149 else
7150 target_interrupt ();
7153 /* Ask the user what to do when an interrupt is received. */
7155 void
7156 remote_target::interrupt_query ()
7158 struct remote_state *rs = get_remote_state ();
7160 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
7162 if (query (_("The target is not responding to interrupt requests.\n"
7163 "Stop debugging it? ")))
7165 remote_unpush_target (this);
7166 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
7169 else
7171 if (query (_("Interrupted while waiting for the program.\n"
7172 "Give up waiting? ")))
7173 quit ();
7177 /* Enable/disable target terminal ownership. Most targets can use
7178 terminal groups to control terminal ownership. Remote targets are
7179 different in that explicit transfer of ownership to/from GDB/target
7180 is required. */
7182 void
7183 remote_target::terminal_inferior ()
7185 /* NOTE: At this point we could also register our selves as the
7186 recipient of all input. Any characters typed could then be
7187 passed on down to the target. */
7190 void
7191 remote_target::terminal_ours ()
7195 static void
7196 remote_console_output (const char *msg)
7198 const char *p;
7200 for (p = msg; p[0] && p[1]; p += 2)
7202 char tb[2];
7203 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
7205 tb[0] = c;
7206 tb[1] = 0;
7207 gdb_stdtarg->puts (tb);
7209 gdb_stdtarg->flush ();
7212 /* Return the length of the stop reply queue. */
7215 remote_target::stop_reply_queue_length ()
7217 remote_state *rs = get_remote_state ();
7218 return rs->stop_reply_queue.size ();
7221 static void
7222 remote_notif_stop_parse (remote_target *remote,
7223 struct notif_client *self, const char *buf,
7224 struct notif_event *event)
7226 remote->remote_parse_stop_reply (buf, (struct stop_reply *) event);
7229 static void
7230 remote_notif_stop_ack (remote_target *remote,
7231 struct notif_client *self, const char *buf,
7232 struct notif_event *event)
7234 struct stop_reply *stop_reply = (struct stop_reply *) event;
7236 /* acknowledge */
7237 putpkt (remote, self->ack_command);
7239 /* Kind can be TARGET_WAITKIND_IGNORE if we have meanwhile discarded
7240 the notification. It was left in the queue because we need to
7241 acknowledge it and pull the rest of the notifications out. */
7242 if (stop_reply->ws.kind () != TARGET_WAITKIND_IGNORE)
7243 remote->push_stop_reply (stop_reply);
7246 static int
7247 remote_notif_stop_can_get_pending_events (remote_target *remote,
7248 struct notif_client *self)
7250 /* We can't get pending events in remote_notif_process for
7251 notification stop, and we have to do this in remote_wait_ns
7252 instead. If we fetch all queued events from stub, remote stub
7253 may exit and we have no chance to process them back in
7254 remote_wait_ns. */
7255 remote_state *rs = remote->get_remote_state ();
7256 mark_async_event_handler (rs->remote_async_inferior_event_token);
7257 return 0;
7260 stop_reply::~stop_reply ()
7262 for (cached_reg_t &reg : regcache)
7263 xfree (reg.data);
7266 static notif_event_up
7267 remote_notif_stop_alloc_reply ()
7269 return notif_event_up (new struct stop_reply ());
7272 /* A client of notification Stop. */
7274 struct notif_client notif_client_stop =
7276 "Stop",
7277 "vStopped",
7278 remote_notif_stop_parse,
7279 remote_notif_stop_ack,
7280 remote_notif_stop_can_get_pending_events,
7281 remote_notif_stop_alloc_reply,
7282 REMOTE_NOTIF_STOP,
7285 /* If CONTEXT contains any fork child threads that have not been
7286 reported yet, remove them from the CONTEXT list. If such a
7287 thread exists it is because we are stopped at a fork catchpoint
7288 and have not yet called follow_fork, which will set up the
7289 host-side data structures for the new process. */
7291 void
7292 remote_target::remove_new_fork_children (threads_listing_context *context)
7294 struct notif_client *notif = &notif_client_stop;
7296 /* For any threads stopped at a fork event, remove the corresponding
7297 fork child threads from the CONTEXT list. */
7298 for (thread_info *thread : all_non_exited_threads (this))
7300 const target_waitstatus *ws = thread_pending_fork_status (thread);
7302 if (ws == nullptr)
7303 continue;
7305 context->remove_thread (ws->child_ptid ());
7308 /* Check for any pending fork events (not reported or processed yet)
7309 in process PID and remove those fork child threads from the
7310 CONTEXT list as well. */
7311 remote_notif_get_pending_events (notif);
7312 for (auto &event : get_remote_state ()->stop_reply_queue)
7313 if (event->ws.kind () == TARGET_WAITKIND_FORKED
7314 || event->ws.kind () == TARGET_WAITKIND_VFORKED)
7315 context->remove_thread (event->ws.child_ptid ());
7316 else if (event->ws.kind () == TARGET_WAITKIND_THREAD_EXITED)
7317 context->remove_thread (event->ptid);
7320 /* Check whether any event pending in the vStopped queue would prevent a
7321 global or process wildcard vCont action. Set *may_global_wildcard to
7322 false if we can't do a global wildcard (vCont;c), and clear the event
7323 inferior's may_wildcard_vcont flag if we can't do a process-wide
7324 wildcard resume (vCont;c:pPID.-1). */
7326 void
7327 remote_target::check_pending_events_prevent_wildcard_vcont
7328 (bool *may_global_wildcard)
7330 struct notif_client *notif = &notif_client_stop;
7332 remote_notif_get_pending_events (notif);
7333 for (auto &event : get_remote_state ()->stop_reply_queue)
7335 if (event->ws.kind () == TARGET_WAITKIND_NO_RESUMED
7336 || event->ws.kind () == TARGET_WAITKIND_NO_HISTORY)
7337 continue;
7339 if (event->ws.kind () == TARGET_WAITKIND_FORKED
7340 || event->ws.kind () == TARGET_WAITKIND_VFORKED)
7341 *may_global_wildcard = false;
7343 /* This may be the first time we heard about this process.
7344 Regardless, we must not do a global wildcard resume, otherwise
7345 we'd resume this process too. */
7346 *may_global_wildcard = false;
7347 if (event->ptid != null_ptid)
7349 inferior *inf = find_inferior_ptid (this, event->ptid);
7350 if (inf != NULL)
7351 get_remote_inferior (inf)->may_wildcard_vcont = false;
7356 /* Discard all pending stop replies of inferior INF. */
7358 void
7359 remote_target::discard_pending_stop_replies (struct inferior *inf)
7361 struct stop_reply *reply;
7362 struct remote_state *rs = get_remote_state ();
7363 struct remote_notif_state *rns = rs->notif_state;
7365 /* This function can be notified when an inferior exists. When the
7366 target is not remote, the notification state is NULL. */
7367 if (rs->remote_desc == NULL)
7368 return;
7370 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
7372 /* Discard the in-flight notification. */
7373 if (reply != NULL && reply->ptid.pid () == inf->pid)
7375 /* Leave the notification pending, since the server expects that
7376 we acknowledge it with vStopped. But clear its contents, so
7377 that later on when we acknowledge it, we also discard it. */
7378 remote_debug_printf
7379 ("discarding in-flight notification: ptid: %s, ws: %s\n",
7380 reply->ptid.to_string().c_str(),
7381 reply->ws.to_string ().c_str ());
7382 reply->ws.set_ignore ();
7385 /* Discard the stop replies we have already pulled with
7386 vStopped. */
7387 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7388 rs->stop_reply_queue.end (),
7389 [=] (const stop_reply_up &event)
7391 return event->ptid.pid () == inf->pid;
7393 for (auto it = iter; it != rs->stop_reply_queue.end (); ++it)
7394 remote_debug_printf
7395 ("discarding queued stop reply: ptid: %s, ws: %s\n",
7396 reply->ptid.to_string().c_str(),
7397 reply->ws.to_string ().c_str ());
7398 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7401 /* Discard the stop replies for RS in stop_reply_queue. */
7403 void
7404 remote_target::discard_pending_stop_replies_in_queue ()
7406 remote_state *rs = get_remote_state ();
7408 /* Discard the stop replies we have already pulled with
7409 vStopped. */
7410 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7411 rs->stop_reply_queue.end (),
7412 [=] (const stop_reply_up &event)
7414 return event->rs == rs;
7416 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7419 /* Remove the first reply in 'stop_reply_queue' which matches
7420 PTID. */
7422 struct stop_reply *
7423 remote_target::remote_notif_remove_queued_reply (ptid_t ptid)
7425 remote_state *rs = get_remote_state ();
7427 auto iter = std::find_if (rs->stop_reply_queue.begin (),
7428 rs->stop_reply_queue.end (),
7429 [=] (const stop_reply_up &event)
7431 return event->ptid.matches (ptid);
7433 struct stop_reply *result;
7434 if (iter == rs->stop_reply_queue.end ())
7435 result = nullptr;
7436 else
7438 result = iter->release ();
7439 rs->stop_reply_queue.erase (iter);
7442 if (notif_debug)
7443 gdb_printf (gdb_stdlog,
7444 "notif: discard queued event: 'Stop' in %s\n",
7445 ptid.to_string ().c_str ());
7447 return result;
7450 /* Look for a queued stop reply belonging to PTID. If one is found,
7451 remove it from the queue, and return it. Returns NULL if none is
7452 found. If there are still queued events left to process, tell the
7453 event loop to get back to target_wait soon. */
7455 struct stop_reply *
7456 remote_target::queued_stop_reply (ptid_t ptid)
7458 remote_state *rs = get_remote_state ();
7459 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
7461 if (!rs->stop_reply_queue.empty () && target_can_async_p ())
7463 /* There's still at least an event left. */
7464 mark_async_event_handler (rs->remote_async_inferior_event_token);
7467 return r;
7470 /* Push a fully parsed stop reply in the stop reply queue. Since we
7471 know that we now have at least one queued event left to pass to the
7472 core side, tell the event loop to get back to target_wait soon. */
7474 void
7475 remote_target::push_stop_reply (struct stop_reply *new_event)
7477 remote_state *rs = get_remote_state ();
7478 rs->stop_reply_queue.push_back (stop_reply_up (new_event));
7480 if (notif_debug)
7481 gdb_printf (gdb_stdlog,
7482 "notif: push 'Stop' %s to queue %d\n",
7483 new_event->ptid.to_string ().c_str (),
7484 int (rs->stop_reply_queue.size ()));
7486 /* Mark the pending event queue only if async mode is currently enabled.
7487 If async mode is not currently enabled, then, if it later becomes
7488 enabled, and there are events in this queue, we will mark the event
7489 token at that point, see remote_target::async. */
7490 if (target_is_async_p ())
7491 mark_async_event_handler (rs->remote_async_inferior_event_token);
7494 /* Returns true if we have a stop reply for PTID. */
7497 remote_target::peek_stop_reply (ptid_t ptid)
7499 remote_state *rs = get_remote_state ();
7500 for (auto &event : rs->stop_reply_queue)
7501 if (ptid == event->ptid
7502 && event->ws.kind () == TARGET_WAITKIND_STOPPED)
7503 return 1;
7504 return 0;
7507 /* Helper for remote_parse_stop_reply. Return nonzero if the substring
7508 starting with P and ending with PEND matches PREFIX. */
7510 static int
7511 strprefix (const char *p, const char *pend, const char *prefix)
7513 for ( ; p < pend; p++, prefix++)
7514 if (*p != *prefix)
7515 return 0;
7516 return *prefix == '\0';
7519 /* Parse the stop reply in BUF. Either the function succeeds, and the
7520 result is stored in EVENT, or throws an error. */
7522 void
7523 remote_target::remote_parse_stop_reply (const char *buf, stop_reply *event)
7525 remote_arch_state *rsa = NULL;
7526 ULONGEST addr;
7527 const char *p;
7528 int skipregs = 0;
7530 event->ptid = null_ptid;
7531 event->rs = get_remote_state ();
7532 event->ws.set_ignore ();
7533 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
7534 event->regcache.clear ();
7535 event->core = -1;
7537 switch (buf[0])
7539 case 'T': /* Status with PC, SP, FP, ... */
7540 /* Expedited reply, containing Signal, {regno, reg} repeat. */
7541 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
7542 ss = signal number
7543 n... = register number
7544 r... = register contents
7547 p = &buf[3]; /* after Txx */
7548 while (*p)
7550 const char *p1;
7551 int fieldsize;
7553 p1 = strchr (p, ':');
7554 if (p1 == NULL)
7555 error (_("Malformed packet(a) (missing colon): %s\n\
7556 Packet: '%s'\n"),
7557 p, buf);
7558 if (p == p1)
7559 error (_("Malformed packet(a) (missing register number): %s\n\
7560 Packet: '%s'\n"),
7561 p, buf);
7563 /* Some "registers" are actually extended stop information.
7564 Note if you're adding a new entry here: GDB 7.9 and
7565 earlier assume that all register "numbers" that start
7566 with an hex digit are real register numbers. Make sure
7567 the server only sends such a packet if it knows the
7568 client understands it. */
7570 if (strprefix (p, p1, "thread"))
7571 event->ptid = read_ptid (++p1, &p);
7572 else if (strprefix (p, p1, "syscall_entry"))
7574 ULONGEST sysno;
7576 p = unpack_varlen_hex (++p1, &sysno);
7577 event->ws.set_syscall_entry ((int) sysno);
7579 else if (strprefix (p, p1, "syscall_return"))
7581 ULONGEST sysno;
7583 p = unpack_varlen_hex (++p1, &sysno);
7584 event->ws.set_syscall_return ((int) sysno);
7586 else if (strprefix (p, p1, "watch")
7587 || strprefix (p, p1, "rwatch")
7588 || strprefix (p, p1, "awatch"))
7590 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
7591 p = unpack_varlen_hex (++p1, &addr);
7592 event->watch_data_address = (CORE_ADDR) addr;
7594 else if (strprefix (p, p1, "swbreak"))
7596 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
7598 /* Make sure the stub doesn't forget to indicate support
7599 with qSupported. */
7600 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
7601 error (_("Unexpected swbreak stop reason"));
7603 /* The value part is documented as "must be empty",
7604 though we ignore it, in case we ever decide to make
7605 use of it in a backward compatible way. */
7606 p = strchrnul (p1 + 1, ';');
7608 else if (strprefix (p, p1, "hwbreak"))
7610 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
7612 /* Make sure the stub doesn't forget to indicate support
7613 with qSupported. */
7614 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
7615 error (_("Unexpected hwbreak stop reason"));
7617 /* See above. */
7618 p = strchrnul (p1 + 1, ';');
7620 else if (strprefix (p, p1, "library"))
7622 event->ws.set_loaded ();
7623 p = strchrnul (p1 + 1, ';');
7625 else if (strprefix (p, p1, "replaylog"))
7627 event->ws.set_no_history ();
7628 /* p1 will indicate "begin" or "end", but it makes
7629 no difference for now, so ignore it. */
7630 p = strchrnul (p1 + 1, ';');
7632 else if (strprefix (p, p1, "core"))
7634 ULONGEST c;
7636 p = unpack_varlen_hex (++p1, &c);
7637 event->core = c;
7639 else if (strprefix (p, p1, "fork"))
7640 event->ws.set_forked (read_ptid (++p1, &p));
7641 else if (strprefix (p, p1, "vfork"))
7642 event->ws.set_vforked (read_ptid (++p1, &p));
7643 else if (strprefix (p, p1, "vforkdone"))
7645 event->ws.set_vfork_done ();
7646 p = strchrnul (p1 + 1, ';');
7648 else if (strprefix (p, p1, "exec"))
7650 ULONGEST ignored;
7651 int pathlen;
7653 /* Determine the length of the execd pathname. */
7654 p = unpack_varlen_hex (++p1, &ignored);
7655 pathlen = (p - p1) / 2;
7657 /* Save the pathname for event reporting and for
7658 the next run command. */
7659 gdb::unique_xmalloc_ptr<char> pathname
7660 ((char *) xmalloc (pathlen + 1));
7661 hex2bin (p1, (gdb_byte *) pathname.get (), pathlen);
7662 pathname.get ()[pathlen] = '\0';
7664 /* This is freed during event handling. */
7665 event->ws.set_execd (std::move (pathname));
7667 /* Skip the registers included in this packet, since
7668 they may be for an architecture different from the
7669 one used by the original program. */
7670 skipregs = 1;
7672 else if (strprefix (p, p1, "create"))
7674 event->ws.set_thread_created ();
7675 p = strchrnul (p1 + 1, ';');
7677 else
7679 ULONGEST pnum;
7680 const char *p_temp;
7682 if (skipregs)
7684 p = strchrnul (p1 + 1, ';');
7685 p++;
7686 continue;
7689 /* Maybe a real ``P'' register number. */
7690 p_temp = unpack_varlen_hex (p, &pnum);
7691 /* If the first invalid character is the colon, we got a
7692 register number. Otherwise, it's an unknown stop
7693 reason. */
7694 if (p_temp == p1)
7696 /* If we haven't parsed the event's thread yet, find
7697 it now, in order to find the architecture of the
7698 reported expedited registers. */
7699 if (event->ptid == null_ptid)
7701 /* If there is no thread-id information then leave
7702 the event->ptid as null_ptid. Later in
7703 process_stop_reply we will pick a suitable
7704 thread. */
7705 const char *thr = strstr (p1 + 1, ";thread:");
7706 if (thr != NULL)
7707 event->ptid = read_ptid (thr + strlen (";thread:"),
7708 NULL);
7711 if (rsa == NULL)
7713 inferior *inf
7714 = (event->ptid == null_ptid
7715 ? NULL
7716 : find_inferior_ptid (this, event->ptid));
7717 /* If this is the first time we learn anything
7718 about this process, skip the registers
7719 included in this packet, since we don't yet
7720 know which architecture to use to parse them.
7721 We'll determine the architecture later when
7722 we process the stop reply and retrieve the
7723 target description, via
7724 remote_notice_new_inferior ->
7725 post_create_inferior. */
7726 if (inf == NULL)
7728 p = strchrnul (p1 + 1, ';');
7729 p++;
7730 continue;
7733 event->arch = inf->gdbarch;
7734 rsa = event->rs->get_remote_arch_state (event->arch);
7737 packet_reg *reg
7738 = packet_reg_from_pnum (event->arch, rsa, pnum);
7739 cached_reg_t cached_reg;
7741 if (reg == NULL)
7742 error (_("Remote sent bad register number %s: %s\n\
7743 Packet: '%s'\n"),
7744 hex_string (pnum), p, buf);
7746 cached_reg.num = reg->regnum;
7747 cached_reg.data = (gdb_byte *)
7748 xmalloc (register_size (event->arch, reg->regnum));
7750 p = p1 + 1;
7751 fieldsize = hex2bin (p, cached_reg.data,
7752 register_size (event->arch, reg->regnum));
7753 p += 2 * fieldsize;
7754 if (fieldsize < register_size (event->arch, reg->regnum))
7755 warning (_("Remote reply is too short: %s"), buf);
7757 event->regcache.push_back (cached_reg);
7759 else
7761 /* Not a number. Silently skip unknown optional
7762 info. */
7763 p = strchrnul (p1 + 1, ';');
7767 if (*p != ';')
7768 error (_("Remote register badly formatted: %s\nhere: %s"),
7769 buf, p);
7770 ++p;
7773 if (event->ws.kind () != TARGET_WAITKIND_IGNORE)
7774 break;
7776 /* fall through */
7777 case 'S': /* Old style status, just signal only. */
7779 int sig;
7781 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
7782 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
7783 event->ws.set_stopped ((enum gdb_signal) sig);
7784 else
7785 event->ws.set_stopped (GDB_SIGNAL_UNKNOWN);
7787 break;
7788 case 'w': /* Thread exited. */
7790 ULONGEST value;
7792 p = unpack_varlen_hex (&buf[1], &value);
7793 event->ws.set_thread_exited (value);
7794 if (*p != ';')
7795 error (_("stop reply packet badly formatted: %s"), buf);
7796 event->ptid = read_ptid (++p, NULL);
7797 break;
7799 case 'W': /* Target exited. */
7800 case 'X':
7802 ULONGEST value;
7804 /* GDB used to accept only 2 hex chars here. Stubs should
7805 only send more if they detect GDB supports multi-process
7806 support. */
7807 p = unpack_varlen_hex (&buf[1], &value);
7809 if (buf[0] == 'W')
7811 /* The remote process exited. */
7812 event->ws.set_exited (value);
7814 else
7816 /* The remote process exited with a signal. */
7817 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
7818 event->ws.set_signalled ((enum gdb_signal) value);
7819 else
7820 event->ws.set_signalled (GDB_SIGNAL_UNKNOWN);
7823 /* If no process is specified, return null_ptid, and let the
7824 caller figure out the right process to use. */
7825 int pid = 0;
7826 if (*p == '\0')
7828 else if (*p == ';')
7830 p++;
7832 if (*p == '\0')
7834 else if (startswith (p, "process:"))
7836 ULONGEST upid;
7838 p += sizeof ("process:") - 1;
7839 unpack_varlen_hex (p, &upid);
7840 pid = upid;
7842 else
7843 error (_("unknown stop reply packet: %s"), buf);
7845 else
7846 error (_("unknown stop reply packet: %s"), buf);
7847 event->ptid = ptid_t (pid);
7849 break;
7850 case 'N':
7851 event->ws.set_no_resumed ();
7852 event->ptid = minus_one_ptid;
7853 break;
7857 /* When the stub wants to tell GDB about a new notification reply, it
7858 sends a notification (%Stop, for example). Those can come it at
7859 any time, hence, we have to make sure that any pending
7860 putpkt/getpkt sequence we're making is finished, before querying
7861 the stub for more events with the corresponding ack command
7862 (vStopped, for example). E.g., if we started a vStopped sequence
7863 immediately upon receiving the notification, something like this
7864 could happen:
7866 1.1) --> Hg 1
7867 1.2) <-- OK
7868 1.3) --> g
7869 1.4) <-- %Stop
7870 1.5) --> vStopped
7871 1.6) <-- (registers reply to step #1.3)
7873 Obviously, the reply in step #1.6 would be unexpected to a vStopped
7874 query.
7876 To solve this, whenever we parse a %Stop notification successfully,
7877 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
7878 doing whatever we were doing:
7880 2.1) --> Hg 1
7881 2.2) <-- OK
7882 2.3) --> g
7883 2.4) <-- %Stop
7884 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
7885 2.5) <-- (registers reply to step #2.3)
7887 Eventually after step #2.5, we return to the event loop, which
7888 notices there's an event on the
7889 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
7890 associated callback --- the function below. At this point, we're
7891 always safe to start a vStopped sequence. :
7893 2.6) --> vStopped
7894 2.7) <-- T05 thread:2
7895 2.8) --> vStopped
7896 2.9) --> OK
7899 void
7900 remote_target::remote_notif_get_pending_events (notif_client *nc)
7902 struct remote_state *rs = get_remote_state ();
7904 if (rs->notif_state->pending_event[nc->id] != NULL)
7906 if (notif_debug)
7907 gdb_printf (gdb_stdlog,
7908 "notif: process: '%s' ack pending event\n",
7909 nc->name);
7911 /* acknowledge */
7912 nc->ack (this, nc, rs->buf.data (),
7913 rs->notif_state->pending_event[nc->id]);
7914 rs->notif_state->pending_event[nc->id] = NULL;
7916 while (1)
7918 getpkt (&rs->buf, 0);
7919 if (strcmp (rs->buf.data (), "OK") == 0)
7920 break;
7921 else
7922 remote_notif_ack (this, nc, rs->buf.data ());
7925 else
7927 if (notif_debug)
7928 gdb_printf (gdb_stdlog,
7929 "notif: process: '%s' no pending reply\n",
7930 nc->name);
7934 /* Wrapper around remote_target::remote_notif_get_pending_events to
7935 avoid having to export the whole remote_target class. */
7937 void
7938 remote_notif_get_pending_events (remote_target *remote, notif_client *nc)
7940 remote->remote_notif_get_pending_events (nc);
7943 /* Called from process_stop_reply when the stop packet we are responding
7944 to didn't include a process-id or thread-id. STATUS is the stop event
7945 we are responding to.
7947 It is the task of this function to select a suitable thread (or process)
7948 and return its ptid, this is the thread (or process) we will assume the
7949 stop event came from.
7951 In some cases there isn't really any choice about which thread (or
7952 process) is selected, a basic remote with a single process containing a
7953 single thread might choose not to send any process-id or thread-id in
7954 its stop packets, this function will select and return the one and only
7955 thread.
7957 However, if a target supports multiple threads (or processes) and still
7958 doesn't include a thread-id (or process-id) in its stop packet then
7959 first, this is a badly behaving target, and second, we're going to have
7960 to select a thread (or process) at random and use that. This function
7961 will print a warning to the user if it detects that there is the
7962 possibility that GDB is guessing which thread (or process) to
7963 report.
7965 Note that this is called before GDB fetches the updated thread list from the
7966 target. So it's possible for the stop reply to be ambiguous and for GDB to
7967 not realize it. For example, if there's initially one thread, the target
7968 spawns a second thread, and then sends a stop reply without an id that
7969 concerns the first thread. GDB will assume the stop reply is about the
7970 first thread - the only thread it knows about - without printing a warning.
7971 Anyway, if the remote meant for the stop reply to be about the second thread,
7972 then it would be really broken, because GDB doesn't know about that thread
7973 yet. */
7975 ptid_t
7976 remote_target::select_thread_for_ambiguous_stop_reply
7977 (const target_waitstatus &status)
7979 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7981 /* Some stop events apply to all threads in an inferior, while others
7982 only apply to a single thread. */
7983 bool process_wide_stop
7984 = (status.kind () == TARGET_WAITKIND_EXITED
7985 || status.kind () == TARGET_WAITKIND_SIGNALLED);
7987 remote_debug_printf ("process_wide_stop = %d", process_wide_stop);
7989 thread_info *first_resumed_thread = nullptr;
7990 bool ambiguous = false;
7992 /* Consider all non-exited threads of the target, find the first resumed
7993 one. */
7994 for (thread_info *thr : all_non_exited_threads (this))
7996 remote_thread_info *remote_thr = get_remote_thread_info (thr);
7998 if (remote_thr->get_resume_state () != resume_state::RESUMED)
7999 continue;
8001 if (first_resumed_thread == nullptr)
8002 first_resumed_thread = thr;
8003 else if (!process_wide_stop
8004 || first_resumed_thread->ptid.pid () != thr->ptid.pid ())
8005 ambiguous = true;
8008 gdb_assert (first_resumed_thread != nullptr);
8010 remote_debug_printf ("first resumed thread is %s",
8011 pid_to_str (first_resumed_thread->ptid).c_str ());
8012 remote_debug_printf ("is this guess ambiguous? = %d", ambiguous);
8014 /* Warn if the remote target is sending ambiguous stop replies. */
8015 if (ambiguous)
8017 static bool warned = false;
8019 if (!warned)
8021 /* If you are seeing this warning then the remote target has
8022 stopped without specifying a thread-id, but the target
8023 does have multiple threads (or inferiors), and so GDB is
8024 having to guess which thread stopped.
8026 Examples of what might cause this are the target sending
8027 and 'S' stop packet, or a 'T' stop packet and not
8028 including a thread-id.
8030 Additionally, the target might send a 'W' or 'X packet
8031 without including a process-id, when the target has
8032 multiple running inferiors. */
8033 if (process_wide_stop)
8034 warning (_("multi-inferior target stopped without "
8035 "sending a process-id, using first "
8036 "non-exited inferior"));
8037 else
8038 warning (_("multi-threaded target stopped without "
8039 "sending a thread-id, using first "
8040 "non-exited thread"));
8041 warned = true;
8045 /* If this is a stop for all threads then don't use a particular threads
8046 ptid, instead create a new ptid where only the pid field is set. */
8047 if (process_wide_stop)
8048 return ptid_t (first_resumed_thread->ptid.pid ());
8049 else
8050 return first_resumed_thread->ptid;
8053 /* Called when it is decided that STOP_REPLY holds the info of the
8054 event that is to be returned to the core. This function always
8055 destroys STOP_REPLY. */
8057 ptid_t
8058 remote_target::process_stop_reply (struct stop_reply *stop_reply,
8059 struct target_waitstatus *status)
8061 *status = stop_reply->ws;
8062 ptid_t ptid = stop_reply->ptid;
8064 /* If no thread/process was reported by the stub then select a suitable
8065 thread/process. */
8066 if (ptid == null_ptid)
8067 ptid = select_thread_for_ambiguous_stop_reply (*status);
8068 gdb_assert (ptid != null_ptid);
8070 if (status->kind () != TARGET_WAITKIND_EXITED
8071 && status->kind () != TARGET_WAITKIND_SIGNALLED
8072 && status->kind () != TARGET_WAITKIND_NO_RESUMED)
8074 /* Expedited registers. */
8075 if (!stop_reply->regcache.empty ())
8077 struct regcache *regcache
8078 = get_thread_arch_regcache (this, ptid, stop_reply->arch);
8080 for (cached_reg_t &reg : stop_reply->regcache)
8082 regcache->raw_supply (reg.num, reg.data);
8083 xfree (reg.data);
8086 stop_reply->regcache.clear ();
8089 remote_notice_new_inferior (ptid, false);
8090 remote_thread_info *remote_thr = get_remote_thread_info (this, ptid);
8091 remote_thr->core = stop_reply->core;
8092 remote_thr->stop_reason = stop_reply->stop_reason;
8093 remote_thr->watch_data_address = stop_reply->watch_data_address;
8095 if (target_is_non_stop_p ())
8097 /* If the target works in non-stop mode, a stop-reply indicates that
8098 only this thread stopped. */
8099 remote_thr->set_not_resumed ();
8101 else
8103 /* If the target works in all-stop mode, a stop-reply indicates that
8104 all the target's threads stopped. */
8105 for (thread_info *tp : all_non_exited_threads (this))
8106 get_remote_thread_info (tp)->set_not_resumed ();
8110 delete stop_reply;
8111 return ptid;
8114 /* The non-stop mode version of target_wait. */
8116 ptid_t
8117 remote_target::wait_ns (ptid_t ptid, struct target_waitstatus *status,
8118 target_wait_flags options)
8120 struct remote_state *rs = get_remote_state ();
8121 struct stop_reply *stop_reply;
8122 int ret;
8123 int is_notif = 0;
8125 /* If in non-stop mode, get out of getpkt even if a
8126 notification is received. */
8128 ret = getpkt_or_notif_sane (&rs->buf, 0 /* forever */, &is_notif);
8129 while (1)
8131 if (ret != -1 && !is_notif)
8132 switch (rs->buf[0])
8134 case 'E': /* Error of some sort. */
8135 /* We're out of sync with the target now. Did it continue
8136 or not? We can't tell which thread it was in non-stop,
8137 so just ignore this. */
8138 warning (_("Remote failure reply: %s"), rs->buf.data ());
8139 break;
8140 case 'O': /* Console output. */
8141 remote_console_output (&rs->buf[1]);
8142 break;
8143 default:
8144 warning (_("Invalid remote reply: %s"), rs->buf.data ());
8145 break;
8148 /* Acknowledge a pending stop reply that may have arrived in the
8149 mean time. */
8150 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
8151 remote_notif_get_pending_events (&notif_client_stop);
8153 /* If indeed we noticed a stop reply, we're done. */
8154 stop_reply = queued_stop_reply (ptid);
8155 if (stop_reply != NULL)
8156 return process_stop_reply (stop_reply, status);
8158 /* Still no event. If we're just polling for an event, then
8159 return to the event loop. */
8160 if (options & TARGET_WNOHANG)
8162 status->set_ignore ();
8163 return minus_one_ptid;
8166 /* Otherwise do a blocking wait. */
8167 ret = getpkt_or_notif_sane (&rs->buf, 1 /* forever */, &is_notif);
8171 /* Return the first resumed thread. */
8173 static ptid_t
8174 first_remote_resumed_thread (remote_target *target)
8176 for (thread_info *tp : all_non_exited_threads (target, minus_one_ptid))
8177 if (tp->resumed ())
8178 return tp->ptid;
8179 return null_ptid;
8182 /* Wait until the remote machine stops, then return, storing status in
8183 STATUS just as `wait' would. */
8185 ptid_t
8186 remote_target::wait_as (ptid_t ptid, target_waitstatus *status,
8187 target_wait_flags options)
8189 struct remote_state *rs = get_remote_state ();
8190 ptid_t event_ptid = null_ptid;
8191 char *buf;
8192 struct stop_reply *stop_reply;
8194 again:
8196 status->set_ignore ();
8198 stop_reply = queued_stop_reply (ptid);
8199 if (stop_reply != NULL)
8201 /* None of the paths that push a stop reply onto the queue should
8202 have set the waiting_for_stop_reply flag. */
8203 gdb_assert (!rs->waiting_for_stop_reply);
8204 event_ptid = process_stop_reply (stop_reply, status);
8206 else
8208 int forever = ((options & TARGET_WNOHANG) == 0
8209 && rs->wait_forever_enabled_p);
8211 if (!rs->waiting_for_stop_reply)
8213 status->set_no_resumed ();
8214 return minus_one_ptid;
8217 /* FIXME: cagney/1999-09-27: If we're in async mode we should
8218 _never_ wait for ever -> test on target_is_async_p().
8219 However, before we do that we need to ensure that the caller
8220 knows how to take the target into/out of async mode. */
8221 int is_notif;
8222 int ret = getpkt_or_notif_sane (&rs->buf, forever, &is_notif);
8224 /* GDB gets a notification. Return to core as this event is
8225 not interesting. */
8226 if (ret != -1 && is_notif)
8227 return minus_one_ptid;
8229 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
8230 return minus_one_ptid;
8232 buf = rs->buf.data ();
8234 /* Assume that the target has acknowledged Ctrl-C unless we receive
8235 an 'F' or 'O' packet. */
8236 if (buf[0] != 'F' && buf[0] != 'O')
8237 rs->ctrlc_pending_p = 0;
8239 switch (buf[0])
8241 case 'E': /* Error of some sort. */
8242 /* We're out of sync with the target now. Did it continue or
8243 not? Not is more likely, so report a stop. */
8244 rs->waiting_for_stop_reply = 0;
8246 warning (_("Remote failure reply: %s"), buf);
8247 status->set_stopped (GDB_SIGNAL_0);
8248 break;
8249 case 'F': /* File-I/O request. */
8250 /* GDB may access the inferior memory while handling the File-I/O
8251 request, but we don't want GDB accessing memory while waiting
8252 for a stop reply. See the comments in putpkt_binary. Set
8253 waiting_for_stop_reply to 0 temporarily. */
8254 rs->waiting_for_stop_reply = 0;
8255 remote_fileio_request (this, buf, rs->ctrlc_pending_p);
8256 rs->ctrlc_pending_p = 0;
8257 /* GDB handled the File-I/O request, and the target is running
8258 again. Keep waiting for events. */
8259 rs->waiting_for_stop_reply = 1;
8260 break;
8261 case 'N': case 'T': case 'S': case 'X': case 'W':
8263 /* There is a stop reply to handle. */
8264 rs->waiting_for_stop_reply = 0;
8266 stop_reply
8267 = (struct stop_reply *) remote_notif_parse (this,
8268 &notif_client_stop,
8269 rs->buf.data ());
8271 event_ptid = process_stop_reply (stop_reply, status);
8272 break;
8274 case 'O': /* Console output. */
8275 remote_console_output (buf + 1);
8276 break;
8277 case '\0':
8278 if (rs->last_sent_signal != GDB_SIGNAL_0)
8280 /* Zero length reply means that we tried 'S' or 'C' and the
8281 remote system doesn't support it. */
8282 target_terminal::ours_for_output ();
8283 gdb_printf
8284 ("Can't send signals to this remote system. %s not sent.\n",
8285 gdb_signal_to_name (rs->last_sent_signal));
8286 rs->last_sent_signal = GDB_SIGNAL_0;
8287 target_terminal::inferior ();
8289 strcpy (buf, rs->last_sent_step ? "s" : "c");
8290 putpkt (buf);
8291 break;
8293 /* fallthrough */
8294 default:
8295 warning (_("Invalid remote reply: %s"), buf);
8296 break;
8300 if (status->kind () == TARGET_WAITKIND_NO_RESUMED)
8301 return minus_one_ptid;
8302 else if (status->kind () == TARGET_WAITKIND_IGNORE)
8304 /* Nothing interesting happened. If we're doing a non-blocking
8305 poll, we're done. Otherwise, go back to waiting. */
8306 if (options & TARGET_WNOHANG)
8307 return minus_one_ptid;
8308 else
8309 goto again;
8311 else if (status->kind () != TARGET_WAITKIND_EXITED
8312 && status->kind () != TARGET_WAITKIND_SIGNALLED)
8314 if (event_ptid != null_ptid)
8315 record_currthread (rs, event_ptid);
8316 else
8317 event_ptid = first_remote_resumed_thread (this);
8319 else
8321 /* A process exit. Invalidate our notion of current thread. */
8322 record_currthread (rs, minus_one_ptid);
8323 /* It's possible that the packet did not include a pid. */
8324 if (event_ptid == null_ptid)
8325 event_ptid = first_remote_resumed_thread (this);
8326 /* EVENT_PTID could still be NULL_PTID. Double-check. */
8327 if (event_ptid == null_ptid)
8328 event_ptid = magic_null_ptid;
8331 return event_ptid;
8334 /* Wait until the remote machine stops, then return, storing status in
8335 STATUS just as `wait' would. */
8337 ptid_t
8338 remote_target::wait (ptid_t ptid, struct target_waitstatus *status,
8339 target_wait_flags options)
8341 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
8343 remote_state *rs = get_remote_state ();
8345 /* Start by clearing the flag that asks for our wait method to be called,
8346 we'll mark it again at the end if needed. If the target is not in
8347 async mode then the async token should not be marked. */
8348 if (target_is_async_p ())
8349 clear_async_event_handler (rs->remote_async_inferior_event_token);
8350 else
8351 gdb_assert (!async_event_handler_marked
8352 (rs->remote_async_inferior_event_token));
8354 ptid_t event_ptid;
8356 if (target_is_non_stop_p ())
8357 event_ptid = wait_ns (ptid, status, options);
8358 else
8359 event_ptid = wait_as (ptid, status, options);
8361 if (target_is_async_p ())
8363 /* If there are events left in the queue, or unacknowledged
8364 notifications, then tell the event loop to call us again. */
8365 if (!rs->stop_reply_queue.empty ()
8366 || rs->notif_state->pending_event[notif_client_stop.id] != nullptr)
8367 mark_async_event_handler (rs->remote_async_inferior_event_token);
8370 return event_ptid;
8373 /* Fetch a single register using a 'p' packet. */
8376 remote_target::fetch_register_using_p (struct regcache *regcache,
8377 packet_reg *reg)
8379 struct gdbarch *gdbarch = regcache->arch ();
8380 struct remote_state *rs = get_remote_state ();
8381 char *buf, *p;
8382 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
8383 int i;
8385 if (packet_support (PACKET_p) == PACKET_DISABLE)
8386 return 0;
8388 if (reg->pnum == -1)
8389 return 0;
8391 p = rs->buf.data ();
8392 *p++ = 'p';
8393 p += hexnumstr (p, reg->pnum);
8394 *p++ = '\0';
8395 putpkt (rs->buf);
8396 getpkt (&rs->buf, 0);
8398 buf = rs->buf.data ();
8400 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_p]))
8402 case PACKET_OK:
8403 break;
8404 case PACKET_UNKNOWN:
8405 return 0;
8406 case PACKET_ERROR:
8407 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
8408 gdbarch_register_name (regcache->arch (),
8409 reg->regnum),
8410 buf);
8413 /* If this register is unfetchable, tell the regcache. */
8414 if (buf[0] == 'x')
8416 regcache->raw_supply (reg->regnum, NULL);
8417 return 1;
8420 /* Otherwise, parse and supply the value. */
8421 p = buf;
8422 i = 0;
8423 while (p[0] != 0)
8425 if (p[1] == 0)
8426 error (_("fetch_register_using_p: early buf termination"));
8428 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
8429 p += 2;
8431 regcache->raw_supply (reg->regnum, regp);
8432 return 1;
8435 /* Fetch the registers included in the target's 'g' packet. */
8438 remote_target::send_g_packet ()
8440 struct remote_state *rs = get_remote_state ();
8441 int buf_len;
8443 xsnprintf (rs->buf.data (), get_remote_packet_size (), "g");
8444 putpkt (rs->buf);
8445 getpkt (&rs->buf, 0);
8446 if (packet_check_result (rs->buf) == PACKET_ERROR)
8447 error (_("Could not read registers; remote failure reply '%s'"),
8448 rs->buf.data ());
8450 /* We can get out of synch in various cases. If the first character
8451 in the buffer is not a hex character, assume that has happened
8452 and try to fetch another packet to read. */
8453 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
8454 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
8455 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
8456 && rs->buf[0] != 'x') /* New: unavailable register value. */
8458 remote_debug_printf ("Bad register packet; fetching a new packet");
8459 getpkt (&rs->buf, 0);
8462 buf_len = strlen (rs->buf.data ());
8464 /* Sanity check the received packet. */
8465 if (buf_len % 2 != 0)
8466 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf.data ());
8468 return buf_len / 2;
8471 void
8472 remote_target::process_g_packet (struct regcache *regcache)
8474 struct gdbarch *gdbarch = regcache->arch ();
8475 struct remote_state *rs = get_remote_state ();
8476 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8477 int i, buf_len;
8478 char *p;
8479 char *regs;
8481 buf_len = strlen (rs->buf.data ());
8483 /* Further sanity checks, with knowledge of the architecture. */
8484 if (buf_len > 2 * rsa->sizeof_g_packet)
8485 error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
8486 "bytes): %s"),
8487 rsa->sizeof_g_packet, buf_len / 2,
8488 rs->buf.data ());
8490 /* Save the size of the packet sent to us by the target. It is used
8491 as a heuristic when determining the max size of packets that the
8492 target can safely receive. */
8493 if (rsa->actual_register_packet_size == 0)
8494 rsa->actual_register_packet_size = buf_len;
8496 /* If this is smaller than we guessed the 'g' packet would be,
8497 update our records. A 'g' reply that doesn't include a register's
8498 value implies either that the register is not available, or that
8499 the 'p' packet must be used. */
8500 if (buf_len < 2 * rsa->sizeof_g_packet)
8502 long sizeof_g_packet = buf_len / 2;
8504 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8506 long offset = rsa->regs[i].offset;
8507 long reg_size = register_size (gdbarch, i);
8509 if (rsa->regs[i].pnum == -1)
8510 continue;
8512 if (offset >= sizeof_g_packet)
8513 rsa->regs[i].in_g_packet = 0;
8514 else if (offset + reg_size > sizeof_g_packet)
8515 error (_("Truncated register %d in remote 'g' packet"), i);
8516 else
8517 rsa->regs[i].in_g_packet = 1;
8520 /* Looks valid enough, we can assume this is the correct length
8521 for a 'g' packet. It's important not to adjust
8522 rsa->sizeof_g_packet if we have truncated registers otherwise
8523 this "if" won't be run the next time the method is called
8524 with a packet of the same size and one of the internal errors
8525 below will trigger instead. */
8526 rsa->sizeof_g_packet = sizeof_g_packet;
8529 regs = (char *) alloca (rsa->sizeof_g_packet);
8531 /* Unimplemented registers read as all bits zero. */
8532 memset (regs, 0, rsa->sizeof_g_packet);
8534 /* Reply describes registers byte by byte, each byte encoded as two
8535 hex characters. Suck them all up, then supply them to the
8536 register cacheing/storage mechanism. */
8538 p = rs->buf.data ();
8539 for (i = 0; i < rsa->sizeof_g_packet; i++)
8541 if (p[0] == 0 || p[1] == 0)
8542 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
8543 internal_error (_("unexpected end of 'g' packet reply"));
8545 if (p[0] == 'x' && p[1] == 'x')
8546 regs[i] = 0; /* 'x' */
8547 else
8548 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
8549 p += 2;
8552 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8554 struct packet_reg *r = &rsa->regs[i];
8555 long reg_size = register_size (gdbarch, i);
8557 if (r->in_g_packet)
8559 if ((r->offset + reg_size) * 2 > strlen (rs->buf.data ()))
8560 /* This shouldn't happen - we adjusted in_g_packet above. */
8561 internal_error (_("unexpected end of 'g' packet reply"));
8562 else if (rs->buf[r->offset * 2] == 'x')
8564 gdb_assert (r->offset * 2 < strlen (rs->buf.data ()));
8565 /* The register isn't available, mark it as such (at
8566 the same time setting the value to zero). */
8567 regcache->raw_supply (r->regnum, NULL);
8569 else
8570 regcache->raw_supply (r->regnum, regs + r->offset);
8575 void
8576 remote_target::fetch_registers_using_g (struct regcache *regcache)
8578 send_g_packet ();
8579 process_g_packet (regcache);
8582 /* Make the remote selected traceframe match GDB's selected
8583 traceframe. */
8585 void
8586 remote_target::set_remote_traceframe ()
8588 int newnum;
8589 struct remote_state *rs = get_remote_state ();
8591 if (rs->remote_traceframe_number == get_traceframe_number ())
8592 return;
8594 /* Avoid recursion, remote_trace_find calls us again. */
8595 rs->remote_traceframe_number = get_traceframe_number ();
8597 newnum = target_trace_find (tfind_number,
8598 get_traceframe_number (), 0, 0, NULL);
8600 /* Should not happen. If it does, all bets are off. */
8601 if (newnum != get_traceframe_number ())
8602 warning (_("could not set remote traceframe"));
8605 void
8606 remote_target::fetch_registers (struct regcache *regcache, int regnum)
8608 struct gdbarch *gdbarch = regcache->arch ();
8609 struct remote_state *rs = get_remote_state ();
8610 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8611 int i;
8613 set_remote_traceframe ();
8614 set_general_thread (regcache->ptid ());
8616 if (regnum >= 0)
8618 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8620 gdb_assert (reg != NULL);
8622 /* If this register might be in the 'g' packet, try that first -
8623 we are likely to read more than one register. If this is the
8624 first 'g' packet, we might be overly optimistic about its
8625 contents, so fall back to 'p'. */
8626 if (reg->in_g_packet)
8628 fetch_registers_using_g (regcache);
8629 if (reg->in_g_packet)
8630 return;
8633 if (fetch_register_using_p (regcache, reg))
8634 return;
8636 /* This register is not available. */
8637 regcache->raw_supply (reg->regnum, NULL);
8639 return;
8642 fetch_registers_using_g (regcache);
8644 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8645 if (!rsa->regs[i].in_g_packet)
8646 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
8648 /* This register is not available. */
8649 regcache->raw_supply (i, NULL);
8653 /* Prepare to store registers. Since we may send them all (using a
8654 'G' request), we have to read out the ones we don't want to change
8655 first. */
8657 void
8658 remote_target::prepare_to_store (struct regcache *regcache)
8660 struct remote_state *rs = get_remote_state ();
8661 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
8662 int i;
8664 /* Make sure the entire registers array is valid. */
8665 switch (packet_support (PACKET_P))
8667 case PACKET_DISABLE:
8668 case PACKET_SUPPORT_UNKNOWN:
8669 /* Make sure all the necessary registers are cached. */
8670 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8671 if (rsa->regs[i].in_g_packet)
8672 regcache->raw_update (rsa->regs[i].regnum);
8673 break;
8674 case PACKET_ENABLE:
8675 break;
8679 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
8680 packet was not recognized. */
8683 remote_target::store_register_using_P (const struct regcache *regcache,
8684 packet_reg *reg)
8686 struct gdbarch *gdbarch = regcache->arch ();
8687 struct remote_state *rs = get_remote_state ();
8688 /* Try storing a single register. */
8689 char *buf = rs->buf.data ();
8690 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
8691 char *p;
8693 if (packet_support (PACKET_P) == PACKET_DISABLE)
8694 return 0;
8696 if (reg->pnum == -1)
8697 return 0;
8699 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
8700 p = buf + strlen (buf);
8701 regcache->raw_collect (reg->regnum, regp);
8702 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
8703 putpkt (rs->buf);
8704 getpkt (&rs->buf, 0);
8706 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
8708 case PACKET_OK:
8709 return 1;
8710 case PACKET_ERROR:
8711 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
8712 gdbarch_register_name (gdbarch, reg->regnum), rs->buf.data ());
8713 case PACKET_UNKNOWN:
8714 return 0;
8715 default:
8716 internal_error (_("Bad result from packet_ok"));
8720 /* Store register REGNUM, or all registers if REGNUM == -1, from the
8721 contents of the register cache buffer. FIXME: ignores errors. */
8723 void
8724 remote_target::store_registers_using_G (const struct regcache *regcache)
8726 struct remote_state *rs = get_remote_state ();
8727 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
8728 gdb_byte *regs;
8729 char *p;
8731 /* Extract all the registers in the regcache copying them into a
8732 local buffer. */
8734 int i;
8736 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
8737 memset (regs, 0, rsa->sizeof_g_packet);
8738 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8740 struct packet_reg *r = &rsa->regs[i];
8742 if (r->in_g_packet)
8743 regcache->raw_collect (r->regnum, regs + r->offset);
8747 /* Command describes registers byte by byte,
8748 each byte encoded as two hex characters. */
8749 p = rs->buf.data ();
8750 *p++ = 'G';
8751 bin2hex (regs, p, rsa->sizeof_g_packet);
8752 putpkt (rs->buf);
8753 getpkt (&rs->buf, 0);
8754 if (packet_check_result (rs->buf) == PACKET_ERROR)
8755 error (_("Could not write registers; remote failure reply '%s'"),
8756 rs->buf.data ());
8759 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
8760 of the register cache buffer. FIXME: ignores errors. */
8762 void
8763 remote_target::store_registers (struct regcache *regcache, int regnum)
8765 struct gdbarch *gdbarch = regcache->arch ();
8766 struct remote_state *rs = get_remote_state ();
8767 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8768 int i;
8770 set_remote_traceframe ();
8771 set_general_thread (regcache->ptid ());
8773 if (regnum >= 0)
8775 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8777 gdb_assert (reg != NULL);
8779 /* Always prefer to store registers using the 'P' packet if
8780 possible; we often change only a small number of registers.
8781 Sometimes we change a larger number; we'd need help from a
8782 higher layer to know to use 'G'. */
8783 if (store_register_using_P (regcache, reg))
8784 return;
8786 /* For now, don't complain if we have no way to write the
8787 register. GDB loses track of unavailable registers too
8788 easily. Some day, this may be an error. We don't have
8789 any way to read the register, either... */
8790 if (!reg->in_g_packet)
8791 return;
8793 store_registers_using_G (regcache);
8794 return;
8797 store_registers_using_G (regcache);
8799 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8800 if (!rsa->regs[i].in_g_packet)
8801 if (!store_register_using_P (regcache, &rsa->regs[i]))
8802 /* See above for why we do not issue an error here. */
8803 continue;
8807 /* Return the number of hex digits in num. */
8809 static int
8810 hexnumlen (ULONGEST num)
8812 int i;
8814 for (i = 0; num != 0; i++)
8815 num >>= 4;
8817 return std::max (i, 1);
8820 /* Set BUF to the minimum number of hex digits representing NUM. */
8822 static int
8823 hexnumstr (char *buf, ULONGEST num)
8825 int len = hexnumlen (num);
8827 return hexnumnstr (buf, num, len);
8831 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
8833 static int
8834 hexnumnstr (char *buf, ULONGEST num, int width)
8836 int i;
8838 buf[width] = '\0';
8840 for (i = width - 1; i >= 0; i--)
8842 buf[i] = "0123456789abcdef"[(num & 0xf)];
8843 num >>= 4;
8846 return width;
8849 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
8851 static CORE_ADDR
8852 remote_address_masked (CORE_ADDR addr)
8854 unsigned int address_size = remote_address_size;
8856 /* If "remoteaddresssize" was not set, default to target address size. */
8857 if (!address_size)
8858 address_size = gdbarch_addr_bit (target_gdbarch ());
8860 if (address_size > 0
8861 && address_size < (sizeof (ULONGEST) * 8))
8863 /* Only create a mask when that mask can safely be constructed
8864 in a ULONGEST variable. */
8865 ULONGEST mask = 1;
8867 mask = (mask << address_size) - 1;
8868 addr &= mask;
8870 return addr;
8873 /* Determine whether the remote target supports binary downloading.
8874 This is accomplished by sending a no-op memory write of zero length
8875 to the target at the specified address. It does not suffice to send
8876 the whole packet, since many stubs strip the eighth bit and
8877 subsequently compute a wrong checksum, which causes real havoc with
8878 remote_write_bytes.
8880 NOTE: This can still lose if the serial line is not eight-bit
8881 clean. In cases like this, the user should clear "remote
8882 X-packet". */
8884 void
8885 remote_target::check_binary_download (CORE_ADDR addr)
8887 struct remote_state *rs = get_remote_state ();
8889 switch (packet_support (PACKET_X))
8891 case PACKET_DISABLE:
8892 break;
8893 case PACKET_ENABLE:
8894 break;
8895 case PACKET_SUPPORT_UNKNOWN:
8897 char *p;
8899 p = rs->buf.data ();
8900 *p++ = 'X';
8901 p += hexnumstr (p, (ULONGEST) addr);
8902 *p++ = ',';
8903 p += hexnumstr (p, (ULONGEST) 0);
8904 *p++ = ':';
8905 *p = '\0';
8907 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
8908 getpkt (&rs->buf, 0);
8910 if (rs->buf[0] == '\0')
8912 remote_debug_printf ("binary downloading NOT supported by target");
8913 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
8915 else
8917 remote_debug_printf ("binary downloading supported by target");
8918 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
8920 break;
8925 /* Helper function to resize the payload in order to try to get a good
8926 alignment. We try to write an amount of data such that the next write will
8927 start on an address aligned on REMOTE_ALIGN_WRITES. */
8929 static int
8930 align_for_efficient_write (int todo, CORE_ADDR memaddr)
8932 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
8935 /* Write memory data directly to the remote machine.
8936 This does not inform the data cache; the data cache uses this.
8937 HEADER is the starting part of the packet.
8938 MEMADDR is the address in the remote memory space.
8939 MYADDR is the address of the buffer in our space.
8940 LEN_UNITS is the number of addressable units to write.
8941 UNIT_SIZE is the length in bytes of an addressable unit.
8942 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
8943 should send data as binary ('X'), or hex-encoded ('M').
8945 The function creates packet of the form
8946 <HEADER><ADDRESS>,<LENGTH>:<DATA>
8948 where encoding of <DATA> is terminated by PACKET_FORMAT.
8950 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
8951 are omitted.
8953 Return the transferred status, error or OK (an
8954 'enum target_xfer_status' value). Save the number of addressable units
8955 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
8957 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
8958 exchange between gdb and the stub could look like (?? in place of the
8959 checksum):
8961 -> $m1000,4#??
8962 <- aaaabbbbccccdddd
8964 -> $M1000,3:eeeeffffeeee#??
8965 <- OK
8967 -> $m1000,4#??
8968 <- eeeeffffeeeedddd */
8970 target_xfer_status
8971 remote_target::remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
8972 const gdb_byte *myaddr,
8973 ULONGEST len_units,
8974 int unit_size,
8975 ULONGEST *xfered_len_units,
8976 char packet_format, int use_length)
8978 struct remote_state *rs = get_remote_state ();
8979 char *p;
8980 char *plen = NULL;
8981 int plenlen = 0;
8982 int todo_units;
8983 int units_written;
8984 int payload_capacity_bytes;
8985 int payload_length_bytes;
8987 if (packet_format != 'X' && packet_format != 'M')
8988 internal_error (_("remote_write_bytes_aux: bad packet format"));
8990 if (len_units == 0)
8991 return TARGET_XFER_EOF;
8993 payload_capacity_bytes = get_memory_write_packet_size ();
8995 /* The packet buffer will be large enough for the payload;
8996 get_memory_packet_size ensures this. */
8997 rs->buf[0] = '\0';
8999 /* Compute the size of the actual payload by subtracting out the
9000 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
9002 payload_capacity_bytes -= strlen ("$,:#NN");
9003 if (!use_length)
9004 /* The comma won't be used. */
9005 payload_capacity_bytes += 1;
9006 payload_capacity_bytes -= strlen (header);
9007 payload_capacity_bytes -= hexnumlen (memaddr);
9009 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
9011 strcat (rs->buf.data (), header);
9012 p = rs->buf.data () + strlen (header);
9014 /* Compute a best guess of the number of bytes actually transfered. */
9015 if (packet_format == 'X')
9017 /* Best guess at number of bytes that will fit. */
9018 todo_units = std::min (len_units,
9019 (ULONGEST) payload_capacity_bytes / unit_size);
9020 if (use_length)
9021 payload_capacity_bytes -= hexnumlen (todo_units);
9022 todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
9024 else
9026 /* Number of bytes that will fit. */
9027 todo_units
9028 = std::min (len_units,
9029 (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
9030 if (use_length)
9031 payload_capacity_bytes -= hexnumlen (todo_units);
9032 todo_units = std::min (todo_units,
9033 (payload_capacity_bytes / unit_size) / 2);
9036 if (todo_units <= 0)
9037 internal_error (_("minimum packet size too small to write data"));
9039 /* If we already need another packet, then try to align the end
9040 of this packet to a useful boundary. */
9041 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
9042 todo_units = align_for_efficient_write (todo_units, memaddr);
9044 /* Append "<memaddr>". */
9045 memaddr = remote_address_masked (memaddr);
9046 p += hexnumstr (p, (ULONGEST) memaddr);
9048 if (use_length)
9050 /* Append ",". */
9051 *p++ = ',';
9053 /* Append the length and retain its location and size. It may need to be
9054 adjusted once the packet body has been created. */
9055 plen = p;
9056 plenlen = hexnumstr (p, (ULONGEST) todo_units);
9057 p += plenlen;
9060 /* Append ":". */
9061 *p++ = ':';
9062 *p = '\0';
9064 /* Append the packet body. */
9065 if (packet_format == 'X')
9067 /* Binary mode. Send target system values byte by byte, in
9068 increasing byte addresses. Only escape certain critical
9069 characters. */
9070 payload_length_bytes =
9071 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
9072 &units_written, payload_capacity_bytes);
9074 /* If not all TODO units fit, then we'll need another packet. Make
9075 a second try to keep the end of the packet aligned. Don't do
9076 this if the packet is tiny. */
9077 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
9079 int new_todo_units;
9081 new_todo_units = align_for_efficient_write (units_written, memaddr);
9083 if (new_todo_units != units_written)
9084 payload_length_bytes =
9085 remote_escape_output (myaddr, new_todo_units, unit_size,
9086 (gdb_byte *) p, &units_written,
9087 payload_capacity_bytes);
9090 p += payload_length_bytes;
9091 if (use_length && units_written < todo_units)
9093 /* Escape chars have filled up the buffer prematurely,
9094 and we have actually sent fewer units than planned.
9095 Fix-up the length field of the packet. Use the same
9096 number of characters as before. */
9097 plen += hexnumnstr (plen, (ULONGEST) units_written,
9098 plenlen);
9099 *plen = ':'; /* overwrite \0 from hexnumnstr() */
9102 else
9104 /* Normal mode: Send target system values byte by byte, in
9105 increasing byte addresses. Each byte is encoded as a two hex
9106 value. */
9107 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
9108 units_written = todo_units;
9111 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
9112 getpkt (&rs->buf, 0);
9114 if (rs->buf[0] == 'E')
9115 return TARGET_XFER_E_IO;
9117 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
9118 send fewer units than we'd planned. */
9119 *xfered_len_units = (ULONGEST) units_written;
9120 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9123 /* Write memory data directly to the remote machine.
9124 This does not inform the data cache; the data cache uses this.
9125 MEMADDR is the address in the remote memory space.
9126 MYADDR is the address of the buffer in our space.
9127 LEN is the number of bytes.
9129 Return the transferred status, error or OK (an
9130 'enum target_xfer_status' value). Save the number of bytes
9131 transferred in *XFERED_LEN. Only transfer a single packet. */
9133 target_xfer_status
9134 remote_target::remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr,
9135 ULONGEST len, int unit_size,
9136 ULONGEST *xfered_len)
9138 const char *packet_format = NULL;
9140 /* Check whether the target supports binary download. */
9141 check_binary_download (memaddr);
9143 switch (packet_support (PACKET_X))
9145 case PACKET_ENABLE:
9146 packet_format = "X";
9147 break;
9148 case PACKET_DISABLE:
9149 packet_format = "M";
9150 break;
9151 case PACKET_SUPPORT_UNKNOWN:
9152 internal_error (_("remote_write_bytes: bad internal state"));
9153 default:
9154 internal_error (_("bad switch"));
9157 return remote_write_bytes_aux (packet_format,
9158 memaddr, myaddr, len, unit_size, xfered_len,
9159 packet_format[0], 1);
9162 /* Read memory data directly from the remote machine.
9163 This does not use the data cache; the data cache uses this.
9164 MEMADDR is the address in the remote memory space.
9165 MYADDR is the address of the buffer in our space.
9166 LEN_UNITS is the number of addressable memory units to read..
9167 UNIT_SIZE is the length in bytes of an addressable unit.
9169 Return the transferred status, error or OK (an
9170 'enum target_xfer_status' value). Save the number of bytes
9171 transferred in *XFERED_LEN_UNITS.
9173 See the comment of remote_write_bytes_aux for an example of
9174 memory read/write exchange between gdb and the stub. */
9176 target_xfer_status
9177 remote_target::remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
9178 ULONGEST len_units,
9179 int unit_size, ULONGEST *xfered_len_units)
9181 struct remote_state *rs = get_remote_state ();
9182 int buf_size_bytes; /* Max size of packet output buffer. */
9183 char *p;
9184 int todo_units;
9185 int decoded_bytes;
9187 buf_size_bytes = get_memory_read_packet_size ();
9188 /* The packet buffer will be large enough for the payload;
9189 get_memory_packet_size ensures this. */
9191 /* Number of units that will fit. */
9192 todo_units = std::min (len_units,
9193 (ULONGEST) (buf_size_bytes / unit_size) / 2);
9195 /* Construct "m"<memaddr>","<len>". */
9196 memaddr = remote_address_masked (memaddr);
9197 p = rs->buf.data ();
9198 *p++ = 'm';
9199 p += hexnumstr (p, (ULONGEST) memaddr);
9200 *p++ = ',';
9201 p += hexnumstr (p, (ULONGEST) todo_units);
9202 *p = '\0';
9203 putpkt (rs->buf);
9204 getpkt (&rs->buf, 0);
9205 if (rs->buf[0] == 'E'
9206 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
9207 && rs->buf[3] == '\0')
9208 return TARGET_XFER_E_IO;
9209 /* Reply describes memory byte by byte, each byte encoded as two hex
9210 characters. */
9211 p = rs->buf.data ();
9212 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
9213 /* Return what we have. Let higher layers handle partial reads. */
9214 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
9215 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9218 /* Using the set of read-only target sections of remote, read live
9219 read-only memory.
9221 For interface/parameters/return description see target.h,
9222 to_xfer_partial. */
9224 target_xfer_status
9225 remote_target::remote_xfer_live_readonly_partial (gdb_byte *readbuf,
9226 ULONGEST memaddr,
9227 ULONGEST len,
9228 int unit_size,
9229 ULONGEST *xfered_len)
9231 const struct target_section *secp;
9233 secp = target_section_by_addr (this, memaddr);
9234 if (secp != NULL
9235 && (bfd_section_flags (secp->the_bfd_section) & SEC_READONLY))
9237 ULONGEST memend = memaddr + len;
9239 const target_section_table *table = target_get_section_table (this);
9240 for (const target_section &p : *table)
9242 if (memaddr >= p.addr)
9244 if (memend <= p.endaddr)
9246 /* Entire transfer is within this section. */
9247 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
9248 xfered_len);
9250 else if (memaddr >= p.endaddr)
9252 /* This section ends before the transfer starts. */
9253 continue;
9255 else
9257 /* This section overlaps the transfer. Just do half. */
9258 len = p.endaddr - memaddr;
9259 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
9260 xfered_len);
9266 return TARGET_XFER_EOF;
9269 /* Similar to remote_read_bytes_1, but it reads from the remote stub
9270 first if the requested memory is unavailable in traceframe.
9271 Otherwise, fall back to remote_read_bytes_1. */
9273 target_xfer_status
9274 remote_target::remote_read_bytes (CORE_ADDR memaddr,
9275 gdb_byte *myaddr, ULONGEST len, int unit_size,
9276 ULONGEST *xfered_len)
9278 if (len == 0)
9279 return TARGET_XFER_EOF;
9281 if (get_traceframe_number () != -1)
9283 std::vector<mem_range> available;
9285 /* If we fail to get the set of available memory, then the
9286 target does not support querying traceframe info, and so we
9287 attempt reading from the traceframe anyway (assuming the
9288 target implements the old QTro packet then). */
9289 if (traceframe_available_memory (&available, memaddr, len))
9291 if (available.empty () || available[0].start != memaddr)
9293 enum target_xfer_status res;
9295 /* Don't read into the traceframe's available
9296 memory. */
9297 if (!available.empty ())
9299 LONGEST oldlen = len;
9301 len = available[0].start - memaddr;
9302 gdb_assert (len <= oldlen);
9305 /* This goes through the topmost target again. */
9306 res = remote_xfer_live_readonly_partial (myaddr, memaddr,
9307 len, unit_size, xfered_len);
9308 if (res == TARGET_XFER_OK)
9309 return TARGET_XFER_OK;
9310 else
9312 /* No use trying further, we know some memory starting
9313 at MEMADDR isn't available. */
9314 *xfered_len = len;
9315 return (*xfered_len != 0) ?
9316 TARGET_XFER_UNAVAILABLE : TARGET_XFER_EOF;
9320 /* Don't try to read more than how much is available, in
9321 case the target implements the deprecated QTro packet to
9322 cater for older GDBs (the target's knowledge of read-only
9323 sections may be outdated by now). */
9324 len = available[0].length;
9328 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
9333 /* Sends a packet with content determined by the printf format string
9334 FORMAT and the remaining arguments, then gets the reply. Returns
9335 whether the packet was a success, a failure, or unknown. */
9337 packet_result
9338 remote_target::remote_send_printf (const char *format, ...)
9340 struct remote_state *rs = get_remote_state ();
9341 int max_size = get_remote_packet_size ();
9342 va_list ap;
9344 va_start (ap, format);
9346 rs->buf[0] = '\0';
9347 int size = vsnprintf (rs->buf.data (), max_size, format, ap);
9349 va_end (ap);
9351 if (size >= max_size)
9352 internal_error (_("Too long remote packet."));
9354 if (putpkt (rs->buf) < 0)
9355 error (_("Communication problem with target."));
9357 rs->buf[0] = '\0';
9358 getpkt (&rs->buf, 0);
9360 return packet_check_result (rs->buf);
9363 /* Flash writing can take quite some time. We'll set
9364 effectively infinite timeout for flash operations.
9365 In future, we'll need to decide on a better approach. */
9366 static const int remote_flash_timeout = 1000;
9368 void
9369 remote_target::flash_erase (ULONGEST address, LONGEST length)
9371 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
9372 enum packet_result ret;
9373 scoped_restore restore_timeout
9374 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9376 ret = remote_send_printf ("vFlashErase:%s,%s",
9377 phex (address, addr_size),
9378 phex (length, 4));
9379 switch (ret)
9381 case PACKET_UNKNOWN:
9382 error (_("Remote target does not support flash erase"));
9383 case PACKET_ERROR:
9384 error (_("Error erasing flash with vFlashErase packet"));
9385 default:
9386 break;
9390 target_xfer_status
9391 remote_target::remote_flash_write (ULONGEST address,
9392 ULONGEST length, ULONGEST *xfered_len,
9393 const gdb_byte *data)
9395 scoped_restore restore_timeout
9396 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9397 return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
9398 xfered_len,'X', 0);
9401 void
9402 remote_target::flash_done ()
9404 int ret;
9406 scoped_restore restore_timeout
9407 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9409 ret = remote_send_printf ("vFlashDone");
9411 switch (ret)
9413 case PACKET_UNKNOWN:
9414 error (_("Remote target does not support vFlashDone"));
9415 case PACKET_ERROR:
9416 error (_("Error finishing flash operation"));
9417 default:
9418 break;
9423 /* Stuff for dealing with the packets which are part of this protocol.
9424 See comment at top of file for details. */
9426 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
9427 error to higher layers. Called when a serial error is detected.
9428 The exception message is STRING, followed by a colon and a blank,
9429 the system error message for errno at function entry and final dot
9430 for output compatibility with throw_perror_with_name. */
9432 static void
9433 unpush_and_perror (remote_target *target, const char *string)
9435 int saved_errno = errno;
9437 remote_unpush_target (target);
9438 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
9439 safe_strerror (saved_errno));
9442 /* Read a single character from the remote end. The current quit
9443 handler is overridden to avoid quitting in the middle of packet
9444 sequence, as that would break communication with the remote server.
9445 See remote_serial_quit_handler for more detail. */
9448 remote_target::readchar (int timeout)
9450 int ch;
9451 struct remote_state *rs = get_remote_state ();
9454 scoped_restore restore_quit_target
9455 = make_scoped_restore (&curr_quit_handler_target, this);
9456 scoped_restore restore_quit
9457 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9459 rs->got_ctrlc_during_io = 0;
9461 ch = serial_readchar (rs->remote_desc, timeout);
9463 if (rs->got_ctrlc_during_io)
9464 set_quit_flag ();
9467 if (ch >= 0)
9468 return ch;
9470 switch ((enum serial_rc) ch)
9472 case SERIAL_EOF:
9473 remote_unpush_target (this);
9474 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
9475 /* no return */
9476 case SERIAL_ERROR:
9477 unpush_and_perror (this, _("Remote communication error. "
9478 "Target disconnected."));
9479 /* no return */
9480 case SERIAL_TIMEOUT:
9481 break;
9483 return ch;
9486 /* Wrapper for serial_write that closes the target and throws if
9487 writing fails. The current quit handler is overridden to avoid
9488 quitting in the middle of packet sequence, as that would break
9489 communication with the remote server. See
9490 remote_serial_quit_handler for more detail. */
9492 void
9493 remote_target::remote_serial_write (const char *str, int len)
9495 struct remote_state *rs = get_remote_state ();
9497 scoped_restore restore_quit_target
9498 = make_scoped_restore (&curr_quit_handler_target, this);
9499 scoped_restore restore_quit
9500 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9502 rs->got_ctrlc_during_io = 0;
9504 if (serial_write (rs->remote_desc, str, len))
9506 unpush_and_perror (this, _("Remote communication error. "
9507 "Target disconnected."));
9510 if (rs->got_ctrlc_during_io)
9511 set_quit_flag ();
9514 /* Return a string representing an escaped version of BUF, of len N.
9515 E.g. \n is converted to \\n, \t to \\t, etc. */
9517 static std::string
9518 escape_buffer (const char *buf, int n)
9520 string_file stb;
9522 stb.putstrn (buf, n, '\\');
9523 return stb.release ();
9527 remote_target::putpkt (const char *buf)
9529 return putpkt_binary (buf, strlen (buf));
9532 /* Wrapper around remote_target::putpkt to avoid exporting
9533 remote_target. */
9536 putpkt (remote_target *remote, const char *buf)
9538 return remote->putpkt (buf);
9541 /* Send a packet to the remote machine, with error checking. The data
9542 of the packet is in BUF. The string in BUF can be at most
9543 get_remote_packet_size () - 5 to account for the $, # and checksum,
9544 and for a possible /0 if we are debugging (remote_debug) and want
9545 to print the sent packet as a string. */
9548 remote_target::putpkt_binary (const char *buf, int cnt)
9550 struct remote_state *rs = get_remote_state ();
9551 int i;
9552 unsigned char csum = 0;
9553 gdb::def_vector<char> data (cnt + 6);
9554 char *buf2 = data.data ();
9556 int ch;
9557 int tcount = 0;
9558 char *p;
9560 /* Catch cases like trying to read memory or listing threads while
9561 we're waiting for a stop reply. The remote server wouldn't be
9562 ready to handle this request, so we'd hang and timeout. We don't
9563 have to worry about this in synchronous mode, because in that
9564 case it's not possible to issue a command while the target is
9565 running. This is not a problem in non-stop mode, because in that
9566 case, the stub is always ready to process serial input. */
9567 if (!target_is_non_stop_p ()
9568 && target_is_async_p ()
9569 && rs->waiting_for_stop_reply)
9571 error (_("Cannot execute this command while the target is running.\n"
9572 "Use the \"interrupt\" command to stop the target\n"
9573 "and then try again."));
9576 /* Copy the packet into buffer BUF2, encapsulating it
9577 and giving it a checksum. */
9579 p = buf2;
9580 *p++ = '$';
9582 for (i = 0; i < cnt; i++)
9584 csum += buf[i];
9585 *p++ = buf[i];
9587 *p++ = '#';
9588 *p++ = tohex ((csum >> 4) & 0xf);
9589 *p++ = tohex (csum & 0xf);
9591 /* Send it over and over until we get a positive ack. */
9593 while (1)
9595 if (remote_debug)
9597 *p = '\0';
9599 int len = (int) (p - buf2);
9600 int max_chars;
9602 if (remote_packet_max_chars < 0)
9603 max_chars = len;
9604 else
9605 max_chars = remote_packet_max_chars;
9607 std::string str
9608 = escape_buffer (buf2, std::min (len, max_chars));
9610 if (len > max_chars)
9611 remote_debug_printf_nofunc
9612 ("Sending packet: %s [%d bytes omitted]", str.c_str (),
9613 len - max_chars);
9614 else
9615 remote_debug_printf_nofunc ("Sending packet: %s", str.c_str ());
9617 remote_serial_write (buf2, p - buf2);
9619 /* If this is a no acks version of the remote protocol, send the
9620 packet and move on. */
9621 if (rs->noack_mode)
9622 break;
9624 /* Read until either a timeout occurs (-2) or '+' is read.
9625 Handle any notification that arrives in the mean time. */
9626 while (1)
9628 ch = readchar (remote_timeout);
9630 switch (ch)
9632 case '+':
9633 remote_debug_printf_nofunc ("Received Ack");
9634 return 1;
9635 case '-':
9636 remote_debug_printf_nofunc ("Received Nak");
9637 /* FALLTHROUGH */
9638 case SERIAL_TIMEOUT:
9639 tcount++;
9640 if (tcount > 3)
9641 return 0;
9642 break; /* Retransmit buffer. */
9643 case '$':
9645 remote_debug_printf ("Packet instead of Ack, ignoring it");
9646 /* It's probably an old response sent because an ACK
9647 was lost. Gobble up the packet and ack it so it
9648 doesn't get retransmitted when we resend this
9649 packet. */
9650 skip_frame ();
9651 remote_serial_write ("+", 1);
9652 continue; /* Now, go look for +. */
9655 case '%':
9657 int val;
9659 /* If we got a notification, handle it, and go back to looking
9660 for an ack. */
9661 /* We've found the start of a notification. Now
9662 collect the data. */
9663 val = read_frame (&rs->buf);
9664 if (val >= 0)
9666 remote_debug_printf_nofunc
9667 (" Notification received: %s",
9668 escape_buffer (rs->buf.data (), val).c_str ());
9670 handle_notification (rs->notif_state, rs->buf.data ());
9671 /* We're in sync now, rewait for the ack. */
9672 tcount = 0;
9674 else
9675 remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
9676 rs->buf.data ());
9677 continue;
9679 /* fall-through */
9680 default:
9681 remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
9682 rs->buf.data ());
9683 continue;
9685 break; /* Here to retransmit. */
9688 #if 0
9689 /* This is wrong. If doing a long backtrace, the user should be
9690 able to get out next time we call QUIT, without anything as
9691 violent as interrupt_query. If we want to provide a way out of
9692 here without getting to the next QUIT, it should be based on
9693 hitting ^C twice as in remote_wait. */
9694 if (quit_flag)
9696 quit_flag = 0;
9697 interrupt_query ();
9699 #endif
9702 return 0;
9705 /* Come here after finding the start of a frame when we expected an
9706 ack. Do our best to discard the rest of this packet. */
9708 void
9709 remote_target::skip_frame ()
9711 int c;
9713 while (1)
9715 c = readchar (remote_timeout);
9716 switch (c)
9718 case SERIAL_TIMEOUT:
9719 /* Nothing we can do. */
9720 return;
9721 case '#':
9722 /* Discard the two bytes of checksum and stop. */
9723 c = readchar (remote_timeout);
9724 if (c >= 0)
9725 c = readchar (remote_timeout);
9727 return;
9728 case '*': /* Run length encoding. */
9729 /* Discard the repeat count. */
9730 c = readchar (remote_timeout);
9731 if (c < 0)
9732 return;
9733 break;
9734 default:
9735 /* A regular character. */
9736 break;
9741 /* Come here after finding the start of the frame. Collect the rest
9742 into *BUF, verifying the checksum, length, and handling run-length
9743 compression. NUL terminate the buffer. If there is not enough room,
9744 expand *BUF.
9746 Returns -1 on error, number of characters in buffer (ignoring the
9747 trailing NULL) on success. (could be extended to return one of the
9748 SERIAL status indications). */
9750 long
9751 remote_target::read_frame (gdb::char_vector *buf_p)
9753 unsigned char csum;
9754 long bc;
9755 int c;
9756 char *buf = buf_p->data ();
9757 struct remote_state *rs = get_remote_state ();
9759 csum = 0;
9760 bc = 0;
9762 while (1)
9764 c = readchar (remote_timeout);
9765 switch (c)
9767 case SERIAL_TIMEOUT:
9768 remote_debug_printf ("Timeout in mid-packet, retrying");
9769 return -1;
9771 case '$':
9772 remote_debug_printf ("Saw new packet start in middle of old one");
9773 return -1; /* Start a new packet, count retries. */
9775 case '#':
9777 unsigned char pktcsum;
9778 int check_0 = 0;
9779 int check_1 = 0;
9781 buf[bc] = '\0';
9783 check_0 = readchar (remote_timeout);
9784 if (check_0 >= 0)
9785 check_1 = readchar (remote_timeout);
9787 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
9789 remote_debug_printf ("Timeout in checksum, retrying");
9790 return -1;
9792 else if (check_0 < 0 || check_1 < 0)
9794 remote_debug_printf ("Communication error in checksum");
9795 return -1;
9798 /* Don't recompute the checksum; with no ack packets we
9799 don't have any way to indicate a packet retransmission
9800 is necessary. */
9801 if (rs->noack_mode)
9802 return bc;
9804 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
9805 if (csum == pktcsum)
9806 return bc;
9808 remote_debug_printf
9809 ("Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s",
9810 pktcsum, csum, escape_buffer (buf, bc).c_str ());
9812 /* Number of characters in buffer ignoring trailing
9813 NULL. */
9814 return -1;
9816 case '*': /* Run length encoding. */
9818 int repeat;
9820 csum += c;
9821 c = readchar (remote_timeout);
9822 csum += c;
9823 repeat = c - ' ' + 3; /* Compute repeat count. */
9825 /* The character before ``*'' is repeated. */
9827 if (repeat > 0 && repeat <= 255 && bc > 0)
9829 if (bc + repeat - 1 >= buf_p->size () - 1)
9831 /* Make some more room in the buffer. */
9832 buf_p->resize (buf_p->size () + repeat);
9833 buf = buf_p->data ();
9836 memset (&buf[bc], buf[bc - 1], repeat);
9837 bc += repeat;
9838 continue;
9841 buf[bc] = '\0';
9842 gdb_printf (_("Invalid run length encoding: %s\n"), buf);
9843 return -1;
9845 default:
9846 if (bc >= buf_p->size () - 1)
9848 /* Make some more room in the buffer. */
9849 buf_p->resize (buf_p->size () * 2);
9850 buf = buf_p->data ();
9853 buf[bc++] = c;
9854 csum += c;
9855 continue;
9860 /* Set this to the maximum number of seconds to wait instead of waiting forever
9861 in target_wait(). If this timer times out, then it generates an error and
9862 the command is aborted. This replaces most of the need for timeouts in the
9863 GDB test suite, and makes it possible to distinguish between a hung target
9864 and one with slow communications. */
9866 static int watchdog = 0;
9867 static void
9868 show_watchdog (struct ui_file *file, int from_tty,
9869 struct cmd_list_element *c, const char *value)
9871 gdb_printf (file, _("Watchdog timer is %s.\n"), value);
9874 /* Read a packet from the remote machine, with error checking, and
9875 store it in *BUF. Resize *BUF if necessary to hold the result. If
9876 FOREVER, wait forever rather than timing out; this is used (in
9877 synchronous mode) to wait for a target that is is executing user
9878 code to stop. */
9879 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
9880 don't have to change all the calls to getpkt to deal with the
9881 return value, because at the moment I don't know what the right
9882 thing to do it for those. */
9884 void
9885 remote_target::getpkt (gdb::char_vector *buf, int forever)
9887 getpkt_sane (buf, forever);
9891 /* Read a packet from the remote machine, with error checking, and
9892 store it in *BUF. Resize *BUF if necessary to hold the result. If
9893 FOREVER, wait forever rather than timing out; this is used (in
9894 synchronous mode) to wait for a target that is is executing user
9895 code to stop. If FOREVER == 0, this function is allowed to time
9896 out gracefully and return an indication of this to the caller.
9897 Otherwise return the number of bytes read. If EXPECTING_NOTIF,
9898 consider receiving a notification enough reason to return to the
9899 caller. *IS_NOTIF is an output boolean that indicates whether *BUF
9900 holds a notification or not (a regular packet). */
9903 remote_target::getpkt_or_notif_sane_1 (gdb::char_vector *buf,
9904 int forever, int expecting_notif,
9905 int *is_notif)
9907 struct remote_state *rs = get_remote_state ();
9908 int c;
9909 int tries;
9910 int timeout;
9911 int val = -1;
9913 strcpy (buf->data (), "timeout");
9915 if (forever)
9916 timeout = watchdog > 0 ? watchdog : -1;
9917 else if (expecting_notif)
9918 timeout = 0; /* There should already be a char in the buffer. If
9919 not, bail out. */
9920 else
9921 timeout = remote_timeout;
9923 #define MAX_TRIES 3
9925 /* Process any number of notifications, and then return when
9926 we get a packet. */
9927 for (;;)
9929 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
9930 times. */
9931 for (tries = 1; tries <= MAX_TRIES; tries++)
9933 /* This can loop forever if the remote side sends us
9934 characters continuously, but if it pauses, we'll get
9935 SERIAL_TIMEOUT from readchar because of timeout. Then
9936 we'll count that as a retry.
9938 Note that even when forever is set, we will only wait
9939 forever prior to the start of a packet. After that, we
9940 expect characters to arrive at a brisk pace. They should
9941 show up within remote_timeout intervals. */
9943 c = readchar (timeout);
9944 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
9946 if (c == SERIAL_TIMEOUT)
9948 if (expecting_notif)
9949 return -1; /* Don't complain, it's normal to not get
9950 anything in this case. */
9952 if (forever) /* Watchdog went off? Kill the target. */
9954 remote_unpush_target (this);
9955 throw_error (TARGET_CLOSE_ERROR,
9956 _("Watchdog timeout has expired. "
9957 "Target detached."));
9960 remote_debug_printf ("Timed out.");
9962 else
9964 /* We've found the start of a packet or notification.
9965 Now collect the data. */
9966 val = read_frame (buf);
9967 if (val >= 0)
9968 break;
9971 remote_serial_write ("-", 1);
9974 if (tries > MAX_TRIES)
9976 /* We have tried hard enough, and just can't receive the
9977 packet/notification. Give up. */
9978 gdb_printf (_("Ignoring packet error, continuing...\n"));
9980 /* Skip the ack char if we're in no-ack mode. */
9981 if (!rs->noack_mode)
9982 remote_serial_write ("+", 1);
9983 return -1;
9986 /* If we got an ordinary packet, return that to our caller. */
9987 if (c == '$')
9989 if (remote_debug)
9991 int max_chars;
9993 if (remote_packet_max_chars < 0)
9994 max_chars = val;
9995 else
9996 max_chars = remote_packet_max_chars;
9998 std::string str
9999 = escape_buffer (buf->data (),
10000 std::min (val, max_chars));
10002 if (val > max_chars)
10003 remote_debug_printf_nofunc
10004 ("Packet received: %s [%d bytes omitted]", str.c_str (),
10005 val - max_chars);
10006 else
10007 remote_debug_printf_nofunc ("Packet received: %s",
10008 str.c_str ());
10011 /* Skip the ack char if we're in no-ack mode. */
10012 if (!rs->noack_mode)
10013 remote_serial_write ("+", 1);
10014 if (is_notif != NULL)
10015 *is_notif = 0;
10016 return val;
10019 /* If we got a notification, handle it, and go back to looking
10020 for a packet. */
10021 else
10023 gdb_assert (c == '%');
10025 remote_debug_printf_nofunc
10026 (" Notification received: %s",
10027 escape_buffer (buf->data (), val).c_str ());
10029 if (is_notif != NULL)
10030 *is_notif = 1;
10032 handle_notification (rs->notif_state, buf->data ());
10034 /* Notifications require no acknowledgement. */
10036 if (expecting_notif)
10037 return val;
10043 remote_target::getpkt_sane (gdb::char_vector *buf, int forever)
10045 return getpkt_or_notif_sane_1 (buf, forever, 0, NULL);
10049 remote_target::getpkt_or_notif_sane (gdb::char_vector *buf, int forever,
10050 int *is_notif)
10052 return getpkt_or_notif_sane_1 (buf, forever, 1, is_notif);
10055 /* Kill any new fork children of inferior INF that haven't been
10056 processed by follow_fork. */
10058 void
10059 remote_target::kill_new_fork_children (inferior *inf)
10061 remote_state *rs = get_remote_state ();
10062 struct notif_client *notif = &notif_client_stop;
10064 /* Kill the fork child threads of any threads in inferior INF that are stopped
10065 at a fork event. */
10066 for (thread_info *thread : inf->non_exited_threads ())
10068 const target_waitstatus *ws = thread_pending_fork_status (thread);
10070 if (ws == nullptr)
10071 continue;
10073 int child_pid = ws->child_ptid ().pid ();
10074 int res = remote_vkill (child_pid);
10076 if (res != 0)
10077 error (_("Can't kill fork child process %d"), child_pid);
10080 /* Check for any pending fork events (not reported or processed yet)
10081 in inferior INF and kill those fork child threads as well. */
10082 remote_notif_get_pending_events (notif);
10083 for (auto &event : rs->stop_reply_queue)
10085 if (event->ptid.pid () != inf->pid)
10086 continue;
10088 if (!is_fork_status (event->ws.kind ()))
10089 continue;
10091 int child_pid = event->ws.child_ptid ().pid ();
10092 int res = remote_vkill (child_pid);
10094 if (res != 0)
10095 error (_("Can't kill fork child process %d"), child_pid);
10100 /* Target hook to kill the current inferior. */
10102 void
10103 remote_target::kill ()
10105 int res = -1;
10106 inferior *inf = find_inferior_pid (this, inferior_ptid.pid ());
10107 struct remote_state *rs = get_remote_state ();
10109 gdb_assert (inf != nullptr);
10111 if (packet_support (PACKET_vKill) != PACKET_DISABLE)
10113 /* If we're stopped while forking and we haven't followed yet,
10114 kill the child task. We need to do this before killing the
10115 parent task because if this is a vfork then the parent will
10116 be sleeping. */
10117 kill_new_fork_children (inf);
10119 res = remote_vkill (inf->pid);
10120 if (res == 0)
10122 target_mourn_inferior (inferior_ptid);
10123 return;
10127 /* If we are in 'target remote' mode and we are killing the only
10128 inferior, then we will tell gdbserver to exit and unpush the
10129 target. */
10130 if (res == -1 && !remote_multi_process_p (rs)
10131 && number_of_live_inferiors (this) == 1)
10133 remote_kill_k ();
10135 /* We've killed the remote end, we get to mourn it. If we are
10136 not in extended mode, mourning the inferior also unpushes
10137 remote_ops from the target stack, which closes the remote
10138 connection. */
10139 target_mourn_inferior (inferior_ptid);
10141 return;
10144 error (_("Can't kill process"));
10147 /* Send a kill request to the target using the 'vKill' packet. */
10150 remote_target::remote_vkill (int pid)
10152 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
10153 return -1;
10155 remote_state *rs = get_remote_state ();
10157 /* Tell the remote target to detach. */
10158 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vKill;%x", pid);
10159 putpkt (rs->buf);
10160 getpkt (&rs->buf, 0);
10162 switch (packet_ok (rs->buf,
10163 &remote_protocol_packets[PACKET_vKill]))
10165 case PACKET_OK:
10166 return 0;
10167 case PACKET_ERROR:
10168 return 1;
10169 case PACKET_UNKNOWN:
10170 return -1;
10171 default:
10172 internal_error (_("Bad result from packet_ok"));
10176 /* Send a kill request to the target using the 'k' packet. */
10178 void
10179 remote_target::remote_kill_k ()
10181 /* Catch errors so the user can quit from gdb even when we
10182 aren't on speaking terms with the remote system. */
10185 putpkt ("k");
10187 catch (const gdb_exception_error &ex)
10189 if (ex.error == TARGET_CLOSE_ERROR)
10191 /* If we got an (EOF) error that caused the target
10192 to go away, then we're done, that's what we wanted.
10193 "k" is susceptible to cause a premature EOF, given
10194 that the remote server isn't actually required to
10195 reply to "k", and it can happen that it doesn't
10196 even get to reply ACK to the "k". */
10197 return;
10200 /* Otherwise, something went wrong. We didn't actually kill
10201 the target. Just propagate the exception, and let the
10202 user or higher layers decide what to do. */
10203 throw;
10207 void
10208 remote_target::mourn_inferior ()
10210 struct remote_state *rs = get_remote_state ();
10212 /* We're no longer interested in notification events of an inferior
10213 that exited or was killed/detached. */
10214 discard_pending_stop_replies (current_inferior ());
10216 /* In 'target remote' mode with one inferior, we close the connection. */
10217 if (!rs->extended && number_of_live_inferiors (this) <= 1)
10219 remote_unpush_target (this);
10220 return;
10223 /* In case we got here due to an error, but we're going to stay
10224 connected. */
10225 rs->waiting_for_stop_reply = 0;
10227 /* If the current general thread belonged to the process we just
10228 detached from or has exited, the remote side current general
10229 thread becomes undefined. Considering a case like this:
10231 - We just got here due to a detach.
10232 - The process that we're detaching from happens to immediately
10233 report a global breakpoint being hit in non-stop mode, in the
10234 same thread we had selected before.
10235 - GDB attaches to this process again.
10236 - This event happens to be the next event we handle.
10238 GDB would consider that the current general thread didn't need to
10239 be set on the stub side (with Hg), since for all it knew,
10240 GENERAL_THREAD hadn't changed.
10242 Notice that although in all-stop mode, the remote server always
10243 sets the current thread to the thread reporting the stop event,
10244 that doesn't happen in non-stop mode; in non-stop, the stub *must
10245 not* change the current thread when reporting a breakpoint hit,
10246 due to the decoupling of event reporting and event handling.
10248 To keep things simple, we always invalidate our notion of the
10249 current thread. */
10250 record_currthread (rs, minus_one_ptid);
10252 /* Call common code to mark the inferior as not running. */
10253 generic_mourn_inferior ();
10256 bool
10257 extended_remote_target::supports_disable_randomization ()
10259 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
10262 void
10263 remote_target::extended_remote_disable_randomization (int val)
10265 struct remote_state *rs = get_remote_state ();
10266 char *reply;
10268 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10269 "QDisableRandomization:%x", val);
10270 putpkt (rs->buf);
10271 reply = remote_get_noisy_reply ();
10272 if (*reply == '\0')
10273 error (_("Target does not support QDisableRandomization."));
10274 if (strcmp (reply, "OK") != 0)
10275 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
10279 remote_target::extended_remote_run (const std::string &args)
10281 struct remote_state *rs = get_remote_state ();
10282 int len;
10283 const char *remote_exec_file = get_remote_exec_file ();
10285 /* If the user has disabled vRun support, or we have detected that
10286 support is not available, do not try it. */
10287 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
10288 return -1;
10290 strcpy (rs->buf.data (), "vRun;");
10291 len = strlen (rs->buf.data ());
10293 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
10294 error (_("Remote file name too long for run packet"));
10295 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf.data () + len,
10296 strlen (remote_exec_file));
10298 if (!args.empty ())
10300 int i;
10302 gdb_argv argv (args.c_str ());
10303 for (i = 0; argv[i] != NULL; i++)
10305 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
10306 error (_("Argument list too long for run packet"));
10307 rs->buf[len++] = ';';
10308 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf.data () + len,
10309 strlen (argv[i]));
10313 rs->buf[len++] = '\0';
10315 putpkt (rs->buf);
10316 getpkt (&rs->buf, 0);
10318 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
10320 case PACKET_OK:
10321 /* We have a wait response. All is well. */
10322 return 0;
10323 case PACKET_UNKNOWN:
10324 return -1;
10325 case PACKET_ERROR:
10326 if (remote_exec_file[0] == '\0')
10327 error (_("Running the default executable on the remote target failed; "
10328 "try \"set remote exec-file\"?"));
10329 else
10330 error (_("Running \"%s\" on the remote target failed"),
10331 remote_exec_file);
10332 default:
10333 gdb_assert_not_reached ("bad switch");
10337 /* Helper function to send set/unset environment packets. ACTION is
10338 either "set" or "unset". PACKET is either "QEnvironmentHexEncoded"
10339 or "QEnvironmentUnsetVariable". VALUE is the variable to be
10340 sent. */
10342 void
10343 remote_target::send_environment_packet (const char *action,
10344 const char *packet,
10345 const char *value)
10347 remote_state *rs = get_remote_state ();
10349 /* Convert the environment variable to an hex string, which
10350 is the best format to be transmitted over the wire. */
10351 std::string encoded_value = bin2hex ((const gdb_byte *) value,
10352 strlen (value));
10354 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10355 "%s:%s", packet, encoded_value.c_str ());
10357 putpkt (rs->buf);
10358 getpkt (&rs->buf, 0);
10359 if (strcmp (rs->buf.data (), "OK") != 0)
10360 warning (_("Unable to %s environment variable '%s' on remote."),
10361 action, value);
10364 /* Helper function to handle the QEnvironment* packets. */
10366 void
10367 remote_target::extended_remote_environment_support ()
10369 remote_state *rs = get_remote_state ();
10371 if (packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
10373 putpkt ("QEnvironmentReset");
10374 getpkt (&rs->buf, 0);
10375 if (strcmp (rs->buf.data (), "OK") != 0)
10376 warning (_("Unable to reset environment on remote."));
10379 gdb_environ *e = &current_inferior ()->environment;
10381 if (packet_support (PACKET_QEnvironmentHexEncoded) != PACKET_DISABLE)
10382 for (const std::string &el : e->user_set_env ())
10383 send_environment_packet ("set", "QEnvironmentHexEncoded",
10384 el.c_str ());
10386 if (packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
10387 for (const std::string &el : e->user_unset_env ())
10388 send_environment_packet ("unset", "QEnvironmentUnset", el.c_str ());
10391 /* Helper function to set the current working directory for the
10392 inferior in the remote target. */
10394 void
10395 remote_target::extended_remote_set_inferior_cwd ()
10397 if (packet_support (PACKET_QSetWorkingDir) != PACKET_DISABLE)
10399 const std::string &inferior_cwd = current_inferior ()->cwd ();
10400 remote_state *rs = get_remote_state ();
10402 if (!inferior_cwd.empty ())
10404 std::string hexpath
10405 = bin2hex ((const gdb_byte *) inferior_cwd.data (),
10406 inferior_cwd.size ());
10408 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10409 "QSetWorkingDir:%s", hexpath.c_str ());
10411 else
10413 /* An empty inferior_cwd means that the user wants us to
10414 reset the remote server's inferior's cwd. */
10415 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10416 "QSetWorkingDir:");
10419 putpkt (rs->buf);
10420 getpkt (&rs->buf, 0);
10421 if (packet_ok (rs->buf,
10422 &remote_protocol_packets[PACKET_QSetWorkingDir])
10423 != PACKET_OK)
10424 error (_("\
10425 Remote replied unexpectedly while setting the inferior's working\n\
10426 directory: %s"),
10427 rs->buf.data ());
10432 /* In the extended protocol we want to be able to do things like
10433 "run" and have them basically work as expected. So we need
10434 a special create_inferior function. We support changing the
10435 executable file and the command line arguments, but not the
10436 environment. */
10438 void
10439 extended_remote_target::create_inferior (const char *exec_file,
10440 const std::string &args,
10441 char **env, int from_tty)
10443 int run_worked;
10444 char *stop_reply;
10445 struct remote_state *rs = get_remote_state ();
10446 const char *remote_exec_file = get_remote_exec_file ();
10448 /* If running asynchronously, register the target file descriptor
10449 with the event loop. */
10450 if (target_can_async_p ())
10451 target_async (true);
10453 /* Disable address space randomization if requested (and supported). */
10454 if (supports_disable_randomization ())
10455 extended_remote_disable_randomization (disable_randomization);
10457 /* If startup-with-shell is on, we inform gdbserver to start the
10458 remote inferior using a shell. */
10459 if (packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
10461 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10462 "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
10463 putpkt (rs->buf);
10464 getpkt (&rs->buf, 0);
10465 if (strcmp (rs->buf.data (), "OK") != 0)
10466 error (_("\
10467 Remote replied unexpectedly while setting startup-with-shell: %s"),
10468 rs->buf.data ());
10471 extended_remote_environment_support ();
10473 extended_remote_set_inferior_cwd ();
10475 /* Now restart the remote server. */
10476 run_worked = extended_remote_run (args) != -1;
10477 if (!run_worked)
10479 /* vRun was not supported. Fail if we need it to do what the
10480 user requested. */
10481 if (remote_exec_file[0])
10482 error (_("Remote target does not support \"set remote exec-file\""));
10483 if (!args.empty ())
10484 error (_("Remote target does not support \"set args\" or run ARGS"));
10486 /* Fall back to "R". */
10487 extended_remote_restart ();
10490 /* vRun's success return is a stop reply. */
10491 stop_reply = run_worked ? rs->buf.data () : NULL;
10492 add_current_inferior_and_thread (stop_reply);
10494 /* Get updated offsets, if the stub uses qOffsets. */
10495 get_offsets ();
10499 /* Given a location's target info BP_TGT and the packet buffer BUF, output
10500 the list of conditions (in agent expression bytecode format), if any, the
10501 target needs to evaluate. The output is placed into the packet buffer
10502 started from BUF and ended at BUF_END. */
10504 static int
10505 remote_add_target_side_condition (struct gdbarch *gdbarch,
10506 struct bp_target_info *bp_tgt, char *buf,
10507 char *buf_end)
10509 if (bp_tgt->conditions.empty ())
10510 return 0;
10512 buf += strlen (buf);
10513 xsnprintf (buf, buf_end - buf, "%s", ";");
10514 buf++;
10516 /* Send conditions to the target. */
10517 for (agent_expr *aexpr : bp_tgt->conditions)
10519 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
10520 buf += strlen (buf);
10521 for (int i = 0; i < aexpr->len; ++i)
10522 buf = pack_hex_byte (buf, aexpr->buf[i]);
10523 *buf = '\0';
10525 return 0;
10528 static void
10529 remote_add_target_side_commands (struct gdbarch *gdbarch,
10530 struct bp_target_info *bp_tgt, char *buf)
10532 if (bp_tgt->tcommands.empty ())
10533 return;
10535 buf += strlen (buf);
10537 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
10538 buf += strlen (buf);
10540 /* Concatenate all the agent expressions that are commands into the
10541 cmds parameter. */
10542 for (agent_expr *aexpr : bp_tgt->tcommands)
10544 sprintf (buf, "X%x,", aexpr->len);
10545 buf += strlen (buf);
10546 for (int i = 0; i < aexpr->len; ++i)
10547 buf = pack_hex_byte (buf, aexpr->buf[i]);
10548 *buf = '\0';
10552 /* Insert a breakpoint. On targets that have software breakpoint
10553 support, we ask the remote target to do the work; on targets
10554 which don't, we insert a traditional memory breakpoint. */
10557 remote_target::insert_breakpoint (struct gdbarch *gdbarch,
10558 struct bp_target_info *bp_tgt)
10560 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
10561 If it succeeds, then set the support to PACKET_ENABLE. If it
10562 fails, and the user has explicitly requested the Z support then
10563 report an error, otherwise, mark it disabled and go on. */
10565 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
10567 CORE_ADDR addr = bp_tgt->reqstd_address;
10568 struct remote_state *rs;
10569 char *p, *endbuf;
10571 /* Make sure the remote is pointing at the right process, if
10572 necessary. */
10573 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10574 set_general_process ();
10576 rs = get_remote_state ();
10577 p = rs->buf.data ();
10578 endbuf = p + get_remote_packet_size ();
10580 *(p++) = 'Z';
10581 *(p++) = '0';
10582 *(p++) = ',';
10583 addr = (ULONGEST) remote_address_masked (addr);
10584 p += hexnumstr (p, addr);
10585 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10587 if (supports_evaluation_of_breakpoint_conditions ())
10588 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10590 if (can_run_breakpoint_commands ())
10591 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10593 putpkt (rs->buf);
10594 getpkt (&rs->buf, 0);
10596 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
10598 case PACKET_ERROR:
10599 return -1;
10600 case PACKET_OK:
10601 return 0;
10602 case PACKET_UNKNOWN:
10603 break;
10607 /* If this breakpoint has target-side commands but this stub doesn't
10608 support Z0 packets, throw error. */
10609 if (!bp_tgt->tcommands.empty ())
10610 throw_error (NOT_SUPPORTED_ERROR, _("\
10611 Target doesn't support breakpoints that have target side commands."));
10613 return memory_insert_breakpoint (this, gdbarch, bp_tgt);
10617 remote_target::remove_breakpoint (struct gdbarch *gdbarch,
10618 struct bp_target_info *bp_tgt,
10619 enum remove_bp_reason reason)
10621 CORE_ADDR addr = bp_tgt->placed_address;
10622 struct remote_state *rs = get_remote_state ();
10624 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
10626 char *p = rs->buf.data ();
10627 char *endbuf = p + get_remote_packet_size ();
10629 /* Make sure the remote is pointing at the right process, if
10630 necessary. */
10631 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10632 set_general_process ();
10634 *(p++) = 'z';
10635 *(p++) = '0';
10636 *(p++) = ',';
10638 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
10639 p += hexnumstr (p, addr);
10640 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10642 putpkt (rs->buf);
10643 getpkt (&rs->buf, 0);
10645 return (rs->buf[0] == 'E');
10648 return memory_remove_breakpoint (this, gdbarch, bp_tgt, reason);
10651 static enum Z_packet_type
10652 watchpoint_to_Z_packet (int type)
10654 switch (type)
10656 case hw_write:
10657 return Z_PACKET_WRITE_WP;
10658 break;
10659 case hw_read:
10660 return Z_PACKET_READ_WP;
10661 break;
10662 case hw_access:
10663 return Z_PACKET_ACCESS_WP;
10664 break;
10665 default:
10666 internal_error (_("hw_bp_to_z: bad watchpoint type %d"), type);
10671 remote_target::insert_watchpoint (CORE_ADDR addr, int len,
10672 enum target_hw_bp_type type, struct expression *cond)
10674 struct remote_state *rs = get_remote_state ();
10675 char *endbuf = rs->buf.data () + get_remote_packet_size ();
10676 char *p;
10677 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10679 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
10680 return 1;
10682 /* Make sure the remote is pointing at the right process, if
10683 necessary. */
10684 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10685 set_general_process ();
10687 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "Z%x,", packet);
10688 p = strchr (rs->buf.data (), '\0');
10689 addr = remote_address_masked (addr);
10690 p += hexnumstr (p, (ULONGEST) addr);
10691 xsnprintf (p, endbuf - p, ",%x", len);
10693 putpkt (rs->buf);
10694 getpkt (&rs->buf, 0);
10696 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
10698 case PACKET_ERROR:
10699 return -1;
10700 case PACKET_UNKNOWN:
10701 return 1;
10702 case PACKET_OK:
10703 return 0;
10705 internal_error (_("remote_insert_watchpoint: reached end of function"));
10708 bool
10709 remote_target::watchpoint_addr_within_range (CORE_ADDR addr,
10710 CORE_ADDR start, int length)
10712 CORE_ADDR diff = remote_address_masked (addr - start);
10714 return diff < length;
10719 remote_target::remove_watchpoint (CORE_ADDR addr, int len,
10720 enum target_hw_bp_type type, struct expression *cond)
10722 struct remote_state *rs = get_remote_state ();
10723 char *endbuf = rs->buf.data () + get_remote_packet_size ();
10724 char *p;
10725 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10727 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
10728 return -1;
10730 /* Make sure the remote is pointing at the right process, if
10731 necessary. */
10732 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10733 set_general_process ();
10735 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "z%x,", packet);
10736 p = strchr (rs->buf.data (), '\0');
10737 addr = remote_address_masked (addr);
10738 p += hexnumstr (p, (ULONGEST) addr);
10739 xsnprintf (p, endbuf - p, ",%x", len);
10740 putpkt (rs->buf);
10741 getpkt (&rs->buf, 0);
10743 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
10745 case PACKET_ERROR:
10746 case PACKET_UNKNOWN:
10747 return -1;
10748 case PACKET_OK:
10749 return 0;
10751 internal_error (_("remote_remove_watchpoint: reached end of function"));
10755 static int remote_hw_watchpoint_limit = -1;
10756 static int remote_hw_watchpoint_length_limit = -1;
10757 static int remote_hw_breakpoint_limit = -1;
10760 remote_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
10762 if (remote_hw_watchpoint_length_limit == 0)
10763 return 0;
10764 else if (remote_hw_watchpoint_length_limit < 0)
10765 return 1;
10766 else if (len <= remote_hw_watchpoint_length_limit)
10767 return 1;
10768 else
10769 return 0;
10773 remote_target::can_use_hw_breakpoint (enum bptype type, int cnt, int ot)
10775 if (type == bp_hardware_breakpoint)
10777 if (remote_hw_breakpoint_limit == 0)
10778 return 0;
10779 else if (remote_hw_breakpoint_limit < 0)
10780 return 1;
10781 else if (cnt <= remote_hw_breakpoint_limit)
10782 return 1;
10784 else
10786 if (remote_hw_watchpoint_limit == 0)
10787 return 0;
10788 else if (remote_hw_watchpoint_limit < 0)
10789 return 1;
10790 else if (ot)
10791 return -1;
10792 else if (cnt <= remote_hw_watchpoint_limit)
10793 return 1;
10795 return -1;
10798 /* The to_stopped_by_sw_breakpoint method of target remote. */
10800 bool
10801 remote_target::stopped_by_sw_breakpoint ()
10803 struct thread_info *thread = inferior_thread ();
10805 return (thread->priv != NULL
10806 && (get_remote_thread_info (thread)->stop_reason
10807 == TARGET_STOPPED_BY_SW_BREAKPOINT));
10810 /* The to_supports_stopped_by_sw_breakpoint method of target
10811 remote. */
10813 bool
10814 remote_target::supports_stopped_by_sw_breakpoint ()
10816 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
10819 /* The to_stopped_by_hw_breakpoint method of target remote. */
10821 bool
10822 remote_target::stopped_by_hw_breakpoint ()
10824 struct thread_info *thread = inferior_thread ();
10826 return (thread->priv != NULL
10827 && (get_remote_thread_info (thread)->stop_reason
10828 == TARGET_STOPPED_BY_HW_BREAKPOINT));
10831 /* The to_supports_stopped_by_hw_breakpoint method of target
10832 remote. */
10834 bool
10835 remote_target::supports_stopped_by_hw_breakpoint ()
10837 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
10840 bool
10841 remote_target::stopped_by_watchpoint ()
10843 struct thread_info *thread = inferior_thread ();
10845 return (thread->priv != NULL
10846 && (get_remote_thread_info (thread)->stop_reason
10847 == TARGET_STOPPED_BY_WATCHPOINT));
10850 bool
10851 remote_target::stopped_data_address (CORE_ADDR *addr_p)
10853 struct thread_info *thread = inferior_thread ();
10855 if (thread->priv != NULL
10856 && (get_remote_thread_info (thread)->stop_reason
10857 == TARGET_STOPPED_BY_WATCHPOINT))
10859 *addr_p = get_remote_thread_info (thread)->watch_data_address;
10860 return true;
10863 return false;
10868 remote_target::insert_hw_breakpoint (struct gdbarch *gdbarch,
10869 struct bp_target_info *bp_tgt)
10871 CORE_ADDR addr = bp_tgt->reqstd_address;
10872 struct remote_state *rs;
10873 char *p, *endbuf;
10874 char *message;
10876 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10877 return -1;
10879 /* Make sure the remote is pointing at the right process, if
10880 necessary. */
10881 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10882 set_general_process ();
10884 rs = get_remote_state ();
10885 p = rs->buf.data ();
10886 endbuf = p + get_remote_packet_size ();
10888 *(p++) = 'Z';
10889 *(p++) = '1';
10890 *(p++) = ',';
10892 addr = remote_address_masked (addr);
10893 p += hexnumstr (p, (ULONGEST) addr);
10894 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
10896 if (supports_evaluation_of_breakpoint_conditions ())
10897 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10899 if (can_run_breakpoint_commands ())
10900 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10902 putpkt (rs->buf);
10903 getpkt (&rs->buf, 0);
10905 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10907 case PACKET_ERROR:
10908 if (rs->buf[1] == '.')
10910 message = strchr (&rs->buf[2], '.');
10911 if (message)
10912 error (_("Remote failure reply: %s"), message + 1);
10914 return -1;
10915 case PACKET_UNKNOWN:
10916 return -1;
10917 case PACKET_OK:
10918 return 0;
10920 internal_error (_("remote_insert_hw_breakpoint: reached end of function"));
10925 remote_target::remove_hw_breakpoint (struct gdbarch *gdbarch,
10926 struct bp_target_info *bp_tgt)
10928 CORE_ADDR addr;
10929 struct remote_state *rs = get_remote_state ();
10930 char *p = rs->buf.data ();
10931 char *endbuf = p + get_remote_packet_size ();
10933 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10934 return -1;
10936 /* Make sure the remote is pointing at the right process, if
10937 necessary. */
10938 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10939 set_general_process ();
10941 *(p++) = 'z';
10942 *(p++) = '1';
10943 *(p++) = ',';
10945 addr = remote_address_masked (bp_tgt->placed_address);
10946 p += hexnumstr (p, (ULONGEST) addr);
10947 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
10949 putpkt (rs->buf);
10950 getpkt (&rs->buf, 0);
10952 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10954 case PACKET_ERROR:
10955 case PACKET_UNKNOWN:
10956 return -1;
10957 case PACKET_OK:
10958 return 0;
10960 internal_error (_("remote_remove_hw_breakpoint: reached end of function"));
10963 /* Verify memory using the "qCRC:" request. */
10966 remote_target::verify_memory (const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
10968 struct remote_state *rs = get_remote_state ();
10969 unsigned long host_crc, target_crc;
10970 char *tmp;
10972 /* It doesn't make sense to use qCRC if the remote target is
10973 connected but not running. */
10974 if (target_has_execution ()
10975 && packet_support (PACKET_qCRC) != PACKET_DISABLE)
10977 enum packet_result result;
10979 /* Make sure the remote is pointing at the right process. */
10980 set_general_process ();
10982 /* FIXME: assumes lma can fit into long. */
10983 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qCRC:%lx,%lx",
10984 (long) lma, (long) size);
10985 putpkt (rs->buf);
10987 /* Be clever; compute the host_crc before waiting for target
10988 reply. */
10989 host_crc = xcrc32 (data, size, 0xffffffff);
10991 getpkt (&rs->buf, 0);
10993 result = packet_ok (rs->buf,
10994 &remote_protocol_packets[PACKET_qCRC]);
10995 if (result == PACKET_ERROR)
10996 return -1;
10997 else if (result == PACKET_OK)
10999 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
11000 target_crc = target_crc * 16 + fromhex (*tmp);
11002 return (host_crc == target_crc);
11006 return simple_verify_memory (this, data, lma, size);
11009 /* compare-sections command
11011 With no arguments, compares each loadable section in the exec bfd
11012 with the same memory range on the target, and reports mismatches.
11013 Useful for verifying the image on the target against the exec file. */
11015 static void
11016 compare_sections_command (const char *args, int from_tty)
11018 asection *s;
11019 const char *sectname;
11020 bfd_size_type size;
11021 bfd_vma lma;
11022 int matched = 0;
11023 int mismatched = 0;
11024 int res;
11025 int read_only = 0;
11027 if (!current_program_space->exec_bfd ())
11028 error (_("command cannot be used without an exec file"));
11030 if (args != NULL && strcmp (args, "-r") == 0)
11032 read_only = 1;
11033 args = NULL;
11036 for (s = current_program_space->exec_bfd ()->sections; s; s = s->next)
11038 if (!(s->flags & SEC_LOAD))
11039 continue; /* Skip non-loadable section. */
11041 if (read_only && (s->flags & SEC_READONLY) == 0)
11042 continue; /* Skip writeable sections */
11044 size = bfd_section_size (s);
11045 if (size == 0)
11046 continue; /* Skip zero-length section. */
11048 sectname = bfd_section_name (s);
11049 if (args && strcmp (args, sectname) != 0)
11050 continue; /* Not the section selected by user. */
11052 matched = 1; /* Do this section. */
11053 lma = s->lma;
11055 gdb::byte_vector sectdata (size);
11056 bfd_get_section_contents (current_program_space->exec_bfd (), s,
11057 sectdata.data (), 0, size);
11059 res = target_verify_memory (sectdata.data (), lma, size);
11061 if (res == -1)
11062 error (_("target memory fault, section %s, range %s -- %s"), sectname,
11063 paddress (target_gdbarch (), lma),
11064 paddress (target_gdbarch (), lma + size));
11066 gdb_printf ("Section %s, range %s -- %s: ", sectname,
11067 paddress (target_gdbarch (), lma),
11068 paddress (target_gdbarch (), lma + size));
11069 if (res)
11070 gdb_printf ("matched.\n");
11071 else
11073 gdb_printf ("MIS-MATCHED!\n");
11074 mismatched++;
11077 if (mismatched > 0)
11078 warning (_("One or more sections of the target image does not match\n\
11079 the loaded file\n"));
11080 if (args && !matched)
11081 gdb_printf (_("No loaded section named '%s'.\n"), args);
11084 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
11085 into remote target. The number of bytes written to the remote
11086 target is returned, or -1 for error. */
11088 target_xfer_status
11089 remote_target::remote_write_qxfer (const char *object_name,
11090 const char *annex, const gdb_byte *writebuf,
11091 ULONGEST offset, LONGEST len,
11092 ULONGEST *xfered_len,
11093 struct packet_config *packet)
11095 int i, buf_len;
11096 ULONGEST n;
11097 struct remote_state *rs = get_remote_state ();
11098 int max_size = get_memory_write_packet_size ();
11100 if (packet_config_support (packet) == PACKET_DISABLE)
11101 return TARGET_XFER_E_IO;
11103 /* Insert header. */
11104 i = snprintf (rs->buf.data (), max_size,
11105 "qXfer:%s:write:%s:%s:",
11106 object_name, annex ? annex : "",
11107 phex_nz (offset, sizeof offset));
11108 max_size -= (i + 1);
11110 /* Escape as much data as fits into rs->buf. */
11111 buf_len = remote_escape_output
11112 (writebuf, len, 1, (gdb_byte *) rs->buf.data () + i, &max_size, max_size);
11114 if (putpkt_binary (rs->buf.data (), i + buf_len) < 0
11115 || getpkt_sane (&rs->buf, 0) < 0
11116 || packet_ok (rs->buf, packet) != PACKET_OK)
11117 return TARGET_XFER_E_IO;
11119 unpack_varlen_hex (rs->buf.data (), &n);
11121 *xfered_len = n;
11122 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
11125 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
11126 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
11127 number of bytes read is returned, or 0 for EOF, or -1 for error.
11128 The number of bytes read may be less than LEN without indicating an
11129 EOF. PACKET is checked and updated to indicate whether the remote
11130 target supports this object. */
11132 target_xfer_status
11133 remote_target::remote_read_qxfer (const char *object_name,
11134 const char *annex,
11135 gdb_byte *readbuf, ULONGEST offset,
11136 LONGEST len,
11137 ULONGEST *xfered_len,
11138 struct packet_config *packet)
11140 struct remote_state *rs = get_remote_state ();
11141 LONGEST i, n, packet_len;
11143 if (packet_config_support (packet) == PACKET_DISABLE)
11144 return TARGET_XFER_E_IO;
11146 /* Check whether we've cached an end-of-object packet that matches
11147 this request. */
11148 if (rs->finished_object)
11150 if (strcmp (object_name, rs->finished_object) == 0
11151 && strcmp (annex ? annex : "", rs->finished_annex) == 0
11152 && offset == rs->finished_offset)
11153 return TARGET_XFER_EOF;
11156 /* Otherwise, we're now reading something different. Discard
11157 the cache. */
11158 xfree (rs->finished_object);
11159 xfree (rs->finished_annex);
11160 rs->finished_object = NULL;
11161 rs->finished_annex = NULL;
11164 /* Request only enough to fit in a single packet. The actual data
11165 may not, since we don't know how much of it will need to be escaped;
11166 the target is free to respond with slightly less data. We subtract
11167 five to account for the response type and the protocol frame. */
11168 n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
11169 snprintf (rs->buf.data (), get_remote_packet_size () - 4,
11170 "qXfer:%s:read:%s:%s,%s",
11171 object_name, annex ? annex : "",
11172 phex_nz (offset, sizeof offset),
11173 phex_nz (n, sizeof n));
11174 i = putpkt (rs->buf);
11175 if (i < 0)
11176 return TARGET_XFER_E_IO;
11178 rs->buf[0] = '\0';
11179 packet_len = getpkt_sane (&rs->buf, 0);
11180 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
11181 return TARGET_XFER_E_IO;
11183 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
11184 error (_("Unknown remote qXfer reply: %s"), rs->buf.data ());
11186 /* 'm' means there is (or at least might be) more data after this
11187 batch. That does not make sense unless there's at least one byte
11188 of data in this reply. */
11189 if (rs->buf[0] == 'm' && packet_len == 1)
11190 error (_("Remote qXfer reply contained no data."));
11192 /* Got some data. */
11193 i = remote_unescape_input ((gdb_byte *) rs->buf.data () + 1,
11194 packet_len - 1, readbuf, n);
11196 /* 'l' is an EOF marker, possibly including a final block of data,
11197 or possibly empty. If we have the final block of a non-empty
11198 object, record this fact to bypass a subsequent partial read. */
11199 if (rs->buf[0] == 'l' && offset + i > 0)
11201 rs->finished_object = xstrdup (object_name);
11202 rs->finished_annex = xstrdup (annex ? annex : "");
11203 rs->finished_offset = offset + i;
11206 if (i == 0)
11207 return TARGET_XFER_EOF;
11208 else
11210 *xfered_len = i;
11211 return TARGET_XFER_OK;
11215 enum target_xfer_status
11216 remote_target::xfer_partial (enum target_object object,
11217 const char *annex, gdb_byte *readbuf,
11218 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
11219 ULONGEST *xfered_len)
11221 struct remote_state *rs;
11222 int i;
11223 char *p2;
11224 char query_type;
11225 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
11227 set_remote_traceframe ();
11228 set_general_thread (inferior_ptid);
11230 rs = get_remote_state ();
11232 /* Handle memory using the standard memory routines. */
11233 if (object == TARGET_OBJECT_MEMORY)
11235 /* If the remote target is connected but not running, we should
11236 pass this request down to a lower stratum (e.g. the executable
11237 file). */
11238 if (!target_has_execution ())
11239 return TARGET_XFER_EOF;
11241 if (writebuf != NULL)
11242 return remote_write_bytes (offset, writebuf, len, unit_size,
11243 xfered_len);
11244 else
11245 return remote_read_bytes (offset, readbuf, len, unit_size,
11246 xfered_len);
11249 /* Handle extra signal info using qxfer packets. */
11250 if (object == TARGET_OBJECT_SIGNAL_INFO)
11252 if (readbuf)
11253 return remote_read_qxfer ("siginfo", annex, readbuf, offset, len,
11254 xfered_len, &remote_protocol_packets
11255 [PACKET_qXfer_siginfo_read]);
11256 else
11257 return remote_write_qxfer ("siginfo", annex,
11258 writebuf, offset, len, xfered_len,
11259 &remote_protocol_packets
11260 [PACKET_qXfer_siginfo_write]);
11263 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
11265 if (readbuf)
11266 return remote_read_qxfer ("statictrace", annex,
11267 readbuf, offset, len, xfered_len,
11268 &remote_protocol_packets
11269 [PACKET_qXfer_statictrace_read]);
11270 else
11271 return TARGET_XFER_E_IO;
11274 /* Only handle flash writes. */
11275 if (writebuf != NULL)
11277 switch (object)
11279 case TARGET_OBJECT_FLASH:
11280 return remote_flash_write (offset, len, xfered_len,
11281 writebuf);
11283 default:
11284 return TARGET_XFER_E_IO;
11288 /* Map pre-existing objects onto letters. DO NOT do this for new
11289 objects!!! Instead specify new query packets. */
11290 switch (object)
11292 case TARGET_OBJECT_AVR:
11293 query_type = 'R';
11294 break;
11296 case TARGET_OBJECT_AUXV:
11297 gdb_assert (annex == NULL);
11298 return remote_read_qxfer ("auxv", annex, readbuf, offset, len,
11299 xfered_len,
11300 &remote_protocol_packets[PACKET_qXfer_auxv]);
11302 case TARGET_OBJECT_AVAILABLE_FEATURES:
11303 return remote_read_qxfer
11304 ("features", annex, readbuf, offset, len, xfered_len,
11305 &remote_protocol_packets[PACKET_qXfer_features]);
11307 case TARGET_OBJECT_LIBRARIES:
11308 return remote_read_qxfer
11309 ("libraries", annex, readbuf, offset, len, xfered_len,
11310 &remote_protocol_packets[PACKET_qXfer_libraries]);
11312 case TARGET_OBJECT_LIBRARIES_SVR4:
11313 return remote_read_qxfer
11314 ("libraries-svr4", annex, readbuf, offset, len, xfered_len,
11315 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
11317 case TARGET_OBJECT_MEMORY_MAP:
11318 gdb_assert (annex == NULL);
11319 return remote_read_qxfer ("memory-map", annex, readbuf, offset, len,
11320 xfered_len,
11321 &remote_protocol_packets[PACKET_qXfer_memory_map]);
11323 case TARGET_OBJECT_OSDATA:
11324 /* Should only get here if we're connected. */
11325 gdb_assert (rs->remote_desc);
11326 return remote_read_qxfer
11327 ("osdata", annex, readbuf, offset, len, xfered_len,
11328 &remote_protocol_packets[PACKET_qXfer_osdata]);
11330 case TARGET_OBJECT_THREADS:
11331 gdb_assert (annex == NULL);
11332 return remote_read_qxfer ("threads", annex, readbuf, offset, len,
11333 xfered_len,
11334 &remote_protocol_packets[PACKET_qXfer_threads]);
11336 case TARGET_OBJECT_TRACEFRAME_INFO:
11337 gdb_assert (annex == NULL);
11338 return remote_read_qxfer
11339 ("traceframe-info", annex, readbuf, offset, len, xfered_len,
11340 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
11342 case TARGET_OBJECT_FDPIC:
11343 return remote_read_qxfer ("fdpic", annex, readbuf, offset, len,
11344 xfered_len,
11345 &remote_protocol_packets[PACKET_qXfer_fdpic]);
11347 case TARGET_OBJECT_OPENVMS_UIB:
11348 return remote_read_qxfer ("uib", annex, readbuf, offset, len,
11349 xfered_len,
11350 &remote_protocol_packets[PACKET_qXfer_uib]);
11352 case TARGET_OBJECT_BTRACE:
11353 return remote_read_qxfer ("btrace", annex, readbuf, offset, len,
11354 xfered_len,
11355 &remote_protocol_packets[PACKET_qXfer_btrace]);
11357 case TARGET_OBJECT_BTRACE_CONF:
11358 return remote_read_qxfer ("btrace-conf", annex, readbuf, offset,
11359 len, xfered_len,
11360 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
11362 case TARGET_OBJECT_EXEC_FILE:
11363 return remote_read_qxfer ("exec-file", annex, readbuf, offset,
11364 len, xfered_len,
11365 &remote_protocol_packets[PACKET_qXfer_exec_file]);
11367 default:
11368 return TARGET_XFER_E_IO;
11371 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
11372 large enough let the caller deal with it. */
11373 if (len < get_remote_packet_size ())
11374 return TARGET_XFER_E_IO;
11375 len = get_remote_packet_size ();
11377 /* Except for querying the minimum buffer size, target must be open. */
11378 if (!rs->remote_desc)
11379 error (_("remote query is only available after target open"));
11381 gdb_assert (annex != NULL);
11382 gdb_assert (readbuf != NULL);
11384 p2 = rs->buf.data ();
11385 *p2++ = 'q';
11386 *p2++ = query_type;
11388 /* We used one buffer char for the remote protocol q command and
11389 another for the query type. As the remote protocol encapsulation
11390 uses 4 chars plus one extra in case we are debugging
11391 (remote_debug), we have PBUFZIZ - 7 left to pack the query
11392 string. */
11393 i = 0;
11394 while (annex[i] && (i < (get_remote_packet_size () - 8)))
11396 /* Bad caller may have sent forbidden characters. */
11397 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
11398 *p2++ = annex[i];
11399 i++;
11401 *p2 = '\0';
11402 gdb_assert (annex[i] == '\0');
11404 i = putpkt (rs->buf);
11405 if (i < 0)
11406 return TARGET_XFER_E_IO;
11408 getpkt (&rs->buf, 0);
11409 strcpy ((char *) readbuf, rs->buf.data ());
11411 *xfered_len = strlen ((char *) readbuf);
11412 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
11415 /* Implementation of to_get_memory_xfer_limit. */
11417 ULONGEST
11418 remote_target::get_memory_xfer_limit ()
11420 return get_memory_write_packet_size ();
11424 remote_target::search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
11425 const gdb_byte *pattern, ULONGEST pattern_len,
11426 CORE_ADDR *found_addrp)
11428 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
11429 struct remote_state *rs = get_remote_state ();
11430 int max_size = get_memory_write_packet_size ();
11431 struct packet_config *packet =
11432 &remote_protocol_packets[PACKET_qSearch_memory];
11433 /* Number of packet bytes used to encode the pattern;
11434 this could be more than PATTERN_LEN due to escape characters. */
11435 int escaped_pattern_len;
11436 /* Amount of pattern that was encodable in the packet. */
11437 int used_pattern_len;
11438 int i;
11439 int found;
11440 ULONGEST found_addr;
11442 auto read_memory = [=] (CORE_ADDR addr, gdb_byte *result, size_t len)
11444 return (target_read (this, TARGET_OBJECT_MEMORY, NULL, result, addr, len)
11445 == len);
11448 /* Don't go to the target if we don't have to. This is done before
11449 checking packet_config_support to avoid the possibility that a
11450 success for this edge case means the facility works in
11451 general. */
11452 if (pattern_len > search_space_len)
11453 return 0;
11454 if (pattern_len == 0)
11456 *found_addrp = start_addr;
11457 return 1;
11460 /* If we already know the packet isn't supported, fall back to the simple
11461 way of searching memory. */
11463 if (packet_config_support (packet) == PACKET_DISABLE)
11465 /* Target doesn't provided special support, fall back and use the
11466 standard support (copy memory and do the search here). */
11467 return simple_search_memory (read_memory, start_addr, search_space_len,
11468 pattern, pattern_len, found_addrp);
11471 /* Make sure the remote is pointing at the right process. */
11472 set_general_process ();
11474 /* Insert header. */
11475 i = snprintf (rs->buf.data (), max_size,
11476 "qSearch:memory:%s;%s;",
11477 phex_nz (start_addr, addr_size),
11478 phex_nz (search_space_len, sizeof (search_space_len)));
11479 max_size -= (i + 1);
11481 /* Escape as much data as fits into rs->buf. */
11482 escaped_pattern_len =
11483 remote_escape_output (pattern, pattern_len, 1,
11484 (gdb_byte *) rs->buf.data () + i,
11485 &used_pattern_len, max_size);
11487 /* Bail if the pattern is too large. */
11488 if (used_pattern_len != pattern_len)
11489 error (_("Pattern is too large to transmit to remote target."));
11491 if (putpkt_binary (rs->buf.data (), i + escaped_pattern_len) < 0
11492 || getpkt_sane (&rs->buf, 0) < 0
11493 || packet_ok (rs->buf, packet) != PACKET_OK)
11495 /* The request may not have worked because the command is not
11496 supported. If so, fall back to the simple way. */
11497 if (packet_config_support (packet) == PACKET_DISABLE)
11499 return simple_search_memory (read_memory, start_addr, search_space_len,
11500 pattern, pattern_len, found_addrp);
11502 return -1;
11505 if (rs->buf[0] == '0')
11506 found = 0;
11507 else if (rs->buf[0] == '1')
11509 found = 1;
11510 if (rs->buf[1] != ',')
11511 error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
11512 unpack_varlen_hex (&rs->buf[2], &found_addr);
11513 *found_addrp = found_addr;
11515 else
11516 error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
11518 return found;
11521 void
11522 remote_target::rcmd (const char *command, struct ui_file *outbuf)
11524 struct remote_state *rs = get_remote_state ();
11525 char *p = rs->buf.data ();
11527 if (!rs->remote_desc)
11528 error (_("remote rcmd is only available after target open"));
11530 /* Send a NULL command across as an empty command. */
11531 if (command == NULL)
11532 command = "";
11534 /* The query prefix. */
11535 strcpy (rs->buf.data (), "qRcmd,");
11536 p = strchr (rs->buf.data (), '\0');
11538 if ((strlen (rs->buf.data ()) + strlen (command) * 2 + 8/*misc*/)
11539 > get_remote_packet_size ())
11540 error (_("\"monitor\" command ``%s'' is too long."), command);
11542 /* Encode the actual command. */
11543 bin2hex ((const gdb_byte *) command, p, strlen (command));
11545 if (putpkt (rs->buf) < 0)
11546 error (_("Communication problem with target."));
11548 /* get/display the response */
11549 while (1)
11551 char *buf;
11553 /* XXX - see also remote_get_noisy_reply(). */
11554 QUIT; /* Allow user to bail out with ^C. */
11555 rs->buf[0] = '\0';
11556 if (getpkt_sane (&rs->buf, 0) == -1)
11558 /* Timeout. Continue to (try to) read responses.
11559 This is better than stopping with an error, assuming the stub
11560 is still executing the (long) monitor command.
11561 If needed, the user can interrupt gdb using C-c, obtaining
11562 an effect similar to stop on timeout. */
11563 continue;
11565 buf = rs->buf.data ();
11566 if (buf[0] == '\0')
11567 error (_("Target does not support this command."));
11568 if (buf[0] == 'O' && buf[1] != 'K')
11570 remote_console_output (buf + 1); /* 'O' message from stub. */
11571 continue;
11573 if (strcmp (buf, "OK") == 0)
11574 break;
11575 if (strlen (buf) == 3 && buf[0] == 'E'
11576 && isxdigit (buf[1]) && isxdigit (buf[2]))
11578 error (_("Protocol error with Rcmd"));
11580 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
11582 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
11584 gdb_putc (c, outbuf);
11586 break;
11590 std::vector<mem_region>
11591 remote_target::memory_map ()
11593 std::vector<mem_region> result;
11594 gdb::optional<gdb::char_vector> text
11595 = target_read_stralloc (current_inferior ()->top_target (),
11596 TARGET_OBJECT_MEMORY_MAP, NULL);
11598 if (text)
11599 result = parse_memory_map (text->data ());
11601 return result;
11604 /* Set of callbacks used to implement the 'maint packet' command. */
11606 struct cli_packet_command_callbacks : public send_remote_packet_callbacks
11608 /* Called before the packet is sent. BUF is the packet content before
11609 the protocol specific prefix, suffix, and escaping is added. */
11611 void sending (gdb::array_view<const char> &buf) override
11613 gdb_puts ("sending: ");
11614 print_packet (buf);
11615 gdb_puts ("\n");
11618 /* Called with BUF, the reply from the remote target. */
11620 void received (gdb::array_view<const char> &buf) override
11622 gdb_puts ("received: \"");
11623 print_packet (buf);
11624 gdb_puts ("\"\n");
11627 private:
11629 /* Print BUF o gdb_stdout. Any non-printable bytes in BUF are printed as
11630 '\x??' with '??' replaced by the hexadecimal value of the byte. */
11632 static void
11633 print_packet (gdb::array_view<const char> &buf)
11635 string_file stb;
11637 for (int i = 0; i < buf.size (); ++i)
11639 gdb_byte c = buf[i];
11640 if (isprint (c))
11641 gdb_putc (c, &stb);
11642 else
11643 gdb_printf (&stb, "\\x%02x", (unsigned char) c);
11646 gdb_puts (stb.string ().c_str ());
11650 /* See remote.h. */
11652 void
11653 send_remote_packet (gdb::array_view<const char> &buf,
11654 send_remote_packet_callbacks *callbacks)
11656 if (buf.size () == 0 || buf.data ()[0] == '\0')
11657 error (_("a remote packet must not be empty"));
11659 remote_target *remote = get_current_remote_target ();
11660 if (remote == nullptr)
11661 error (_("packets can only be sent to a remote target"));
11663 callbacks->sending (buf);
11665 remote->putpkt_binary (buf.data (), buf.size ());
11666 remote_state *rs = remote->get_remote_state ();
11667 int bytes = remote->getpkt_sane (&rs->buf, 0);
11669 if (bytes < 0)
11670 error (_("error while fetching packet from remote target"));
11672 gdb::array_view<const char> view (&rs->buf[0], bytes);
11673 callbacks->received (view);
11676 /* Entry point for the 'maint packet' command. */
11678 static void
11679 cli_packet_command (const char *args, int from_tty)
11681 cli_packet_command_callbacks cb;
11682 gdb::array_view<const char> view
11683 = gdb::make_array_view (args, args == nullptr ? 0 : strlen (args));
11684 send_remote_packet (view, &cb);
11687 #if 0
11688 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
11690 static void display_thread_info (struct gdb_ext_thread_info *info);
11692 static void threadset_test_cmd (char *cmd, int tty);
11694 static void threadalive_test (char *cmd, int tty);
11696 static void threadlist_test_cmd (char *cmd, int tty);
11698 int get_and_display_threadinfo (threadref *ref);
11700 static void threadinfo_test_cmd (char *cmd, int tty);
11702 static int thread_display_step (threadref *ref, void *context);
11704 static void threadlist_update_test_cmd (char *cmd, int tty);
11706 static void init_remote_threadtests (void);
11708 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
11710 static void
11711 threadset_test_cmd (const char *cmd, int tty)
11713 int sample_thread = SAMPLE_THREAD;
11715 gdb_printf (_("Remote threadset test\n"));
11716 set_general_thread (sample_thread);
11720 static void
11721 threadalive_test (const char *cmd, int tty)
11723 int sample_thread = SAMPLE_THREAD;
11724 int pid = inferior_ptid.pid ();
11725 ptid_t ptid = ptid_t (pid, sample_thread, 0);
11727 if (remote_thread_alive (ptid))
11728 gdb_printf ("PASS: Thread alive test\n");
11729 else
11730 gdb_printf ("FAIL: Thread alive test\n");
11733 void output_threadid (char *title, threadref *ref);
11735 void
11736 output_threadid (char *title, threadref *ref)
11738 char hexid[20];
11740 pack_threadid (&hexid[0], ref); /* Convert thread id into hex. */
11741 hexid[16] = 0;
11742 gdb_printf ("%s %s\n", title, (&hexid[0]));
11745 static void
11746 threadlist_test_cmd (const char *cmd, int tty)
11748 int startflag = 1;
11749 threadref nextthread;
11750 int done, result_count;
11751 threadref threadlist[3];
11753 gdb_printf ("Remote Threadlist test\n");
11754 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
11755 &result_count, &threadlist[0]))
11756 gdb_printf ("FAIL: threadlist test\n");
11757 else
11759 threadref *scan = threadlist;
11760 threadref *limit = scan + result_count;
11762 while (scan < limit)
11763 output_threadid (" thread ", scan++);
11767 void
11768 display_thread_info (struct gdb_ext_thread_info *info)
11770 output_threadid ("Threadid: ", &info->threadid);
11771 gdb_printf ("Name: %s\n ", info->shortname);
11772 gdb_printf ("State: %s\n", info->display);
11773 gdb_printf ("other: %s\n\n", info->more_display);
11777 get_and_display_threadinfo (threadref *ref)
11779 int result;
11780 int set;
11781 struct gdb_ext_thread_info threadinfo;
11783 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
11784 | TAG_MOREDISPLAY | TAG_DISPLAY;
11785 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
11786 display_thread_info (&threadinfo);
11787 return result;
11790 static void
11791 threadinfo_test_cmd (const char *cmd, int tty)
11793 int athread = SAMPLE_THREAD;
11794 threadref thread;
11795 int set;
11797 int_to_threadref (&thread, athread);
11798 gdb_printf ("Remote Threadinfo test\n");
11799 if (!get_and_display_threadinfo (&thread))
11800 gdb_printf ("FAIL cannot get thread info\n");
11803 static int
11804 thread_display_step (threadref *ref, void *context)
11806 /* output_threadid(" threadstep ",ref); *//* simple test */
11807 return get_and_display_threadinfo (ref);
11810 static void
11811 threadlist_update_test_cmd (const char *cmd, int tty)
11813 gdb_printf ("Remote Threadlist update test\n");
11814 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
11817 static void
11818 init_remote_threadtests (void)
11820 add_com ("tlist", class_obscure, threadlist_test_cmd,
11821 _("Fetch and print the remote list of "
11822 "thread identifiers, one pkt only."));
11823 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
11824 _("Fetch and display info about one thread."));
11825 add_com ("tset", class_obscure, threadset_test_cmd,
11826 _("Test setting to a different thread."));
11827 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
11828 _("Iterate through updating all remote thread info."));
11829 add_com ("talive", class_obscure, threadalive_test,
11830 _("Remote thread alive test."));
11833 #endif /* 0 */
11835 /* Convert a thread ID to a string. */
11837 std::string
11838 remote_target::pid_to_str (ptid_t ptid)
11840 struct remote_state *rs = get_remote_state ();
11842 if (ptid == null_ptid)
11843 return normal_pid_to_str (ptid);
11844 else if (ptid.is_pid ())
11846 /* Printing an inferior target id. */
11848 /* When multi-process extensions are off, there's no way in the
11849 remote protocol to know the remote process id, if there's any
11850 at all. There's one exception --- when we're connected with
11851 target extended-remote, and we manually attached to a process
11852 with "attach PID". We don't record anywhere a flag that
11853 allows us to distinguish that case from the case of
11854 connecting with extended-remote and the stub already being
11855 attached to a process, and reporting yes to qAttached, hence
11856 no smart special casing here. */
11857 if (!remote_multi_process_p (rs))
11858 return "Remote target";
11860 return normal_pid_to_str (ptid);
11862 else
11864 if (magic_null_ptid == ptid)
11865 return "Thread <main>";
11866 else if (remote_multi_process_p (rs))
11867 if (ptid.lwp () == 0)
11868 return normal_pid_to_str (ptid);
11869 else
11870 return string_printf ("Thread %d.%ld",
11871 ptid.pid (), ptid.lwp ());
11872 else
11873 return string_printf ("Thread %ld", ptid.lwp ());
11877 /* Get the address of the thread local variable in OBJFILE which is
11878 stored at OFFSET within the thread local storage for thread PTID. */
11880 CORE_ADDR
11881 remote_target::get_thread_local_address (ptid_t ptid, CORE_ADDR lm,
11882 CORE_ADDR offset)
11884 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
11886 struct remote_state *rs = get_remote_state ();
11887 char *p = rs->buf.data ();
11888 char *endp = p + get_remote_packet_size ();
11889 enum packet_result result;
11891 strcpy (p, "qGetTLSAddr:");
11892 p += strlen (p);
11893 p = write_ptid (p, endp, ptid);
11894 *p++ = ',';
11895 p += hexnumstr (p, offset);
11896 *p++ = ',';
11897 p += hexnumstr (p, lm);
11898 *p++ = '\0';
11900 putpkt (rs->buf);
11901 getpkt (&rs->buf, 0);
11902 result = packet_ok (rs->buf,
11903 &remote_protocol_packets[PACKET_qGetTLSAddr]);
11904 if (result == PACKET_OK)
11906 ULONGEST addr;
11908 unpack_varlen_hex (rs->buf.data (), &addr);
11909 return addr;
11911 else if (result == PACKET_UNKNOWN)
11912 throw_error (TLS_GENERIC_ERROR,
11913 _("Remote target doesn't support qGetTLSAddr packet"));
11914 else
11915 throw_error (TLS_GENERIC_ERROR,
11916 _("Remote target failed to process qGetTLSAddr request"));
11918 else
11919 throw_error (TLS_GENERIC_ERROR,
11920 _("TLS not supported or disabled on this target"));
11921 /* Not reached. */
11922 return 0;
11925 /* Provide thread local base, i.e. Thread Information Block address.
11926 Returns 1 if ptid is found and thread_local_base is non zero. */
11928 bool
11929 remote_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
11931 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
11933 struct remote_state *rs = get_remote_state ();
11934 char *p = rs->buf.data ();
11935 char *endp = p + get_remote_packet_size ();
11936 enum packet_result result;
11938 strcpy (p, "qGetTIBAddr:");
11939 p += strlen (p);
11940 p = write_ptid (p, endp, ptid);
11941 *p++ = '\0';
11943 putpkt (rs->buf);
11944 getpkt (&rs->buf, 0);
11945 result = packet_ok (rs->buf,
11946 &remote_protocol_packets[PACKET_qGetTIBAddr]);
11947 if (result == PACKET_OK)
11949 ULONGEST val;
11950 unpack_varlen_hex (rs->buf.data (), &val);
11951 if (addr)
11952 *addr = (CORE_ADDR) val;
11953 return true;
11955 else if (result == PACKET_UNKNOWN)
11956 error (_("Remote target doesn't support qGetTIBAddr packet"));
11957 else
11958 error (_("Remote target failed to process qGetTIBAddr request"));
11960 else
11961 error (_("qGetTIBAddr not supported or disabled on this target"));
11962 /* Not reached. */
11963 return false;
11966 /* Support for inferring a target description based on the current
11967 architecture and the size of a 'g' packet. While the 'g' packet
11968 can have any size (since optional registers can be left off the
11969 end), some sizes are easily recognizable given knowledge of the
11970 approximate architecture. */
11972 struct remote_g_packet_guess
11974 remote_g_packet_guess (int bytes_, const struct target_desc *tdesc_)
11975 : bytes (bytes_),
11976 tdesc (tdesc_)
11980 int bytes;
11981 const struct target_desc *tdesc;
11984 struct remote_g_packet_data
11986 std::vector<remote_g_packet_guess> guesses;
11989 static const registry<gdbarch>::key<struct remote_g_packet_data>
11990 remote_g_packet_data_handle;
11992 static struct remote_g_packet_data *
11993 get_g_packet_data (struct gdbarch *gdbarch)
11995 struct remote_g_packet_data *data
11996 = remote_g_packet_data_handle.get (gdbarch);
11997 if (data == nullptr)
11998 data = remote_g_packet_data_handle.emplace (gdbarch);
11999 return data;
12002 void
12003 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
12004 const struct target_desc *tdesc)
12006 struct remote_g_packet_data *data = get_g_packet_data (gdbarch);
12008 gdb_assert (tdesc != NULL);
12010 for (const remote_g_packet_guess &guess : data->guesses)
12011 if (guess.bytes == bytes)
12012 internal_error (_("Duplicate g packet description added for size %d"),
12013 bytes);
12015 data->guesses.emplace_back (bytes, tdesc);
12018 /* Return true if remote_read_description would do anything on this target
12019 and architecture, false otherwise. */
12021 static bool
12022 remote_read_description_p (struct target_ops *target)
12024 struct remote_g_packet_data *data = get_g_packet_data (target_gdbarch ());
12026 return !data->guesses.empty ();
12029 const struct target_desc *
12030 remote_target::read_description ()
12032 struct remote_g_packet_data *data = get_g_packet_data (target_gdbarch ());
12034 /* Do not try this during initial connection, when we do not know
12035 whether there is a running but stopped thread. */
12036 if (!target_has_execution () || inferior_ptid == null_ptid)
12037 return beneath ()->read_description ();
12039 if (!data->guesses.empty ())
12041 int bytes = send_g_packet ();
12043 for (const remote_g_packet_guess &guess : data->guesses)
12044 if (guess.bytes == bytes)
12045 return guess.tdesc;
12047 /* We discard the g packet. A minor optimization would be to
12048 hold on to it, and fill the register cache once we have selected
12049 an architecture, but it's too tricky to do safely. */
12052 return beneath ()->read_description ();
12055 /* Remote file transfer support. This is host-initiated I/O, not
12056 target-initiated; for target-initiated, see remote-fileio.c. */
12058 /* If *LEFT is at least the length of STRING, copy STRING to
12059 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12060 decrease *LEFT. Otherwise raise an error. */
12062 static void
12063 remote_buffer_add_string (char **buffer, int *left, const char *string)
12065 int len = strlen (string);
12067 if (len > *left)
12068 error (_("Packet too long for target."));
12070 memcpy (*buffer, string, len);
12071 *buffer += len;
12072 *left -= len;
12074 /* NUL-terminate the buffer as a convenience, if there is
12075 room. */
12076 if (*left)
12077 **buffer = '\0';
12080 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
12081 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12082 decrease *LEFT. Otherwise raise an error. */
12084 static void
12085 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
12086 int len)
12088 if (2 * len > *left)
12089 error (_("Packet too long for target."));
12091 bin2hex (bytes, *buffer, len);
12092 *buffer += 2 * len;
12093 *left -= 2 * len;
12095 /* NUL-terminate the buffer as a convenience, if there is
12096 room. */
12097 if (*left)
12098 **buffer = '\0';
12101 /* If *LEFT is large enough, convert VALUE to hex and add it to
12102 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12103 decrease *LEFT. Otherwise raise an error. */
12105 static void
12106 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
12108 int len = hexnumlen (value);
12110 if (len > *left)
12111 error (_("Packet too long for target."));
12113 hexnumstr (*buffer, value);
12114 *buffer += len;
12115 *left -= len;
12117 /* NUL-terminate the buffer as a convenience, if there is
12118 room. */
12119 if (*left)
12120 **buffer = '\0';
12123 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
12124 value, *REMOTE_ERRNO to the remote error number or FILEIO_SUCCESS if none
12125 was included, and *ATTACHMENT to point to the start of the annex
12126 if any. The length of the packet isn't needed here; there may
12127 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
12129 Return 0 if the packet could be parsed, -1 if it could not. If
12130 -1 is returned, the other variables may not be initialized. */
12132 static int
12133 remote_hostio_parse_result (const char *buffer, int *retcode,
12134 fileio_error *remote_errno, const char **attachment)
12136 char *p, *p2;
12138 *remote_errno = FILEIO_SUCCESS;
12139 *attachment = NULL;
12141 if (buffer[0] != 'F')
12142 return -1;
12144 errno = 0;
12145 *retcode = strtol (&buffer[1], &p, 16);
12146 if (errno != 0 || p == &buffer[1])
12147 return -1;
12149 /* Check for ",errno". */
12150 if (*p == ',')
12152 errno = 0;
12153 *remote_errno = (fileio_error) strtol (p + 1, &p2, 16);
12154 if (errno != 0 || p + 1 == p2)
12155 return -1;
12156 p = p2;
12159 /* Check for ";attachment". If there is no attachment, the
12160 packet should end here. */
12161 if (*p == ';')
12163 *attachment = p + 1;
12164 return 0;
12166 else if (*p == '\0')
12167 return 0;
12168 else
12169 return -1;
12172 /* Send a prepared I/O packet to the target and read its response.
12173 The prepared packet is in the global RS->BUF before this function
12174 is called, and the answer is there when we return.
12176 COMMAND_BYTES is the length of the request to send, which may include
12177 binary data. WHICH_PACKET is the packet configuration to check
12178 before attempting a packet. If an error occurs, *REMOTE_ERRNO
12179 is set to the error number and -1 is returned. Otherwise the value
12180 returned by the function is returned.
12182 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
12183 attachment is expected; an error will be reported if there's a
12184 mismatch. If one is found, *ATTACHMENT will be set to point into
12185 the packet buffer and *ATTACHMENT_LEN will be set to the
12186 attachment's length. */
12189 remote_target::remote_hostio_send_command (int command_bytes, int which_packet,
12190 fileio_error *remote_errno, const char **attachment,
12191 int *attachment_len)
12193 struct remote_state *rs = get_remote_state ();
12194 int ret, bytes_read;
12195 const char *attachment_tmp;
12197 if (packet_support (which_packet) == PACKET_DISABLE)
12199 *remote_errno = FILEIO_ENOSYS;
12200 return -1;
12203 putpkt_binary (rs->buf.data (), command_bytes);
12204 bytes_read = getpkt_sane (&rs->buf, 0);
12206 /* If it timed out, something is wrong. Don't try to parse the
12207 buffer. */
12208 if (bytes_read < 0)
12210 *remote_errno = FILEIO_EINVAL;
12211 return -1;
12214 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
12216 case PACKET_ERROR:
12217 *remote_errno = FILEIO_EINVAL;
12218 return -1;
12219 case PACKET_UNKNOWN:
12220 *remote_errno = FILEIO_ENOSYS;
12221 return -1;
12222 case PACKET_OK:
12223 break;
12226 if (remote_hostio_parse_result (rs->buf.data (), &ret, remote_errno,
12227 &attachment_tmp))
12229 *remote_errno = FILEIO_EINVAL;
12230 return -1;
12233 /* Make sure we saw an attachment if and only if we expected one. */
12234 if ((attachment_tmp == NULL && attachment != NULL)
12235 || (attachment_tmp != NULL && attachment == NULL))
12237 *remote_errno = FILEIO_EINVAL;
12238 return -1;
12241 /* If an attachment was found, it must point into the packet buffer;
12242 work out how many bytes there were. */
12243 if (attachment_tmp != NULL)
12245 *attachment = attachment_tmp;
12246 *attachment_len = bytes_read - (*attachment - rs->buf.data ());
12249 return ret;
12252 /* See declaration.h. */
12254 void
12255 readahead_cache::invalidate ()
12257 this->fd = -1;
12260 /* See declaration.h. */
12262 void
12263 readahead_cache::invalidate_fd (int fd)
12265 if (this->fd == fd)
12266 this->fd = -1;
12269 /* Set the filesystem remote_hostio functions that take FILENAME
12270 arguments will use. Return 0 on success, or -1 if an error
12271 occurs (and set *REMOTE_ERRNO). */
12274 remote_target::remote_hostio_set_filesystem (struct inferior *inf,
12275 fileio_error *remote_errno)
12277 struct remote_state *rs = get_remote_state ();
12278 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
12279 char *p = rs->buf.data ();
12280 int left = get_remote_packet_size () - 1;
12281 char arg[9];
12282 int ret;
12284 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
12285 return 0;
12287 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
12288 return 0;
12290 remote_buffer_add_string (&p, &left, "vFile:setfs:");
12292 xsnprintf (arg, sizeof (arg), "%x", required_pid);
12293 remote_buffer_add_string (&p, &left, arg);
12295 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_setfs,
12296 remote_errno, NULL, NULL);
12298 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
12299 return 0;
12301 if (ret == 0)
12302 rs->fs_pid = required_pid;
12304 return ret;
12307 /* Implementation of to_fileio_open. */
12310 remote_target::remote_hostio_open (inferior *inf, const char *filename,
12311 int flags, int mode, int warn_if_slow,
12312 fileio_error *remote_errno)
12314 struct remote_state *rs = get_remote_state ();
12315 char *p = rs->buf.data ();
12316 int left = get_remote_packet_size () - 1;
12318 if (warn_if_slow)
12320 static int warning_issued = 0;
12322 gdb_printf (_("Reading %s from remote target...\n"),
12323 filename);
12325 if (!warning_issued)
12327 warning (_("File transfers from remote targets can be slow."
12328 " Use \"set sysroot\" to access files locally"
12329 " instead."));
12330 warning_issued = 1;
12334 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12335 return -1;
12337 remote_buffer_add_string (&p, &left, "vFile:open:");
12339 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12340 strlen (filename));
12341 remote_buffer_add_string (&p, &left, ",");
12343 remote_buffer_add_int (&p, &left, flags);
12344 remote_buffer_add_string (&p, &left, ",");
12346 remote_buffer_add_int (&p, &left, mode);
12348 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_open,
12349 remote_errno, NULL, NULL);
12353 remote_target::fileio_open (struct inferior *inf, const char *filename,
12354 int flags, int mode, int warn_if_slow,
12355 fileio_error *remote_errno)
12357 return remote_hostio_open (inf, filename, flags, mode, warn_if_slow,
12358 remote_errno);
12361 /* Implementation of to_fileio_pwrite. */
12364 remote_target::remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
12365 ULONGEST offset, fileio_error *remote_errno)
12367 struct remote_state *rs = get_remote_state ();
12368 char *p = rs->buf.data ();
12369 int left = get_remote_packet_size ();
12370 int out_len;
12372 rs->readahead_cache.invalidate_fd (fd);
12374 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
12376 remote_buffer_add_int (&p, &left, fd);
12377 remote_buffer_add_string (&p, &left, ",");
12379 remote_buffer_add_int (&p, &left, offset);
12380 remote_buffer_add_string (&p, &left, ",");
12382 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
12383 (get_remote_packet_size ()
12384 - (p - rs->buf.data ())));
12386 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pwrite,
12387 remote_errno, NULL, NULL);
12391 remote_target::fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
12392 ULONGEST offset, fileio_error *remote_errno)
12394 return remote_hostio_pwrite (fd, write_buf, len, offset, remote_errno);
12397 /* Helper for the implementation of to_fileio_pread. Read the file
12398 from the remote side with vFile:pread. */
12401 remote_target::remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
12402 ULONGEST offset, fileio_error *remote_errno)
12404 struct remote_state *rs = get_remote_state ();
12405 char *p = rs->buf.data ();
12406 const char *attachment;
12407 int left = get_remote_packet_size ();
12408 int ret, attachment_len;
12409 int read_len;
12411 remote_buffer_add_string (&p, &left, "vFile:pread:");
12413 remote_buffer_add_int (&p, &left, fd);
12414 remote_buffer_add_string (&p, &left, ",");
12416 remote_buffer_add_int (&p, &left, len);
12417 remote_buffer_add_string (&p, &left, ",");
12419 remote_buffer_add_int (&p, &left, offset);
12421 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pread,
12422 remote_errno, &attachment,
12423 &attachment_len);
12425 if (ret < 0)
12426 return ret;
12428 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12429 read_buf, len);
12430 if (read_len != ret)
12431 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
12433 return ret;
12436 /* See declaration.h. */
12439 readahead_cache::pread (int fd, gdb_byte *read_buf, size_t len,
12440 ULONGEST offset)
12442 if (this->fd == fd
12443 && this->offset <= offset
12444 && offset < this->offset + this->bufsize)
12446 ULONGEST max = this->offset + this->bufsize;
12448 if (offset + len > max)
12449 len = max - offset;
12451 memcpy (read_buf, this->buf + offset - this->offset, len);
12452 return len;
12455 return 0;
12458 /* Implementation of to_fileio_pread. */
12461 remote_target::remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
12462 ULONGEST offset, fileio_error *remote_errno)
12464 int ret;
12465 struct remote_state *rs = get_remote_state ();
12466 readahead_cache *cache = &rs->readahead_cache;
12468 ret = cache->pread (fd, read_buf, len, offset);
12469 if (ret > 0)
12471 cache->hit_count++;
12473 remote_debug_printf ("readahead cache hit %s",
12474 pulongest (cache->hit_count));
12475 return ret;
12478 cache->miss_count++;
12480 remote_debug_printf ("readahead cache miss %s",
12481 pulongest (cache->miss_count));
12483 cache->fd = fd;
12484 cache->offset = offset;
12485 cache->bufsize = get_remote_packet_size ();
12486 cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
12488 ret = remote_hostio_pread_vFile (cache->fd, cache->buf, cache->bufsize,
12489 cache->offset, remote_errno);
12490 if (ret <= 0)
12492 cache->invalidate_fd (fd);
12493 return ret;
12496 cache->bufsize = ret;
12497 return cache->pread (fd, read_buf, len, offset);
12501 remote_target::fileio_pread (int fd, gdb_byte *read_buf, int len,
12502 ULONGEST offset, fileio_error *remote_errno)
12504 return remote_hostio_pread (fd, read_buf, len, offset, remote_errno);
12507 /* Implementation of to_fileio_close. */
12510 remote_target::remote_hostio_close (int fd, fileio_error *remote_errno)
12512 struct remote_state *rs = get_remote_state ();
12513 char *p = rs->buf.data ();
12514 int left = get_remote_packet_size () - 1;
12516 rs->readahead_cache.invalidate_fd (fd);
12518 remote_buffer_add_string (&p, &left, "vFile:close:");
12520 remote_buffer_add_int (&p, &left, fd);
12522 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_close,
12523 remote_errno, NULL, NULL);
12527 remote_target::fileio_close (int fd, fileio_error *remote_errno)
12529 return remote_hostio_close (fd, remote_errno);
12532 /* Implementation of to_fileio_unlink. */
12535 remote_target::remote_hostio_unlink (inferior *inf, const char *filename,
12536 fileio_error *remote_errno)
12538 struct remote_state *rs = get_remote_state ();
12539 char *p = rs->buf.data ();
12540 int left = get_remote_packet_size () - 1;
12542 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12543 return -1;
12545 remote_buffer_add_string (&p, &left, "vFile:unlink:");
12547 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12548 strlen (filename));
12550 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_unlink,
12551 remote_errno, NULL, NULL);
12555 remote_target::fileio_unlink (struct inferior *inf, const char *filename,
12556 fileio_error *remote_errno)
12558 return remote_hostio_unlink (inf, filename, remote_errno);
12561 /* Implementation of to_fileio_readlink. */
12563 gdb::optional<std::string>
12564 remote_target::fileio_readlink (struct inferior *inf, const char *filename,
12565 fileio_error *remote_errno)
12567 struct remote_state *rs = get_remote_state ();
12568 char *p = rs->buf.data ();
12569 const char *attachment;
12570 int left = get_remote_packet_size ();
12571 int len, attachment_len;
12572 int read_len;
12574 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12575 return {};
12577 remote_buffer_add_string (&p, &left, "vFile:readlink:");
12579 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12580 strlen (filename));
12582 len = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_readlink,
12583 remote_errno, &attachment,
12584 &attachment_len);
12586 if (len < 0)
12587 return {};
12589 std::string ret (len, '\0');
12591 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12592 (gdb_byte *) &ret[0], len);
12593 if (read_len != len)
12594 error (_("Readlink returned %d, but %d bytes."), len, read_len);
12596 return ret;
12599 /* Implementation of to_fileio_fstat. */
12602 remote_target::fileio_fstat (int fd, struct stat *st, fileio_error *remote_errno)
12604 struct remote_state *rs = get_remote_state ();
12605 char *p = rs->buf.data ();
12606 int left = get_remote_packet_size ();
12607 int attachment_len, ret;
12608 const char *attachment;
12609 struct fio_stat fst;
12610 int read_len;
12612 remote_buffer_add_string (&p, &left, "vFile:fstat:");
12614 remote_buffer_add_int (&p, &left, fd);
12616 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_fstat,
12617 remote_errno, &attachment,
12618 &attachment_len);
12619 if (ret < 0)
12621 if (*remote_errno != FILEIO_ENOSYS)
12622 return ret;
12624 /* Strictly we should return -1, ENOSYS here, but when
12625 "set sysroot remote:" was implemented in August 2008
12626 BFD's need for a stat function was sidestepped with
12627 this hack. This was not remedied until March 2015
12628 so we retain the previous behavior to avoid breaking
12629 compatibility.
12631 Note that the memset is a March 2015 addition; older
12632 GDBs set st_size *and nothing else* so the structure
12633 would have garbage in all other fields. This might
12634 break something but retaining the previous behavior
12635 here would be just too wrong. */
12637 memset (st, 0, sizeof (struct stat));
12638 st->st_size = INT_MAX;
12639 return 0;
12642 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12643 (gdb_byte *) &fst, sizeof (fst));
12645 if (read_len != ret)
12646 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
12648 if (read_len != sizeof (fst))
12649 error (_("vFile:fstat returned %d bytes, but expecting %d."),
12650 read_len, (int) sizeof (fst));
12652 remote_fileio_to_host_stat (&fst, st);
12654 return 0;
12657 /* Implementation of to_filesystem_is_local. */
12659 bool
12660 remote_target::filesystem_is_local ()
12662 /* Valgrind GDB presents itself as a remote target but works
12663 on the local filesystem: it does not implement remote get
12664 and users are not expected to set a sysroot. To handle
12665 this case we treat the remote filesystem as local if the
12666 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
12667 does not support vFile:open. */
12668 if (gdb_sysroot == TARGET_SYSROOT_PREFIX)
12670 enum packet_support ps = packet_support (PACKET_vFile_open);
12672 if (ps == PACKET_SUPPORT_UNKNOWN)
12674 int fd;
12675 fileio_error remote_errno;
12677 /* Try opening a file to probe support. The supplied
12678 filename is irrelevant, we only care about whether
12679 the stub recognizes the packet or not. */
12680 fd = remote_hostio_open (NULL, "just probing",
12681 FILEIO_O_RDONLY, 0700, 0,
12682 &remote_errno);
12684 if (fd >= 0)
12685 remote_hostio_close (fd, &remote_errno);
12687 ps = packet_support (PACKET_vFile_open);
12690 if (ps == PACKET_DISABLE)
12692 static int warning_issued = 0;
12694 if (!warning_issued)
12696 warning (_("remote target does not support file"
12697 " transfer, attempting to access files"
12698 " from local filesystem."));
12699 warning_issued = 1;
12702 return true;
12706 return false;
12709 static char *
12710 remote_hostio_error (fileio_error errnum)
12712 int host_error = fileio_error_to_host (errnum);
12714 if (host_error == -1)
12715 error (_("Unknown remote I/O error %d"), errnum);
12716 else
12717 error (_("Remote I/O error: %s"), safe_strerror (host_error));
12720 /* A RAII wrapper around a remote file descriptor. */
12722 class scoped_remote_fd
12724 public:
12725 scoped_remote_fd (remote_target *remote, int fd)
12726 : m_remote (remote), m_fd (fd)
12730 ~scoped_remote_fd ()
12732 if (m_fd != -1)
12736 fileio_error remote_errno;
12737 m_remote->remote_hostio_close (m_fd, &remote_errno);
12739 catch (...)
12741 /* Swallow exception before it escapes the dtor. If
12742 something goes wrong, likely the connection is gone,
12743 and there's nothing else that can be done. */
12748 DISABLE_COPY_AND_ASSIGN (scoped_remote_fd);
12750 /* Release ownership of the file descriptor, and return it. */
12751 ATTRIBUTE_UNUSED_RESULT int release () noexcept
12753 int fd = m_fd;
12754 m_fd = -1;
12755 return fd;
12758 /* Return the owned file descriptor. */
12759 int get () const noexcept
12761 return m_fd;
12764 private:
12765 /* The remote target. */
12766 remote_target *m_remote;
12768 /* The owned remote I/O file descriptor. */
12769 int m_fd;
12772 void
12773 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
12775 remote_target *remote = get_current_remote_target ();
12777 if (remote == nullptr)
12778 error (_("command can only be used with remote target"));
12780 remote->remote_file_put (local_file, remote_file, from_tty);
12783 void
12784 remote_target::remote_file_put (const char *local_file, const char *remote_file,
12785 int from_tty)
12787 int retcode, bytes, io_size;
12788 fileio_error remote_errno;
12789 int bytes_in_buffer;
12790 int saw_eof;
12791 ULONGEST offset;
12793 gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
12794 if (file == NULL)
12795 perror_with_name (local_file);
12797 scoped_remote_fd fd
12798 (this, remote_hostio_open (NULL,
12799 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
12800 | FILEIO_O_TRUNC),
12801 0700, 0, &remote_errno));
12802 if (fd.get () == -1)
12803 remote_hostio_error (remote_errno);
12805 /* Send up to this many bytes at once. They won't all fit in the
12806 remote packet limit, so we'll transfer slightly fewer. */
12807 io_size = get_remote_packet_size ();
12808 gdb::byte_vector buffer (io_size);
12810 bytes_in_buffer = 0;
12811 saw_eof = 0;
12812 offset = 0;
12813 while (bytes_in_buffer || !saw_eof)
12815 if (!saw_eof)
12817 bytes = fread (buffer.data () + bytes_in_buffer, 1,
12818 io_size - bytes_in_buffer,
12819 file.get ());
12820 if (bytes == 0)
12822 if (ferror (file.get ()))
12823 error (_("Error reading %s."), local_file);
12824 else
12826 /* EOF. Unless there is something still in the
12827 buffer from the last iteration, we are done. */
12828 saw_eof = 1;
12829 if (bytes_in_buffer == 0)
12830 break;
12834 else
12835 bytes = 0;
12837 bytes += bytes_in_buffer;
12838 bytes_in_buffer = 0;
12840 retcode = remote_hostio_pwrite (fd.get (), buffer.data (), bytes,
12841 offset, &remote_errno);
12843 if (retcode < 0)
12844 remote_hostio_error (remote_errno);
12845 else if (retcode == 0)
12846 error (_("Remote write of %d bytes returned 0!"), bytes);
12847 else if (retcode < bytes)
12849 /* Short write. Save the rest of the read data for the next
12850 write. */
12851 bytes_in_buffer = bytes - retcode;
12852 memmove (buffer.data (), buffer.data () + retcode, bytes_in_buffer);
12855 offset += retcode;
12858 if (remote_hostio_close (fd.release (), &remote_errno))
12859 remote_hostio_error (remote_errno);
12861 if (from_tty)
12862 gdb_printf (_("Successfully sent file \"%s\".\n"), local_file);
12865 void
12866 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
12868 remote_target *remote = get_current_remote_target ();
12870 if (remote == nullptr)
12871 error (_("command can only be used with remote target"));
12873 remote->remote_file_get (remote_file, local_file, from_tty);
12876 void
12877 remote_target::remote_file_get (const char *remote_file, const char *local_file,
12878 int from_tty)
12880 fileio_error remote_errno;
12881 int bytes, io_size;
12882 ULONGEST offset;
12884 scoped_remote_fd fd
12885 (this, remote_hostio_open (NULL,
12886 remote_file, FILEIO_O_RDONLY, 0, 0,
12887 &remote_errno));
12888 if (fd.get () == -1)
12889 remote_hostio_error (remote_errno);
12891 gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
12892 if (file == NULL)
12893 perror_with_name (local_file);
12895 /* Send up to this many bytes at once. They won't all fit in the
12896 remote packet limit, so we'll transfer slightly fewer. */
12897 io_size = get_remote_packet_size ();
12898 gdb::byte_vector buffer (io_size);
12900 offset = 0;
12901 while (1)
12903 bytes = remote_hostio_pread (fd.get (), buffer.data (), io_size, offset,
12904 &remote_errno);
12905 if (bytes == 0)
12906 /* Success, but no bytes, means end-of-file. */
12907 break;
12908 if (bytes == -1)
12909 remote_hostio_error (remote_errno);
12911 offset += bytes;
12913 bytes = fwrite (buffer.data (), 1, bytes, file.get ());
12914 if (bytes == 0)
12915 perror_with_name (local_file);
12918 if (remote_hostio_close (fd.release (), &remote_errno))
12919 remote_hostio_error (remote_errno);
12921 if (from_tty)
12922 gdb_printf (_("Successfully fetched file \"%s\".\n"), remote_file);
12925 void
12926 remote_file_delete (const char *remote_file, int from_tty)
12928 remote_target *remote = get_current_remote_target ();
12930 if (remote == nullptr)
12931 error (_("command can only be used with remote target"));
12933 remote->remote_file_delete (remote_file, from_tty);
12936 void
12937 remote_target::remote_file_delete (const char *remote_file, int from_tty)
12939 int retcode;
12940 fileio_error remote_errno;
12942 retcode = remote_hostio_unlink (NULL, remote_file, &remote_errno);
12943 if (retcode == -1)
12944 remote_hostio_error (remote_errno);
12946 if (from_tty)
12947 gdb_printf (_("Successfully deleted file \"%s\".\n"), remote_file);
12950 static void
12951 remote_put_command (const char *args, int from_tty)
12953 if (args == NULL)
12954 error_no_arg (_("file to put"));
12956 gdb_argv argv (args);
12957 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12958 error (_("Invalid parameters to remote put"));
12960 remote_file_put (argv[0], argv[1], from_tty);
12963 static void
12964 remote_get_command (const char *args, int from_tty)
12966 if (args == NULL)
12967 error_no_arg (_("file to get"));
12969 gdb_argv argv (args);
12970 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12971 error (_("Invalid parameters to remote get"));
12973 remote_file_get (argv[0], argv[1], from_tty);
12976 static void
12977 remote_delete_command (const char *args, int from_tty)
12979 if (args == NULL)
12980 error_no_arg (_("file to delete"));
12982 gdb_argv argv (args);
12983 if (argv[0] == NULL || argv[1] != NULL)
12984 error (_("Invalid parameters to remote delete"));
12986 remote_file_delete (argv[0], from_tty);
12989 bool
12990 remote_target::can_execute_reverse ()
12992 if (packet_support (PACKET_bs) == PACKET_ENABLE
12993 || packet_support (PACKET_bc) == PACKET_ENABLE)
12994 return true;
12995 else
12996 return false;
12999 bool
13000 remote_target::supports_non_stop ()
13002 return true;
13005 bool
13006 remote_target::supports_disable_randomization ()
13008 /* Only supported in extended mode. */
13009 return false;
13012 bool
13013 remote_target::supports_multi_process ()
13015 struct remote_state *rs = get_remote_state ();
13017 return remote_multi_process_p (rs);
13020 static int
13021 remote_supports_cond_tracepoints ()
13023 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
13026 bool
13027 remote_target::supports_evaluation_of_breakpoint_conditions ()
13029 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
13032 static int
13033 remote_supports_fast_tracepoints ()
13035 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
13038 static int
13039 remote_supports_static_tracepoints ()
13041 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
13044 static int
13045 remote_supports_install_in_trace ()
13047 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
13050 bool
13051 remote_target::supports_enable_disable_tracepoint ()
13053 return (packet_support (PACKET_EnableDisableTracepoints_feature)
13054 == PACKET_ENABLE);
13057 bool
13058 remote_target::supports_string_tracing ()
13060 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
13063 bool
13064 remote_target::can_run_breakpoint_commands ()
13066 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
13069 void
13070 remote_target::trace_init ()
13072 struct remote_state *rs = get_remote_state ();
13074 putpkt ("QTinit");
13075 remote_get_noisy_reply ();
13076 if (strcmp (rs->buf.data (), "OK") != 0)
13077 error (_("Target does not support this command."));
13080 /* Recursive routine to walk through command list including loops, and
13081 download packets for each command. */
13083 void
13084 remote_target::remote_download_command_source (int num, ULONGEST addr,
13085 struct command_line *cmds)
13087 struct remote_state *rs = get_remote_state ();
13088 struct command_line *cmd;
13090 for (cmd = cmds; cmd; cmd = cmd->next)
13092 QUIT; /* Allow user to bail out with ^C. */
13093 strcpy (rs->buf.data (), "QTDPsrc:");
13094 encode_source_string (num, addr, "cmd", cmd->line,
13095 rs->buf.data () + strlen (rs->buf.data ()),
13096 rs->buf.size () - strlen (rs->buf.data ()));
13097 putpkt (rs->buf);
13098 remote_get_noisy_reply ();
13099 if (strcmp (rs->buf.data (), "OK"))
13100 warning (_("Target does not support source download."));
13102 if (cmd->control_type == while_control
13103 || cmd->control_type == while_stepping_control)
13105 remote_download_command_source (num, addr, cmd->body_list_0.get ());
13107 QUIT; /* Allow user to bail out with ^C. */
13108 strcpy (rs->buf.data (), "QTDPsrc:");
13109 encode_source_string (num, addr, "cmd", "end",
13110 rs->buf.data () + strlen (rs->buf.data ()),
13111 rs->buf.size () - strlen (rs->buf.data ()));
13112 putpkt (rs->buf);
13113 remote_get_noisy_reply ();
13114 if (strcmp (rs->buf.data (), "OK"))
13115 warning (_("Target does not support source download."));
13120 void
13121 remote_target::download_tracepoint (struct bp_location *loc)
13123 CORE_ADDR tpaddr;
13124 char addrbuf[40];
13125 std::vector<std::string> tdp_actions;
13126 std::vector<std::string> stepping_actions;
13127 char *pkt;
13128 struct breakpoint *b = loc->owner;
13129 struct tracepoint *t = (struct tracepoint *) b;
13130 struct remote_state *rs = get_remote_state ();
13131 int ret;
13132 const char *err_msg = _("Tracepoint packet too large for target.");
13133 size_t size_left;
13135 /* We use a buffer other than rs->buf because we'll build strings
13136 across multiple statements, and other statements in between could
13137 modify rs->buf. */
13138 gdb::char_vector buf (get_remote_packet_size ());
13140 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
13142 tpaddr = loc->address;
13143 strcpy (addrbuf, phex (tpaddr, sizeof (CORE_ADDR)));
13144 ret = snprintf (buf.data (), buf.size (), "QTDP:%x:%s:%c:%lx:%x",
13145 b->number, addrbuf, /* address */
13146 (b->enable_state == bp_enabled ? 'E' : 'D'),
13147 t->step_count, t->pass_count);
13149 if (ret < 0 || ret >= buf.size ())
13150 error ("%s", err_msg);
13152 /* Fast tracepoints are mostly handled by the target, but we can
13153 tell the target how big of an instruction block should be moved
13154 around. */
13155 if (b->type == bp_fast_tracepoint)
13157 /* Only test for support at download time; we may not know
13158 target capabilities at definition time. */
13159 if (remote_supports_fast_tracepoints ())
13161 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
13162 NULL))
13164 size_left = buf.size () - strlen (buf.data ());
13165 ret = snprintf (buf.data () + strlen (buf.data ()),
13166 size_left, ":F%x",
13167 gdb_insn_length (loc->gdbarch, tpaddr));
13169 if (ret < 0 || ret >= size_left)
13170 error ("%s", err_msg);
13172 else
13173 /* If it passed validation at definition but fails now,
13174 something is very wrong. */
13175 internal_error (_("Fast tracepoint not valid during download"));
13177 else
13178 /* Fast tracepoints are functionally identical to regular
13179 tracepoints, so don't take lack of support as a reason to
13180 give up on the trace run. */
13181 warning (_("Target does not support fast tracepoints, "
13182 "downloading %d as regular tracepoint"), b->number);
13184 else if (b->type == bp_static_tracepoint
13185 || b->type == bp_static_marker_tracepoint)
13187 /* Only test for support at download time; we may not know
13188 target capabilities at definition time. */
13189 if (remote_supports_static_tracepoints ())
13191 struct static_tracepoint_marker marker;
13193 if (target_static_tracepoint_marker_at (tpaddr, &marker))
13195 size_left = buf.size () - strlen (buf.data ());
13196 ret = snprintf (buf.data () + strlen (buf.data ()),
13197 size_left, ":S");
13199 if (ret < 0 || ret >= size_left)
13200 error ("%s", err_msg);
13202 else
13203 error (_("Static tracepoint not valid during download"));
13205 else
13206 /* Fast tracepoints are functionally identical to regular
13207 tracepoints, so don't take lack of support as a reason
13208 to give up on the trace run. */
13209 error (_("Target does not support static tracepoints"));
13211 /* If the tracepoint has a conditional, make it into an agent
13212 expression and append to the definition. */
13213 if (loc->cond)
13215 /* Only test support at download time, we may not know target
13216 capabilities at definition time. */
13217 if (remote_supports_cond_tracepoints ())
13219 agent_expr_up aexpr = gen_eval_for_expr (tpaddr,
13220 loc->cond.get ());
13222 size_left = buf.size () - strlen (buf.data ());
13224 ret = snprintf (buf.data () + strlen (buf.data ()),
13225 size_left, ":X%x,", aexpr->len);
13227 if (ret < 0 || ret >= size_left)
13228 error ("%s", err_msg);
13230 size_left = buf.size () - strlen (buf.data ());
13232 /* Two bytes to encode each aexpr byte, plus the terminating
13233 null byte. */
13234 if (aexpr->len * 2 + 1 > size_left)
13235 error ("%s", err_msg);
13237 pkt = buf.data () + strlen (buf.data ());
13239 for (int ndx = 0; ndx < aexpr->len; ++ndx)
13240 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
13241 *pkt = '\0';
13243 else
13244 warning (_("Target does not support conditional tracepoints, "
13245 "ignoring tp %d cond"), b->number);
13248 if (b->commands || !default_collect.empty ())
13250 size_left = buf.size () - strlen (buf.data ());
13252 ret = snprintf (buf.data () + strlen (buf.data ()),
13253 size_left, "-");
13255 if (ret < 0 || ret >= size_left)
13256 error ("%s", err_msg);
13259 putpkt (buf.data ());
13260 remote_get_noisy_reply ();
13261 if (strcmp (rs->buf.data (), "OK"))
13262 error (_("Target does not support tracepoints."));
13264 /* do_single_steps (t); */
13265 for (auto action_it = tdp_actions.begin ();
13266 action_it != tdp_actions.end (); action_it++)
13268 QUIT; /* Allow user to bail out with ^C. */
13270 bool has_more = ((action_it + 1) != tdp_actions.end ()
13271 || !stepping_actions.empty ());
13273 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%c",
13274 b->number, addrbuf, /* address */
13275 action_it->c_str (),
13276 has_more ? '-' : 0);
13278 if (ret < 0 || ret >= buf.size ())
13279 error ("%s", err_msg);
13281 putpkt (buf.data ());
13282 remote_get_noisy_reply ();
13283 if (strcmp (rs->buf.data (), "OK"))
13284 error (_("Error on target while setting tracepoints."));
13287 for (auto action_it = stepping_actions.begin ();
13288 action_it != stepping_actions.end (); action_it++)
13290 QUIT; /* Allow user to bail out with ^C. */
13292 bool is_first = action_it == stepping_actions.begin ();
13293 bool has_more = (action_it + 1) != stepping_actions.end ();
13295 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%s%s",
13296 b->number, addrbuf, /* address */
13297 is_first ? "S" : "",
13298 action_it->c_str (),
13299 has_more ? "-" : "");
13301 if (ret < 0 || ret >= buf.size ())
13302 error ("%s", err_msg);
13304 putpkt (buf.data ());
13305 remote_get_noisy_reply ();
13306 if (strcmp (rs->buf.data (), "OK"))
13307 error (_("Error on target while setting tracepoints."));
13310 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
13312 if (b->locspec != nullptr)
13314 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13316 if (ret < 0 || ret >= buf.size ())
13317 error ("%s", err_msg);
13319 const char *str = b->locspec->to_string ();
13320 encode_source_string (b->number, loc->address, "at", str,
13321 buf.data () + strlen (buf.data ()),
13322 buf.size () - strlen (buf.data ()));
13323 putpkt (buf.data ());
13324 remote_get_noisy_reply ();
13325 if (strcmp (rs->buf.data (), "OK"))
13326 warning (_("Target does not support source download."));
13328 if (b->cond_string)
13330 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13332 if (ret < 0 || ret >= buf.size ())
13333 error ("%s", err_msg);
13335 encode_source_string (b->number, loc->address,
13336 "cond", b->cond_string.get (),
13337 buf.data () + strlen (buf.data ()),
13338 buf.size () - strlen (buf.data ()));
13339 putpkt (buf.data ());
13340 remote_get_noisy_reply ();
13341 if (strcmp (rs->buf.data (), "OK"))
13342 warning (_("Target does not support source download."));
13344 remote_download_command_source (b->number, loc->address,
13345 breakpoint_commands (b));
13349 bool
13350 remote_target::can_download_tracepoint ()
13352 struct remote_state *rs = get_remote_state ();
13353 struct trace_status *ts;
13354 int status;
13356 /* Don't try to install tracepoints until we've relocated our
13357 symbols, and fetched and merged the target's tracepoint list with
13358 ours. */
13359 if (rs->starting_up)
13360 return false;
13362 ts = current_trace_status ();
13363 status = get_trace_status (ts);
13365 if (status == -1 || !ts->running_known || !ts->running)
13366 return false;
13368 /* If we are in a tracing experiment, but remote stub doesn't support
13369 installing tracepoint in trace, we have to return. */
13370 if (!remote_supports_install_in_trace ())
13371 return false;
13373 return true;
13377 void
13378 remote_target::download_trace_state_variable (const trace_state_variable &tsv)
13380 struct remote_state *rs = get_remote_state ();
13381 char *p;
13383 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDV:%x:%s:%x:",
13384 tsv.number, phex ((ULONGEST) tsv.initial_value, 8),
13385 tsv.builtin);
13386 p = rs->buf.data () + strlen (rs->buf.data ());
13387 if ((p - rs->buf.data ()) + tsv.name.length () * 2
13388 >= get_remote_packet_size ())
13389 error (_("Trace state variable name too long for tsv definition packet"));
13390 p += 2 * bin2hex ((gdb_byte *) (tsv.name.data ()), p, tsv.name.length ());
13391 *p++ = '\0';
13392 putpkt (rs->buf);
13393 remote_get_noisy_reply ();
13394 if (rs->buf[0] == '\0')
13395 error (_("Target does not support this command."));
13396 if (strcmp (rs->buf.data (), "OK") != 0)
13397 error (_("Error on target while downloading trace state variable."));
13400 void
13401 remote_target::enable_tracepoint (struct bp_location *location)
13403 struct remote_state *rs = get_remote_state ();
13405 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTEnable:%x:%s",
13406 location->owner->number,
13407 phex (location->address, sizeof (CORE_ADDR)));
13408 putpkt (rs->buf);
13409 remote_get_noisy_reply ();
13410 if (rs->buf[0] == '\0')
13411 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
13412 if (strcmp (rs->buf.data (), "OK") != 0)
13413 error (_("Error on target while enabling tracepoint."));
13416 void
13417 remote_target::disable_tracepoint (struct bp_location *location)
13419 struct remote_state *rs = get_remote_state ();
13421 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDisable:%x:%s",
13422 location->owner->number,
13423 phex (location->address, sizeof (CORE_ADDR)));
13424 putpkt (rs->buf);
13425 remote_get_noisy_reply ();
13426 if (rs->buf[0] == '\0')
13427 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
13428 if (strcmp (rs->buf.data (), "OK") != 0)
13429 error (_("Error on target while disabling tracepoint."));
13432 void
13433 remote_target::trace_set_readonly_regions ()
13435 asection *s;
13436 bfd_size_type size;
13437 bfd_vma vma;
13438 int anysecs = 0;
13439 int offset = 0;
13440 bfd *abfd = current_program_space->exec_bfd ();
13442 if (!abfd)
13443 return; /* No information to give. */
13445 struct remote_state *rs = get_remote_state ();
13447 strcpy (rs->buf.data (), "QTro");
13448 offset = strlen (rs->buf.data ());
13449 for (s = abfd->sections; s; s = s->next)
13451 char tmp1[40], tmp2[40];
13452 int sec_length;
13454 if ((s->flags & SEC_LOAD) == 0
13455 /* || (s->flags & SEC_CODE) == 0 */
13456 || (s->flags & SEC_READONLY) == 0)
13457 continue;
13459 anysecs = 1;
13460 vma = bfd_section_vma (s);
13461 size = bfd_section_size (s);
13462 bfd_sprintf_vma (abfd, tmp1, vma);
13463 bfd_sprintf_vma (abfd, tmp2, vma + size);
13464 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
13465 if (offset + sec_length + 1 > rs->buf.size ())
13467 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
13468 warning (_("\
13469 Too many sections for read-only sections definition packet."));
13470 break;
13472 xsnprintf (rs->buf.data () + offset, rs->buf.size () - offset, ":%s,%s",
13473 tmp1, tmp2);
13474 offset += sec_length;
13476 if (anysecs)
13478 putpkt (rs->buf);
13479 getpkt (&rs->buf, 0);
13483 void
13484 remote_target::trace_start ()
13486 struct remote_state *rs = get_remote_state ();
13488 putpkt ("QTStart");
13489 remote_get_noisy_reply ();
13490 if (rs->buf[0] == '\0')
13491 error (_("Target does not support this command."));
13492 if (strcmp (rs->buf.data (), "OK") != 0)
13493 error (_("Bogus reply from target: %s"), rs->buf.data ());
13497 remote_target::get_trace_status (struct trace_status *ts)
13499 /* Initialize it just to avoid a GCC false warning. */
13500 char *p = NULL;
13501 enum packet_result result;
13502 struct remote_state *rs = get_remote_state ();
13504 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
13505 return -1;
13507 /* FIXME we need to get register block size some other way. */
13508 trace_regblock_size
13509 = rs->get_remote_arch_state (target_gdbarch ())->sizeof_g_packet;
13511 putpkt ("qTStatus");
13515 p = remote_get_noisy_reply ();
13517 catch (const gdb_exception_error &ex)
13519 if (ex.error != TARGET_CLOSE_ERROR)
13521 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
13522 return -1;
13524 throw;
13527 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
13529 /* If the remote target doesn't do tracing, flag it. */
13530 if (result == PACKET_UNKNOWN)
13531 return -1;
13533 /* We're working with a live target. */
13534 ts->filename = NULL;
13536 if (*p++ != 'T')
13537 error (_("Bogus trace status reply from target: %s"), rs->buf.data ());
13539 /* Function 'parse_trace_status' sets default value of each field of
13540 'ts' at first, so we don't have to do it here. */
13541 parse_trace_status (p, ts);
13543 return ts->running;
13546 void
13547 remote_target::get_tracepoint_status (struct breakpoint *bp,
13548 struct uploaded_tp *utp)
13550 struct remote_state *rs = get_remote_state ();
13551 char *reply;
13552 struct tracepoint *tp = (struct tracepoint *) bp;
13553 size_t size = get_remote_packet_size ();
13555 if (tp)
13557 tp->hit_count = 0;
13558 tp->traceframe_usage = 0;
13559 for (bp_location *loc : tp->locations ())
13561 /* If the tracepoint was never downloaded, don't go asking for
13562 any status. */
13563 if (tp->number_on_target == 0)
13564 continue;
13565 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", tp->number_on_target,
13566 phex_nz (loc->address, 0));
13567 putpkt (rs->buf);
13568 reply = remote_get_noisy_reply ();
13569 if (reply && *reply)
13571 if (*reply == 'V')
13572 parse_tracepoint_status (reply + 1, bp, utp);
13576 else if (utp)
13578 utp->hit_count = 0;
13579 utp->traceframe_usage = 0;
13580 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", utp->number,
13581 phex_nz (utp->addr, 0));
13582 putpkt (rs->buf);
13583 reply = remote_get_noisy_reply ();
13584 if (reply && *reply)
13586 if (*reply == 'V')
13587 parse_tracepoint_status (reply + 1, bp, utp);
13592 void
13593 remote_target::trace_stop ()
13595 struct remote_state *rs = get_remote_state ();
13597 putpkt ("QTStop");
13598 remote_get_noisy_reply ();
13599 if (rs->buf[0] == '\0')
13600 error (_("Target does not support this command."));
13601 if (strcmp (rs->buf.data (), "OK") != 0)
13602 error (_("Bogus reply from target: %s"), rs->buf.data ());
13606 remote_target::trace_find (enum trace_find_type type, int num,
13607 CORE_ADDR addr1, CORE_ADDR addr2,
13608 int *tpp)
13610 struct remote_state *rs = get_remote_state ();
13611 char *endbuf = rs->buf.data () + get_remote_packet_size ();
13612 char *p, *reply;
13613 int target_frameno = -1, target_tracept = -1;
13615 /* Lookups other than by absolute frame number depend on the current
13616 trace selected, so make sure it is correct on the remote end
13617 first. */
13618 if (type != tfind_number)
13619 set_remote_traceframe ();
13621 p = rs->buf.data ();
13622 strcpy (p, "QTFrame:");
13623 p = strchr (p, '\0');
13624 switch (type)
13626 case tfind_number:
13627 xsnprintf (p, endbuf - p, "%x", num);
13628 break;
13629 case tfind_pc:
13630 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
13631 break;
13632 case tfind_tp:
13633 xsnprintf (p, endbuf - p, "tdp:%x", num);
13634 break;
13635 case tfind_range:
13636 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
13637 phex_nz (addr2, 0));
13638 break;
13639 case tfind_outside:
13640 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
13641 phex_nz (addr2, 0));
13642 break;
13643 default:
13644 error (_("Unknown trace find type %d"), type);
13647 putpkt (rs->buf);
13648 reply = remote_get_noisy_reply ();
13649 if (*reply == '\0')
13650 error (_("Target does not support this command."));
13652 while (reply && *reply)
13653 switch (*reply)
13655 case 'F':
13656 p = ++reply;
13657 target_frameno = (int) strtol (p, &reply, 16);
13658 if (reply == p)
13659 error (_("Unable to parse trace frame number"));
13660 /* Don't update our remote traceframe number cache on failure
13661 to select a remote traceframe. */
13662 if (target_frameno == -1)
13663 return -1;
13664 break;
13665 case 'T':
13666 p = ++reply;
13667 target_tracept = (int) strtol (p, &reply, 16);
13668 if (reply == p)
13669 error (_("Unable to parse tracepoint number"));
13670 break;
13671 case 'O': /* "OK"? */
13672 if (reply[1] == 'K' && reply[2] == '\0')
13673 reply += 2;
13674 else
13675 error (_("Bogus reply from target: %s"), reply);
13676 break;
13677 default:
13678 error (_("Bogus reply from target: %s"), reply);
13680 if (tpp)
13681 *tpp = target_tracept;
13683 rs->remote_traceframe_number = target_frameno;
13684 return target_frameno;
13687 bool
13688 remote_target::get_trace_state_variable_value (int tsvnum, LONGEST *val)
13690 struct remote_state *rs = get_remote_state ();
13691 char *reply;
13692 ULONGEST uval;
13694 set_remote_traceframe ();
13696 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTV:%x", tsvnum);
13697 putpkt (rs->buf);
13698 reply = remote_get_noisy_reply ();
13699 if (reply && *reply)
13701 if (*reply == 'V')
13703 unpack_varlen_hex (reply + 1, &uval);
13704 *val = (LONGEST) uval;
13705 return true;
13708 return false;
13712 remote_target::save_trace_data (const char *filename)
13714 struct remote_state *rs = get_remote_state ();
13715 char *p, *reply;
13717 p = rs->buf.data ();
13718 strcpy (p, "QTSave:");
13719 p += strlen (p);
13720 if ((p - rs->buf.data ()) + strlen (filename) * 2
13721 >= get_remote_packet_size ())
13722 error (_("Remote file name too long for trace save packet"));
13723 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
13724 *p++ = '\0';
13725 putpkt (rs->buf);
13726 reply = remote_get_noisy_reply ();
13727 if (*reply == '\0')
13728 error (_("Target does not support this command."));
13729 if (strcmp (reply, "OK") != 0)
13730 error (_("Bogus reply from target: %s"), reply);
13731 return 0;
13734 /* This is basically a memory transfer, but needs to be its own packet
13735 because we don't know how the target actually organizes its trace
13736 memory, plus we want to be able to ask for as much as possible, but
13737 not be unhappy if we don't get as much as we ask for. */
13739 LONGEST
13740 remote_target::get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
13742 struct remote_state *rs = get_remote_state ();
13743 char *reply;
13744 char *p;
13745 int rslt;
13747 p = rs->buf.data ();
13748 strcpy (p, "qTBuffer:");
13749 p += strlen (p);
13750 p += hexnumstr (p, offset);
13751 *p++ = ',';
13752 p += hexnumstr (p, len);
13753 *p++ = '\0';
13755 putpkt (rs->buf);
13756 reply = remote_get_noisy_reply ();
13757 if (reply && *reply)
13759 /* 'l' by itself means we're at the end of the buffer and
13760 there is nothing more to get. */
13761 if (*reply == 'l')
13762 return 0;
13764 /* Convert the reply into binary. Limit the number of bytes to
13765 convert according to our passed-in buffer size, rather than
13766 what was returned in the packet; if the target is
13767 unexpectedly generous and gives us a bigger reply than we
13768 asked for, we don't want to crash. */
13769 rslt = hex2bin (reply, buf, len);
13770 return rslt;
13773 /* Something went wrong, flag as an error. */
13774 return -1;
13777 void
13778 remote_target::set_disconnected_tracing (int val)
13780 struct remote_state *rs = get_remote_state ();
13782 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
13784 char *reply;
13786 xsnprintf (rs->buf.data (), get_remote_packet_size (),
13787 "QTDisconnected:%x", val);
13788 putpkt (rs->buf);
13789 reply = remote_get_noisy_reply ();
13790 if (*reply == '\0')
13791 error (_("Target does not support this command."));
13792 if (strcmp (reply, "OK") != 0)
13793 error (_("Bogus reply from target: %s"), reply);
13795 else if (val)
13796 warning (_("Target does not support disconnected tracing."));
13800 remote_target::core_of_thread (ptid_t ptid)
13802 thread_info *info = find_thread_ptid (this, ptid);
13804 if (info != NULL && info->priv != NULL)
13805 return get_remote_thread_info (info)->core;
13807 return -1;
13810 void
13811 remote_target::set_circular_trace_buffer (int val)
13813 struct remote_state *rs = get_remote_state ();
13814 char *reply;
13816 xsnprintf (rs->buf.data (), get_remote_packet_size (),
13817 "QTBuffer:circular:%x", val);
13818 putpkt (rs->buf);
13819 reply = remote_get_noisy_reply ();
13820 if (*reply == '\0')
13821 error (_("Target does not support this command."));
13822 if (strcmp (reply, "OK") != 0)
13823 error (_("Bogus reply from target: %s"), reply);
13826 traceframe_info_up
13827 remote_target::traceframe_info ()
13829 gdb::optional<gdb::char_vector> text
13830 = target_read_stralloc (current_inferior ()->top_target (),
13831 TARGET_OBJECT_TRACEFRAME_INFO,
13832 NULL);
13833 if (text)
13834 return parse_traceframe_info (text->data ());
13836 return NULL;
13839 /* Handle the qTMinFTPILen packet. Returns the minimum length of
13840 instruction on which a fast tracepoint may be placed. Returns -1
13841 if the packet is not supported, and 0 if the minimum instruction
13842 length is unknown. */
13845 remote_target::get_min_fast_tracepoint_insn_len ()
13847 struct remote_state *rs = get_remote_state ();
13848 char *reply;
13850 /* If we're not debugging a process yet, the IPA can't be
13851 loaded. */
13852 if (!target_has_execution ())
13853 return 0;
13855 /* Make sure the remote is pointing at the right process. */
13856 set_general_process ();
13858 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTMinFTPILen");
13859 putpkt (rs->buf);
13860 reply = remote_get_noisy_reply ();
13861 if (*reply == '\0')
13862 return -1;
13863 else
13865 ULONGEST min_insn_len;
13867 unpack_varlen_hex (reply, &min_insn_len);
13869 return (int) min_insn_len;
13873 void
13874 remote_target::set_trace_buffer_size (LONGEST val)
13876 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
13878 struct remote_state *rs = get_remote_state ();
13879 char *buf = rs->buf.data ();
13880 char *endbuf = buf + get_remote_packet_size ();
13881 enum packet_result result;
13883 gdb_assert (val >= 0 || val == -1);
13884 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
13885 /* Send -1 as literal "-1" to avoid host size dependency. */
13886 if (val < 0)
13888 *buf++ = '-';
13889 buf += hexnumstr (buf, (ULONGEST) -val);
13891 else
13892 buf += hexnumstr (buf, (ULONGEST) val);
13894 putpkt (rs->buf);
13895 remote_get_noisy_reply ();
13896 result = packet_ok (rs->buf,
13897 &remote_protocol_packets[PACKET_QTBuffer_size]);
13899 if (result != PACKET_OK)
13900 warning (_("Bogus reply from target: %s"), rs->buf.data ());
13904 bool
13905 remote_target::set_trace_notes (const char *user, const char *notes,
13906 const char *stop_notes)
13908 struct remote_state *rs = get_remote_state ();
13909 char *reply;
13910 char *buf = rs->buf.data ();
13911 char *endbuf = buf + get_remote_packet_size ();
13912 int nbytes;
13914 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
13915 if (user)
13917 buf += xsnprintf (buf, endbuf - buf, "user:");
13918 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
13919 buf += 2 * nbytes;
13920 *buf++ = ';';
13922 if (notes)
13924 buf += xsnprintf (buf, endbuf - buf, "notes:");
13925 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
13926 buf += 2 * nbytes;
13927 *buf++ = ';';
13929 if (stop_notes)
13931 buf += xsnprintf (buf, endbuf - buf, "tstop:");
13932 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
13933 buf += 2 * nbytes;
13934 *buf++ = ';';
13936 /* Ensure the buffer is terminated. */
13937 *buf = '\0';
13939 putpkt (rs->buf);
13940 reply = remote_get_noisy_reply ();
13941 if (*reply == '\0')
13942 return false;
13944 if (strcmp (reply, "OK") != 0)
13945 error (_("Bogus reply from target: %s"), reply);
13947 return true;
13950 bool
13951 remote_target::use_agent (bool use)
13953 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
13955 struct remote_state *rs = get_remote_state ();
13957 /* If the stub supports QAgent. */
13958 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAgent:%d", use);
13959 putpkt (rs->buf);
13960 getpkt (&rs->buf, 0);
13962 if (strcmp (rs->buf.data (), "OK") == 0)
13964 ::use_agent = use;
13965 return true;
13969 return false;
13972 bool
13973 remote_target::can_use_agent ()
13975 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
13978 struct btrace_target_info
13980 /* The ptid of the traced thread. */
13981 ptid_t ptid;
13983 /* The obtained branch trace configuration. */
13984 struct btrace_config conf;
13987 /* Reset our idea of our target's btrace configuration. */
13989 static void
13990 remote_btrace_reset (remote_state *rs)
13992 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
13995 /* Synchronize the configuration with the target. */
13997 void
13998 remote_target::btrace_sync_conf (const btrace_config *conf)
14000 struct packet_config *packet;
14001 struct remote_state *rs;
14002 char *buf, *pos, *endbuf;
14004 rs = get_remote_state ();
14005 buf = rs->buf.data ();
14006 endbuf = buf + get_remote_packet_size ();
14008 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
14009 if (packet_config_support (packet) == PACKET_ENABLE
14010 && conf->bts.size != rs->btrace_config.bts.size)
14012 pos = buf;
14013 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
14014 conf->bts.size);
14016 putpkt (buf);
14017 getpkt (&rs->buf, 0);
14019 if (packet_ok (buf, packet) == PACKET_ERROR)
14021 if (buf[0] == 'E' && buf[1] == '.')
14022 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
14023 else
14024 error (_("Failed to configure the BTS buffer size."));
14027 rs->btrace_config.bts.size = conf->bts.size;
14030 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
14031 if (packet_config_support (packet) == PACKET_ENABLE
14032 && conf->pt.size != rs->btrace_config.pt.size)
14034 pos = buf;
14035 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
14036 conf->pt.size);
14038 putpkt (buf);
14039 getpkt (&rs->buf, 0);
14041 if (packet_ok (buf, packet) == PACKET_ERROR)
14043 if (buf[0] == 'E' && buf[1] == '.')
14044 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
14045 else
14046 error (_("Failed to configure the trace buffer size."));
14049 rs->btrace_config.pt.size = conf->pt.size;
14053 /* Read TP's btrace configuration from the target and store it into CONF. */
14055 static void
14056 btrace_read_config (thread_info *tp, struct btrace_config *conf)
14058 /* target_read_stralloc relies on INFERIOR_PTID. */
14059 scoped_restore_current_thread restore_thread;
14060 switch_to_thread (tp);
14062 gdb::optional<gdb::char_vector> xml
14063 = target_read_stralloc (current_inferior ()->top_target (),
14064 TARGET_OBJECT_BTRACE_CONF, "");
14065 if (xml)
14066 parse_xml_btrace_conf (conf, xml->data ());
14069 /* Maybe reopen target btrace. */
14071 void
14072 remote_target::remote_btrace_maybe_reopen ()
14074 struct remote_state *rs = get_remote_state ();
14075 int btrace_target_pushed = 0;
14076 #if !defined (HAVE_LIBIPT)
14077 int warned = 0;
14078 #endif
14080 /* Don't bother walking the entirety of the remote thread list when
14081 we know the feature isn't supported by the remote. */
14082 if (packet_support (PACKET_qXfer_btrace_conf) != PACKET_ENABLE)
14083 return;
14085 for (thread_info *tp : all_non_exited_threads (this))
14087 memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
14088 btrace_read_config (tp, &rs->btrace_config);
14090 if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
14091 continue;
14093 #if !defined (HAVE_LIBIPT)
14094 if (rs->btrace_config.format == BTRACE_FORMAT_PT)
14096 if (!warned)
14098 warned = 1;
14099 warning (_("Target is recording using Intel Processor Trace "
14100 "but support was disabled at compile time."));
14103 continue;
14105 #endif /* !defined (HAVE_LIBIPT) */
14107 /* Push target, once, but before anything else happens. This way our
14108 changes to the threads will be cleaned up by unpushing the target
14109 in case btrace_read_config () throws. */
14110 if (!btrace_target_pushed)
14112 btrace_target_pushed = 1;
14113 record_btrace_push_target ();
14114 gdb_printf (_("Target is recording using %s.\n"),
14115 btrace_format_string (rs->btrace_config.format));
14118 tp->btrace.target = XCNEW (struct btrace_target_info);
14119 tp->btrace.target->ptid = tp->ptid;
14120 tp->btrace.target->conf = rs->btrace_config;
14124 /* Enable branch tracing. */
14126 struct btrace_target_info *
14127 remote_target::enable_btrace (thread_info *tp,
14128 const struct btrace_config *conf)
14130 struct btrace_target_info *tinfo = NULL;
14131 struct packet_config *packet = NULL;
14132 struct remote_state *rs = get_remote_state ();
14133 char *buf = rs->buf.data ();
14134 char *endbuf = buf + get_remote_packet_size ();
14136 switch (conf->format)
14138 case BTRACE_FORMAT_BTS:
14139 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
14140 break;
14142 case BTRACE_FORMAT_PT:
14143 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
14144 break;
14147 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
14148 error (_("Target does not support branch tracing."));
14150 btrace_sync_conf (conf);
14152 ptid_t ptid = tp->ptid;
14153 set_general_thread (ptid);
14155 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
14156 putpkt (rs->buf);
14157 getpkt (&rs->buf, 0);
14159 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
14161 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
14162 error (_("Could not enable branch tracing for %s: %s"),
14163 target_pid_to_str (ptid).c_str (), &rs->buf[2]);
14164 else
14165 error (_("Could not enable branch tracing for %s."),
14166 target_pid_to_str (ptid).c_str ());
14169 tinfo = XCNEW (struct btrace_target_info);
14170 tinfo->ptid = ptid;
14172 /* If we fail to read the configuration, we lose some information, but the
14173 tracing itself is not impacted. */
14176 btrace_read_config (tp, &tinfo->conf);
14178 catch (const gdb_exception_error &err)
14180 if (err.message != NULL)
14181 warning ("%s", err.what ());
14184 return tinfo;
14187 /* Disable branch tracing. */
14189 void
14190 remote_target::disable_btrace (struct btrace_target_info *tinfo)
14192 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
14193 struct remote_state *rs = get_remote_state ();
14194 char *buf = rs->buf.data ();
14195 char *endbuf = buf + get_remote_packet_size ();
14197 if (packet_config_support (packet) != PACKET_ENABLE)
14198 error (_("Target does not support branch tracing."));
14200 set_general_thread (tinfo->ptid);
14202 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
14203 putpkt (rs->buf);
14204 getpkt (&rs->buf, 0);
14206 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
14208 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
14209 error (_("Could not disable branch tracing for %s: %s"),
14210 target_pid_to_str (tinfo->ptid).c_str (), &rs->buf[2]);
14211 else
14212 error (_("Could not disable branch tracing for %s."),
14213 target_pid_to_str (tinfo->ptid).c_str ());
14216 xfree (tinfo);
14219 /* Teardown branch tracing. */
14221 void
14222 remote_target::teardown_btrace (struct btrace_target_info *tinfo)
14224 /* We must not talk to the target during teardown. */
14225 xfree (tinfo);
14228 /* Read the branch trace. */
14230 enum btrace_error
14231 remote_target::read_btrace (struct btrace_data *btrace,
14232 struct btrace_target_info *tinfo,
14233 enum btrace_read_type type)
14235 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
14236 const char *annex;
14238 if (packet_config_support (packet) != PACKET_ENABLE)
14239 error (_("Target does not support branch tracing."));
14241 #if !defined(HAVE_LIBEXPAT)
14242 error (_("Cannot process branch tracing result. XML parsing not supported."));
14243 #endif
14245 switch (type)
14247 case BTRACE_READ_ALL:
14248 annex = "all";
14249 break;
14250 case BTRACE_READ_NEW:
14251 annex = "new";
14252 break;
14253 case BTRACE_READ_DELTA:
14254 annex = "delta";
14255 break;
14256 default:
14257 internal_error (_("Bad branch tracing read type: %u."),
14258 (unsigned int) type);
14261 gdb::optional<gdb::char_vector> xml
14262 = target_read_stralloc (current_inferior ()->top_target (),
14263 TARGET_OBJECT_BTRACE, annex);
14264 if (!xml)
14265 return BTRACE_ERR_UNKNOWN;
14267 parse_xml_btrace (btrace, xml->data ());
14269 return BTRACE_ERR_NONE;
14272 const struct btrace_config *
14273 remote_target::btrace_conf (const struct btrace_target_info *tinfo)
14275 return &tinfo->conf;
14278 bool
14279 remote_target::augmented_libraries_svr4_read ()
14281 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
14282 == PACKET_ENABLE);
14285 /* Implementation of to_load. */
14287 void
14288 remote_target::load (const char *name, int from_tty)
14290 generic_load (name, from_tty);
14293 /* Accepts an integer PID; returns a string representing a file that
14294 can be opened on the remote side to get the symbols for the child
14295 process. Returns NULL if the operation is not supported. */
14297 const char *
14298 remote_target::pid_to_exec_file (int pid)
14300 static gdb::optional<gdb::char_vector> filename;
14301 char *annex = NULL;
14303 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
14304 return NULL;
14306 inferior *inf = find_inferior_pid (this, pid);
14307 if (inf == NULL)
14308 internal_error (_("not currently attached to process %d"), pid);
14310 if (!inf->fake_pid_p)
14312 const int annex_size = 9;
14314 annex = (char *) alloca (annex_size);
14315 xsnprintf (annex, annex_size, "%x", pid);
14318 filename = target_read_stralloc (current_inferior ()->top_target (),
14319 TARGET_OBJECT_EXEC_FILE, annex);
14321 return filename ? filename->data () : nullptr;
14324 /* Implement the to_can_do_single_step target_ops method. */
14327 remote_target::can_do_single_step ()
14329 /* We can only tell whether target supports single step or not by
14330 supported s and S vCont actions if the stub supports vContSupported
14331 feature. If the stub doesn't support vContSupported feature,
14332 we have conservatively to think target doesn't supports single
14333 step. */
14334 if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
14336 struct remote_state *rs = get_remote_state ();
14338 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
14339 remote_vcont_probe ();
14341 return rs->supports_vCont.s && rs->supports_vCont.S;
14343 else
14344 return 0;
14347 /* Implementation of the to_execution_direction method for the remote
14348 target. */
14350 enum exec_direction_kind
14351 remote_target::execution_direction ()
14353 struct remote_state *rs = get_remote_state ();
14355 return rs->last_resume_exec_dir;
14358 /* Return pointer to the thread_info struct which corresponds to
14359 THREAD_HANDLE (having length HANDLE_LEN). */
14361 thread_info *
14362 remote_target::thread_handle_to_thread_info (const gdb_byte *thread_handle,
14363 int handle_len,
14364 inferior *inf)
14366 for (thread_info *tp : all_non_exited_threads (this))
14368 remote_thread_info *priv = get_remote_thread_info (tp);
14370 if (tp->inf == inf && priv != NULL)
14372 if (handle_len != priv->thread_handle.size ())
14373 error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
14374 handle_len, priv->thread_handle.size ());
14375 if (memcmp (thread_handle, priv->thread_handle.data (),
14376 handle_len) == 0)
14377 return tp;
14381 return NULL;
14384 gdb::byte_vector
14385 remote_target::thread_info_to_thread_handle (struct thread_info *tp)
14387 remote_thread_info *priv = get_remote_thread_info (tp);
14388 return priv->thread_handle;
14391 bool
14392 remote_target::can_async_p ()
14394 /* This flag should be checked in the common target.c code. */
14395 gdb_assert (target_async_permitted);
14397 /* We're async whenever the serial device can. */
14398 struct remote_state *rs = get_remote_state ();
14399 return serial_can_async_p (rs->remote_desc);
14402 bool
14403 remote_target::is_async_p ()
14405 /* We're async whenever the serial device is. */
14406 struct remote_state *rs = get_remote_state ();
14407 return serial_is_async_p (rs->remote_desc);
14410 /* Pass the SERIAL event on and up to the client. One day this code
14411 will be able to delay notifying the client of an event until the
14412 point where an entire packet has been received. */
14414 static serial_event_ftype remote_async_serial_handler;
14416 static void
14417 remote_async_serial_handler (struct serial *scb, void *context)
14419 /* Don't propogate error information up to the client. Instead let
14420 the client find out about the error by querying the target. */
14421 inferior_event_handler (INF_REG_EVENT);
14424 static void
14425 remote_async_inferior_event_handler (gdb_client_data data)
14427 inferior_event_handler (INF_REG_EVENT);
14431 remote_target::async_wait_fd ()
14433 struct remote_state *rs = get_remote_state ();
14434 return rs->remote_desc->fd;
14437 void
14438 remote_target::async (bool enable)
14440 struct remote_state *rs = get_remote_state ();
14442 if (enable)
14444 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
14446 /* If there are pending events in the stop reply queue tell the
14447 event loop to process them. */
14448 if (!rs->stop_reply_queue.empty ())
14449 mark_async_event_handler (rs->remote_async_inferior_event_token);
14450 /* For simplicity, below we clear the pending events token
14451 without remembering whether it is marked, so here we always
14452 mark it. If there's actually no pending notification to
14453 process, this ends up being a no-op (other than a spurious
14454 event-loop wakeup). */
14455 if (target_is_non_stop_p ())
14456 mark_async_event_handler (rs->notif_state->get_pending_events_token);
14458 else
14460 serial_async (rs->remote_desc, NULL, NULL);
14461 /* If the core is disabling async, it doesn't want to be
14462 disturbed with target events. Clear all async event sources
14463 too. */
14464 clear_async_event_handler (rs->remote_async_inferior_event_token);
14465 if (target_is_non_stop_p ())
14466 clear_async_event_handler (rs->notif_state->get_pending_events_token);
14470 /* Implementation of the to_thread_events method. */
14472 void
14473 remote_target::thread_events (int enable)
14475 struct remote_state *rs = get_remote_state ();
14476 size_t size = get_remote_packet_size ();
14478 if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
14479 return;
14481 xsnprintf (rs->buf.data (), size, "QThreadEvents:%x", enable ? 1 : 0);
14482 putpkt (rs->buf);
14483 getpkt (&rs->buf, 0);
14485 switch (packet_ok (rs->buf,
14486 &remote_protocol_packets[PACKET_QThreadEvents]))
14488 case PACKET_OK:
14489 if (strcmp (rs->buf.data (), "OK") != 0)
14490 error (_("Remote refused setting thread events: %s"), rs->buf.data ());
14491 break;
14492 case PACKET_ERROR:
14493 warning (_("Remote failure reply: %s"), rs->buf.data ());
14494 break;
14495 case PACKET_UNKNOWN:
14496 break;
14500 static void
14501 show_remote_cmd (const char *args, int from_tty)
14503 /* We can't just use cmd_show_list here, because we want to skip
14504 the redundant "show remote Z-packet" and the legacy aliases. */
14505 struct cmd_list_element *list = remote_show_cmdlist;
14506 struct ui_out *uiout = current_uiout;
14508 ui_out_emit_tuple tuple_emitter (uiout, "showlist");
14509 for (; list != NULL; list = list->next)
14510 if (strcmp (list->name, "Z-packet") == 0)
14511 continue;
14512 else if (list->type == not_set_cmd)
14513 /* Alias commands are exactly like the original, except they
14514 don't have the normal type. */
14515 continue;
14516 else
14518 ui_out_emit_tuple option_emitter (uiout, "option");
14520 uiout->field_string ("name", list->name);
14521 uiout->text (": ");
14522 if (list->type == show_cmd)
14523 do_show_command (NULL, from_tty, list);
14524 else
14525 cmd_func (list, NULL, from_tty);
14530 /* Function to be called whenever a new objfile (shlib) is detected. */
14531 static void
14532 remote_new_objfile (struct objfile *objfile)
14534 /* The objfile change happened in that program space. */
14535 program_space *pspace = current_program_space;
14537 /* The affected program space is possibly shared by multiple inferiors.
14538 Consider sending a qSymbol packet for each of the inferiors using that
14539 program space. */
14540 for (inferior *inf : all_inferiors ())
14542 if (inf->pspace != pspace)
14543 continue;
14545 /* Check whether the inferior's process target is a remote target. */
14546 remote_target *remote = as_remote_target (inf->process_target ());
14547 if (remote == nullptr)
14548 continue;
14550 /* When we are attaching or handling a fork child and the shared library
14551 subsystem reads the list of loaded libraries, we receive new objfile
14552 events in between each found library. The libraries are read in an
14553 undefined order, so if we gave the remote side a chance to look up
14554 symbols between each objfile, we might give it an inconsistent picture
14555 of the inferior. It could appear that a library A appears loaded but
14556 a library B does not, even though library A requires library B. That
14557 would present a state that couldn't normally exist in the inferior.
14559 So, skip these events, we'll give the remote a chance to look up
14560 symbols once all the loaded libraries and their symbols are known to
14561 GDB. */
14562 if (inf->in_initial_library_scan)
14563 continue;
14565 if (!remote->has_execution (inf))
14566 continue;
14568 /* Need to switch to a specific thread, because remote_check_symbols will
14569 set the general thread using INFERIOR_PTID.
14571 It's possible to have inferiors with no thread here, because we are
14572 called very early in the connection process, while the inferior is
14573 being set up, before threads are added. Just skip it, start_remote_1
14574 also calls remote_check_symbols when it's done setting things up. */
14575 thread_info *thread = any_thread_of_inferior (inf);
14576 if (thread != nullptr)
14578 scoped_restore_current_thread restore_thread;
14579 switch_to_thread (thread);
14580 remote->remote_check_symbols ();
14585 /* Pull all the tracepoints defined on the target and create local
14586 data structures representing them. We don't want to create real
14587 tracepoints yet, we don't want to mess up the user's existing
14588 collection. */
14591 remote_target::upload_tracepoints (struct uploaded_tp **utpp)
14593 struct remote_state *rs = get_remote_state ();
14594 char *p;
14596 /* Ask for a first packet of tracepoint definition. */
14597 putpkt ("qTfP");
14598 getpkt (&rs->buf, 0);
14599 p = rs->buf.data ();
14600 while (*p && *p != 'l')
14602 parse_tracepoint_definition (p, utpp);
14603 /* Ask for another packet of tracepoint definition. */
14604 putpkt ("qTsP");
14605 getpkt (&rs->buf, 0);
14606 p = rs->buf.data ();
14608 return 0;
14612 remote_target::upload_trace_state_variables (struct uploaded_tsv **utsvp)
14614 struct remote_state *rs = get_remote_state ();
14615 char *p;
14617 /* Ask for a first packet of variable definition. */
14618 putpkt ("qTfV");
14619 getpkt (&rs->buf, 0);
14620 p = rs->buf.data ();
14621 while (*p && *p != 'l')
14623 parse_tsv_definition (p, utsvp);
14624 /* Ask for another packet of variable definition. */
14625 putpkt ("qTsV");
14626 getpkt (&rs->buf, 0);
14627 p = rs->buf.data ();
14629 return 0;
14632 /* The "set/show range-stepping" show hook. */
14634 static void
14635 show_range_stepping (struct ui_file *file, int from_tty,
14636 struct cmd_list_element *c,
14637 const char *value)
14639 gdb_printf (file,
14640 _("Debugger's willingness to use range stepping "
14641 "is %s.\n"), value);
14644 /* Return true if the vCont;r action is supported by the remote
14645 stub. */
14647 bool
14648 remote_target::vcont_r_supported ()
14650 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
14651 remote_vcont_probe ();
14653 return (packet_support (PACKET_vCont) == PACKET_ENABLE
14654 && get_remote_state ()->supports_vCont.r);
14657 /* The "set/show range-stepping" set hook. */
14659 static void
14660 set_range_stepping (const char *ignore_args, int from_tty,
14661 struct cmd_list_element *c)
14663 /* When enabling, check whether range stepping is actually supported
14664 by the target, and warn if not. */
14665 if (use_range_stepping)
14667 remote_target *remote = get_current_remote_target ();
14668 if (remote == NULL
14669 || !remote->vcont_r_supported ())
14670 warning (_("Range stepping is not supported by the current target"));
14674 static void
14675 show_remote_debug (struct ui_file *file, int from_tty,
14676 struct cmd_list_element *c, const char *value)
14678 gdb_printf (file, _("Debugging of remote protocol is %s.\n"),
14679 value);
14682 static void
14683 show_remote_timeout (struct ui_file *file, int from_tty,
14684 struct cmd_list_element *c, const char *value)
14686 gdb_printf (file,
14687 _("Timeout limit to wait for target to respond is %s.\n"),
14688 value);
14691 /* Implement the "supports_memory_tagging" target_ops method. */
14693 bool
14694 remote_target::supports_memory_tagging ()
14696 return remote_memory_tagging_p ();
14699 /* Create the qMemTags packet given ADDRESS, LEN and TYPE. */
14701 static void
14702 create_fetch_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
14703 size_t len, int type)
14705 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
14707 std::string request = string_printf ("qMemTags:%s,%s:%s",
14708 phex_nz (address, addr_size),
14709 phex_nz (len, sizeof (len)),
14710 phex_nz (type, sizeof (type)));
14712 strcpy (packet.data (), request.c_str ());
14715 /* Parse the qMemTags packet reply into TAGS.
14717 Return true if successful, false otherwise. */
14719 static bool
14720 parse_fetch_memtags_reply (const gdb::char_vector &reply,
14721 gdb::byte_vector &tags)
14723 if (reply.empty () || reply[0] == 'E' || reply[0] != 'm')
14724 return false;
14726 /* Copy the tag data. */
14727 tags = hex2bin (reply.data () + 1);
14729 return true;
14732 /* Create the QMemTags packet given ADDRESS, LEN, TYPE and TAGS. */
14734 static void
14735 create_store_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
14736 size_t len, int type,
14737 const gdb::byte_vector &tags)
14739 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
14741 /* Put together the main packet, address and length. */
14742 std::string request = string_printf ("QMemTags:%s,%s:%s:",
14743 phex_nz (address, addr_size),
14744 phex_nz (len, sizeof (len)),
14745 phex_nz (type, sizeof (type)));
14746 request += bin2hex (tags.data (), tags.size ());
14748 /* Check if we have exceeded the maximum packet size. */
14749 if (packet.size () < request.length ())
14750 error (_("Contents too big for packet QMemTags."));
14752 strcpy (packet.data (), request.c_str ());
14755 /* Implement the "fetch_memtags" target_ops method. */
14757 bool
14758 remote_target::fetch_memtags (CORE_ADDR address, size_t len,
14759 gdb::byte_vector &tags, int type)
14761 /* Make sure the qMemTags packet is supported. */
14762 if (!remote_memory_tagging_p ())
14763 gdb_assert_not_reached ("remote fetch_memtags called with packet disabled");
14765 struct remote_state *rs = get_remote_state ();
14767 create_fetch_memtags_request (rs->buf, address, len, type);
14769 putpkt (rs->buf);
14770 getpkt (&rs->buf, 0);
14772 return parse_fetch_memtags_reply (rs->buf, tags);
14775 /* Implement the "store_memtags" target_ops method. */
14777 bool
14778 remote_target::store_memtags (CORE_ADDR address, size_t len,
14779 const gdb::byte_vector &tags, int type)
14781 /* Make sure the QMemTags packet is supported. */
14782 if (!remote_memory_tagging_p ())
14783 gdb_assert_not_reached ("remote store_memtags called with packet disabled");
14785 struct remote_state *rs = get_remote_state ();
14787 create_store_memtags_request (rs->buf, address, len, type, tags);
14789 putpkt (rs->buf);
14790 getpkt (&rs->buf, 0);
14792 /* Verify if the request was successful. */
14793 return packet_check_result (rs->buf.data ()) == PACKET_OK;
14796 /* Return true if remote target T is non-stop. */
14798 bool
14799 remote_target_is_non_stop_p (remote_target *t)
14801 scoped_restore_current_thread restore_thread;
14802 switch_to_target_no_thread (t);
14804 return target_is_non_stop_p ();
14807 #if GDB_SELF_TEST
14809 namespace selftests {
14811 static void
14812 test_memory_tagging_functions ()
14814 remote_target remote;
14816 struct packet_config *config
14817 = &remote_protocol_packets[PACKET_memory_tagging_feature];
14819 scoped_restore restore_memtag_support_
14820 = make_scoped_restore (&config->support);
14822 /* Test memory tagging packet support. */
14823 config->support = PACKET_SUPPORT_UNKNOWN;
14824 SELF_CHECK (remote.supports_memory_tagging () == false);
14825 config->support = PACKET_DISABLE;
14826 SELF_CHECK (remote.supports_memory_tagging () == false);
14827 config->support = PACKET_ENABLE;
14828 SELF_CHECK (remote.supports_memory_tagging () == true);
14830 /* Setup testing. */
14831 gdb::char_vector packet;
14832 gdb::byte_vector tags, bv;
14833 std::string expected, reply;
14834 packet.resize (32000);
14836 /* Test creating a qMemTags request. */
14838 expected = "qMemTags:0,0:0";
14839 create_fetch_memtags_request (packet, 0x0, 0x0, 0);
14840 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
14842 expected = "qMemTags:deadbeef,10:1";
14843 create_fetch_memtags_request (packet, 0xdeadbeef, 16, 1);
14844 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
14846 /* Test parsing a qMemTags reply. */
14848 /* Error reply, tags vector unmodified. */
14849 reply = "E00";
14850 strcpy (packet.data (), reply.c_str ());
14851 tags.resize (0);
14852 SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == false);
14853 SELF_CHECK (tags.size () == 0);
14855 /* Valid reply, tags vector updated. */
14856 tags.resize (0);
14857 bv.resize (0);
14859 for (int i = 0; i < 5; i++)
14860 bv.push_back (i);
14862 reply = "m" + bin2hex (bv.data (), bv.size ());
14863 strcpy (packet.data (), reply.c_str ());
14865 SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == true);
14866 SELF_CHECK (tags.size () == 5);
14868 for (int i = 0; i < 5; i++)
14869 SELF_CHECK (tags[i] == i);
14871 /* Test creating a QMemTags request. */
14873 /* Empty tag data. */
14874 tags.resize (0);
14875 expected = "QMemTags:0,0:0:";
14876 create_store_memtags_request (packet, 0x0, 0x0, 0, tags);
14877 SELF_CHECK (memcmp (packet.data (), expected.c_str (),
14878 expected.length ()) == 0);
14880 /* Non-empty tag data. */
14881 tags.resize (0);
14882 for (int i = 0; i < 5; i++)
14883 tags.push_back (i);
14884 expected = "QMemTags:deadbeef,ff:1:0001020304";
14885 create_store_memtags_request (packet, 0xdeadbeef, 255, 1, tags);
14886 SELF_CHECK (memcmp (packet.data (), expected.c_str (),
14887 expected.length ()) == 0);
14890 } // namespace selftests
14891 #endif /* GDB_SELF_TEST */
14893 void _initialize_remote ();
14894 void
14895 _initialize_remote ()
14897 add_target (remote_target_info, remote_target::open);
14898 add_target (extended_remote_target_info, extended_remote_target::open);
14900 /* Hook into new objfile notification. */
14901 gdb::observers::new_objfile.attach (remote_new_objfile, "remote");
14903 #if 0
14904 init_remote_threadtests ();
14905 #endif
14907 /* set/show remote ... */
14909 add_basic_prefix_cmd ("remote", class_maintenance, _("\
14910 Remote protocol specific variables.\n\
14911 Configure various remote-protocol specific variables such as\n\
14912 the packets being used."),
14913 &remote_set_cmdlist,
14914 0 /* allow-unknown */, &setlist);
14915 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
14916 Remote protocol specific variables.\n\
14917 Configure various remote-protocol specific variables such as\n\
14918 the packets being used."),
14919 &remote_show_cmdlist,
14920 0 /* allow-unknown */, &showlist);
14922 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
14923 Compare section data on target to the exec file.\n\
14924 Argument is a single section name (default: all loaded sections).\n\
14925 To compare only read-only loaded sections, specify the -r option."),
14926 &cmdlist);
14928 add_cmd ("packet", class_maintenance, cli_packet_command, _("\
14929 Send an arbitrary packet to a remote target.\n\
14930 maintenance packet TEXT\n\
14931 If GDB is talking to an inferior via the GDB serial protocol, then\n\
14932 this command sends the string TEXT to the inferior, and displays the\n\
14933 response packet. GDB supplies the initial `$' character, and the\n\
14934 terminating `#' character and checksum."),
14935 &maintenancelist);
14937 set_show_commands remotebreak_cmds
14938 = add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
14939 Set whether to send break if interrupted."), _("\
14940 Show whether to send break if interrupted."), _("\
14941 If set, a break, instead of a cntrl-c, is sent to the remote target."),
14942 set_remotebreak, show_remotebreak,
14943 &setlist, &showlist);
14944 deprecate_cmd (remotebreak_cmds.set, "set remote interrupt-sequence");
14945 deprecate_cmd (remotebreak_cmds.show, "show remote interrupt-sequence");
14947 add_setshow_enum_cmd ("interrupt-sequence", class_support,
14948 interrupt_sequence_modes, &interrupt_sequence_mode,
14949 _("\
14950 Set interrupt sequence to remote target."), _("\
14951 Show interrupt sequence to remote target."), _("\
14952 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
14953 NULL, show_interrupt_sequence,
14954 &remote_set_cmdlist,
14955 &remote_show_cmdlist);
14957 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
14958 &interrupt_on_connect, _("\
14959 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
14960 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
14961 If set, interrupt sequence is sent to remote target."),
14962 NULL, NULL,
14963 &remote_set_cmdlist, &remote_show_cmdlist);
14965 /* Install commands for configuring memory read/write packets. */
14967 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
14968 Set the maximum number of bytes per memory write packet (deprecated)."),
14969 &setlist);
14970 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
14971 Show the maximum number of bytes per memory write packet (deprecated)."),
14972 &showlist);
14973 add_cmd ("memory-write-packet-size", no_class,
14974 set_memory_write_packet_size, _("\
14975 Set the maximum number of bytes per memory-write packet.\n\
14976 Specify the number of bytes in a packet or 0 (zero) for the\n\
14977 default packet size. The actual limit is further reduced\n\
14978 dependent on the target. Specify ``fixed'' to disable the\n\
14979 further restriction and ``limit'' to enable that restriction."),
14980 &remote_set_cmdlist);
14981 add_cmd ("memory-read-packet-size", no_class,
14982 set_memory_read_packet_size, _("\
14983 Set the maximum number of bytes per memory-read packet.\n\
14984 Specify the number of bytes in a packet or 0 (zero) for the\n\
14985 default packet size. The actual limit is further reduced\n\
14986 dependent on the target. Specify ``fixed'' to disable the\n\
14987 further restriction and ``limit'' to enable that restriction."),
14988 &remote_set_cmdlist);
14989 add_cmd ("memory-write-packet-size", no_class,
14990 show_memory_write_packet_size,
14991 _("Show the maximum number of bytes per memory-write packet."),
14992 &remote_show_cmdlist);
14993 add_cmd ("memory-read-packet-size", no_class,
14994 show_memory_read_packet_size,
14995 _("Show the maximum number of bytes per memory-read packet."),
14996 &remote_show_cmdlist);
14998 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-limit", no_class,
14999 &remote_hw_watchpoint_limit, _("\
15000 Set the maximum number of target hardware watchpoints."), _("\
15001 Show the maximum number of target hardware watchpoints."), _("\
15002 Specify \"unlimited\" for unlimited hardware watchpoints."),
15003 NULL, show_hardware_watchpoint_limit,
15004 &remote_set_cmdlist,
15005 &remote_show_cmdlist);
15006 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-length-limit",
15007 no_class,
15008 &remote_hw_watchpoint_length_limit, _("\
15009 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
15010 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
15011 Specify \"unlimited\" to allow watchpoints of unlimited size."),
15012 NULL, show_hardware_watchpoint_length_limit,
15013 &remote_set_cmdlist, &remote_show_cmdlist);
15014 add_setshow_zuinteger_unlimited_cmd ("hardware-breakpoint-limit", no_class,
15015 &remote_hw_breakpoint_limit, _("\
15016 Set the maximum number of target hardware breakpoints."), _("\
15017 Show the maximum number of target hardware breakpoints."), _("\
15018 Specify \"unlimited\" for unlimited hardware breakpoints."),
15019 NULL, show_hardware_breakpoint_limit,
15020 &remote_set_cmdlist, &remote_show_cmdlist);
15022 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
15023 &remote_address_size, _("\
15024 Set the maximum size of the address (in bits) in a memory packet."), _("\
15025 Show the maximum size of the address (in bits) in a memory packet."), NULL,
15026 NULL,
15027 NULL, /* FIXME: i18n: */
15028 &setlist, &showlist);
15030 init_all_packet_configs ();
15032 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
15033 "X", "binary-download", 1);
15035 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
15036 "vCont", "verbose-resume", 0);
15038 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
15039 "QPassSignals", "pass-signals", 0);
15041 add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
15042 "QCatchSyscalls", "catch-syscalls", 0);
15044 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
15045 "QProgramSignals", "program-signals", 0);
15047 add_packet_config_cmd (&remote_protocol_packets[PACKET_QSetWorkingDir],
15048 "QSetWorkingDir", "set-working-dir", 0);
15050 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartupWithShell],
15051 "QStartupWithShell", "startup-with-shell", 0);
15053 add_packet_config_cmd (&remote_protocol_packets
15054 [PACKET_QEnvironmentHexEncoded],
15055 "QEnvironmentHexEncoded", "environment-hex-encoded",
15058 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentReset],
15059 "QEnvironmentReset", "environment-reset",
15062 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentUnset],
15063 "QEnvironmentUnset", "environment-unset",
15066 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
15067 "qSymbol", "symbol-lookup", 0);
15069 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
15070 "P", "set-register", 1);
15072 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
15073 "p", "fetch-register", 1);
15075 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
15076 "Z0", "software-breakpoint", 0);
15078 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
15079 "Z1", "hardware-breakpoint", 0);
15081 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
15082 "Z2", "write-watchpoint", 0);
15084 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
15085 "Z3", "read-watchpoint", 0);
15087 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
15088 "Z4", "access-watchpoint", 0);
15090 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
15091 "qXfer:auxv:read", "read-aux-vector", 0);
15093 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
15094 "qXfer:exec-file:read", "pid-to-exec-file", 0);
15096 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
15097 "qXfer:features:read", "target-features", 0);
15099 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
15100 "qXfer:libraries:read", "library-info", 0);
15102 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
15103 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
15105 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
15106 "qXfer:memory-map:read", "memory-map", 0);
15108 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
15109 "qXfer:osdata:read", "osdata", 0);
15111 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
15112 "qXfer:threads:read", "threads", 0);
15114 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
15115 "qXfer:siginfo:read", "read-siginfo-object", 0);
15117 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
15118 "qXfer:siginfo:write", "write-siginfo-object", 0);
15120 add_packet_config_cmd
15121 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
15122 "qXfer:traceframe-info:read", "traceframe-info", 0);
15124 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
15125 "qXfer:uib:read", "unwind-info-block", 0);
15127 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
15128 "qGetTLSAddr", "get-thread-local-storage-address",
15131 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
15132 "qGetTIBAddr", "get-thread-information-block-address",
15135 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
15136 "bc", "reverse-continue", 0);
15138 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
15139 "bs", "reverse-step", 0);
15141 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
15142 "qSupported", "supported-packets", 0);
15144 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
15145 "qSearch:memory", "search-memory", 0);
15147 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
15148 "qTStatus", "trace-status", 0);
15150 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
15151 "vFile:setfs", "hostio-setfs", 0);
15153 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
15154 "vFile:open", "hostio-open", 0);
15156 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
15157 "vFile:pread", "hostio-pread", 0);
15159 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
15160 "vFile:pwrite", "hostio-pwrite", 0);
15162 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
15163 "vFile:close", "hostio-close", 0);
15165 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
15166 "vFile:unlink", "hostio-unlink", 0);
15168 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
15169 "vFile:readlink", "hostio-readlink", 0);
15171 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
15172 "vFile:fstat", "hostio-fstat", 0);
15174 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
15175 "vAttach", "attach", 0);
15177 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
15178 "vRun", "run", 0);
15180 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
15181 "QStartNoAckMode", "noack", 0);
15183 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
15184 "vKill", "kill", 0);
15186 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
15187 "qAttached", "query-attached", 0);
15189 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
15190 "ConditionalTracepoints",
15191 "conditional-tracepoints", 0);
15193 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
15194 "ConditionalBreakpoints",
15195 "conditional-breakpoints", 0);
15197 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
15198 "BreakpointCommands",
15199 "breakpoint-commands", 0);
15201 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
15202 "FastTracepoints", "fast-tracepoints", 0);
15204 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
15205 "TracepointSource", "TracepointSource", 0);
15207 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
15208 "QAllow", "allow", 0);
15210 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
15211 "StaticTracepoints", "static-tracepoints", 0);
15213 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
15214 "InstallInTrace", "install-in-trace", 0);
15216 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
15217 "qXfer:statictrace:read", "read-sdata-object", 0);
15219 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
15220 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
15222 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
15223 "QDisableRandomization", "disable-randomization", 0);
15225 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
15226 "QAgent", "agent", 0);
15228 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
15229 "QTBuffer:size", "trace-buffer-size", 0);
15231 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
15232 "Qbtrace:off", "disable-btrace", 0);
15234 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
15235 "Qbtrace:bts", "enable-btrace-bts", 0);
15237 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
15238 "Qbtrace:pt", "enable-btrace-pt", 0);
15240 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
15241 "qXfer:btrace", "read-btrace", 0);
15243 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
15244 "qXfer:btrace-conf", "read-btrace-conf", 0);
15246 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
15247 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
15249 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
15250 "multiprocess-feature", "multiprocess-feature", 0);
15252 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
15253 "swbreak-feature", "swbreak-feature", 0);
15255 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
15256 "hwbreak-feature", "hwbreak-feature", 0);
15258 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
15259 "fork-event-feature", "fork-event-feature", 0);
15261 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
15262 "vfork-event-feature", "vfork-event-feature", 0);
15264 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
15265 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
15267 add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
15268 "vContSupported", "verbose-resume-supported", 0);
15270 add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
15271 "exec-event-feature", "exec-event-feature", 0);
15273 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
15274 "vCtrlC", "ctrl-c", 0);
15276 add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
15277 "QThreadEvents", "thread-events", 0);
15279 add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
15280 "N stop reply", "no-resumed-stop-reply", 0);
15282 add_packet_config_cmd (&remote_protocol_packets[PACKET_memory_tagging_feature],
15283 "memory-tagging-feature", "memory-tagging-feature", 0);
15285 /* Assert that we've registered "set remote foo-packet" commands
15286 for all packet configs. */
15288 int i;
15290 for (i = 0; i < PACKET_MAX; i++)
15292 /* Ideally all configs would have a command associated. Some
15293 still don't though. */
15294 int excepted;
15296 switch (i)
15298 case PACKET_QNonStop:
15299 case PACKET_EnableDisableTracepoints_feature:
15300 case PACKET_tracenz_feature:
15301 case PACKET_DisconnectedTracing_feature:
15302 case PACKET_augmented_libraries_svr4_read_feature:
15303 case PACKET_qCRC:
15304 /* Additions to this list need to be well justified:
15305 pre-existing packets are OK; new packets are not. */
15306 excepted = 1;
15307 break;
15308 default:
15309 excepted = 0;
15310 break;
15313 /* This catches both forgetting to add a config command, and
15314 forgetting to remove a packet from the exception list. */
15315 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
15319 /* Keep the old ``set remote Z-packet ...'' working. Each individual
15320 Z sub-packet has its own set and show commands, but users may
15321 have sets to this variable in their .gdbinit files (or in their
15322 documentation). */
15323 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
15324 &remote_Z_packet_detect, _("\
15325 Set use of remote protocol `Z' packets."), _("\
15326 Show use of remote protocol `Z' packets."), _("\
15327 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
15328 packets."),
15329 set_remote_protocol_Z_packet_cmd,
15330 show_remote_protocol_Z_packet_cmd,
15331 /* FIXME: i18n: Use of remote protocol
15332 `Z' packets is %s. */
15333 &remote_set_cmdlist, &remote_show_cmdlist);
15335 add_basic_prefix_cmd ("remote", class_files, _("\
15336 Manipulate files on the remote system.\n\
15337 Transfer files to and from the remote target system."),
15338 &remote_cmdlist,
15339 0 /* allow-unknown */, &cmdlist);
15341 add_cmd ("put", class_files, remote_put_command,
15342 _("Copy a local file to the remote system."),
15343 &remote_cmdlist);
15345 add_cmd ("get", class_files, remote_get_command,
15346 _("Copy a remote file to the local system."),
15347 &remote_cmdlist);
15349 add_cmd ("delete", class_files, remote_delete_command,
15350 _("Delete a remote file."),
15351 &remote_cmdlist);
15353 add_setshow_string_noescape_cmd ("exec-file", class_files,
15354 &remote_exec_file_var, _("\
15355 Set the remote pathname for \"run\"."), _("\
15356 Show the remote pathname for \"run\"."), NULL,
15357 set_remote_exec_file,
15358 show_remote_exec_file,
15359 &remote_set_cmdlist,
15360 &remote_show_cmdlist);
15362 add_setshow_boolean_cmd ("range-stepping", class_run,
15363 &use_range_stepping, _("\
15364 Enable or disable range stepping."), _("\
15365 Show whether target-assisted range stepping is enabled."), _("\
15366 If on, and the target supports it, when stepping a source line, GDB\n\
15367 tells the target to step the corresponding range of addresses itself instead\n\
15368 of issuing multiple single-steps. This speeds up source level\n\
15369 stepping. If off, GDB always issues single-steps, even if range\n\
15370 stepping is supported by the target. The default is on."),
15371 set_range_stepping,
15372 show_range_stepping,
15373 &setlist,
15374 &showlist);
15376 add_setshow_zinteger_cmd ("watchdog", class_maintenance, &watchdog, _("\
15377 Set watchdog timer."), _("\
15378 Show watchdog timer."), _("\
15379 When non-zero, this timeout is used instead of waiting forever for a target\n\
15380 to finish a low-level step or continue operation. If the specified amount\n\
15381 of time passes without a response from the target, an error occurs."),
15382 NULL,
15383 show_watchdog,
15384 &setlist, &showlist);
15386 add_setshow_zuinteger_unlimited_cmd ("remote-packet-max-chars", no_class,
15387 &remote_packet_max_chars, _("\
15388 Set the maximum number of characters to display for each remote packet."), _("\
15389 Show the maximum number of characters to display for each remote packet."), _("\
15390 Specify \"unlimited\" to display all the characters."),
15391 NULL, show_remote_packet_max_chars,
15392 &setdebuglist, &showdebuglist);
15394 add_setshow_boolean_cmd ("remote", no_class, &remote_debug,
15395 _("Set debugging of remote protocol."),
15396 _("Show debugging of remote protocol."),
15397 _("\
15398 When enabled, each packet sent or received with the remote target\n\
15399 is displayed."),
15400 NULL,
15401 show_remote_debug,
15402 &setdebuglist, &showdebuglist);
15404 add_setshow_zuinteger_unlimited_cmd ("remotetimeout", no_class,
15405 &remote_timeout, _("\
15406 Set timeout limit to wait for target to respond."), _("\
15407 Show timeout limit to wait for target to respond."), _("\
15408 This value is used to set the time limit for gdb to wait for a response\n\
15409 from the target."),
15410 NULL,
15411 show_remote_timeout,
15412 &setlist, &showlist);
15414 /* Eventually initialize fileio. See fileio.c */
15415 initialize_remote_fileio (&remote_set_cmdlist, &remote_show_cmdlist);
15417 #if GDB_SELF_TEST
15418 selftests::register_test ("remote_memory_tagging",
15419 selftests::test_memory_tagging_functions);
15420 #endif