IBM zSystems: Add support for z16 as CPU name.
[binutils-gdb.git] / gdb / remote.c
blobb002f041734ce37fa8911282e69645defdd9633d
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 "gdb/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 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 (int) 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 int *target_errno) override;
565 int fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
566 ULONGEST offset, int *target_errno) override;
568 int fileio_pread (int fd, gdb_byte *read_buf, int len,
569 ULONGEST offset, int *target_errno) override;
571 int fileio_fstat (int fd, struct stat *sb, int *target_errno) override;
573 int fileio_close (int fd, int *target_errno) override;
575 int fileio_unlink (struct inferior *inf,
576 const char *filename,
577 int *target_errno) override;
579 gdb::optional<std::string>
580 fileio_readlink (struct inferior *inf,
581 const char *filename,
582 int *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, int *remote_errno);
705 int remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
706 ULONGEST offset, int *remote_errno);
707 int remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
708 ULONGEST offset, int *remote_errno);
710 int remote_hostio_send_command (int command_bytes, int which_packet,
711 int *remote_errno, const char **attachment,
712 int *attachment_len);
713 int remote_hostio_set_filesystem (struct inferior *inf,
714 int *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 int *remote_errno);
719 int remote_hostio_close (int fd, int *remote_errno);
721 int remote_hostio_unlink (inferior *inf, const char *filename,
722 int *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 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 /* See remote.h. */
1021 bool
1022 is_remote_target (process_stratum_target *target)
1024 remote_target *rt = dynamic_cast<remote_target *> (target);
1025 return rt != nullptr;
1028 /* Per-program-space data key. */
1029 static const struct program_space_key<char, gdb::xfree_deleter<char>>
1030 remote_pspace_data;
1032 /* The variable registered as the control variable used by the
1033 remote exec-file commands. While the remote exec-file setting is
1034 per-program-space, the set/show machinery uses this as the
1035 location of the remote exec-file value. */
1036 static std::string remote_exec_file_var;
1038 /* The size to align memory write packets, when practical. The protocol
1039 does not guarantee any alignment, and gdb will generate short
1040 writes and unaligned writes, but even as a best-effort attempt this
1041 can improve bulk transfers. For instance, if a write is misaligned
1042 relative to the target's data bus, the stub may need to make an extra
1043 round trip fetching data from the target. This doesn't make a
1044 huge difference, but it's easy to do, so we try to be helpful.
1046 The alignment chosen is arbitrary; usually data bus width is
1047 important here, not the possibly larger cache line size. */
1048 enum { REMOTE_ALIGN_WRITES = 16 };
1050 /* Prototypes for local functions. */
1052 static int hexnumlen (ULONGEST num);
1054 static int stubhex (int ch);
1056 static int hexnumstr (char *, ULONGEST);
1058 static int hexnumnstr (char *, ULONGEST, int);
1060 static CORE_ADDR remote_address_masked (CORE_ADDR);
1062 static int stub_unpack_int (const char *buff, int fieldlength);
1064 struct packet_config;
1066 static void show_remote_protocol_packet_cmd (struct ui_file *file,
1067 int from_tty,
1068 struct cmd_list_element *c,
1069 const char *value);
1071 static ptid_t read_ptid (const char *buf, const char **obuf);
1073 static void remote_async_inferior_event_handler (gdb_client_data);
1075 static bool remote_read_description_p (struct target_ops *target);
1077 static void remote_console_output (const char *msg);
1079 static void remote_btrace_reset (remote_state *rs);
1081 static void remote_unpush_and_throw (remote_target *target);
1083 /* For "remote". */
1085 static struct cmd_list_element *remote_cmdlist;
1087 /* For "set remote" and "show remote". */
1089 static struct cmd_list_element *remote_set_cmdlist;
1090 static struct cmd_list_element *remote_show_cmdlist;
1092 /* Controls whether GDB is willing to use range stepping. */
1094 static bool use_range_stepping = true;
1096 /* From the remote target's point of view, each thread is in one of these three
1097 states. */
1098 enum class resume_state
1100 /* Not resumed - we haven't been asked to resume this thread. */
1101 NOT_RESUMED,
1103 /* We have been asked to resume this thread, but haven't sent a vCont action
1104 for it yet. We'll need to consider it next time commit_resume is
1105 called. */
1106 RESUMED_PENDING_VCONT,
1108 /* We have been asked to resume this thread, and we have sent a vCont action
1109 for it. */
1110 RESUMED,
1113 /* Information about a thread's pending vCont-resume. Used when a thread is in
1114 the remote_resume_state::RESUMED_PENDING_VCONT state. remote_target::resume
1115 stores this information which is then picked up by
1116 remote_target::commit_resume to know which is the proper action for this
1117 thread to include in the vCont packet. */
1118 struct resumed_pending_vcont_info
1120 /* True if the last resume call for this thread was a step request, false
1121 if a continue request. */
1122 bool step;
1124 /* The signal specified in the last resume call for this thread. */
1125 gdb_signal sig;
1128 /* Private data that we'll store in (struct thread_info)->priv. */
1129 struct remote_thread_info : public private_thread_info
1131 std::string extra;
1132 std::string name;
1133 int core = -1;
1135 /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
1136 sequence of bytes. */
1137 gdb::byte_vector thread_handle;
1139 /* Whether the target stopped for a breakpoint/watchpoint. */
1140 enum target_stop_reason stop_reason = TARGET_STOPPED_BY_NO_REASON;
1142 /* This is set to the data address of the access causing the target
1143 to stop for a watchpoint. */
1144 CORE_ADDR watch_data_address = 0;
1146 /* Get the thread's resume state. */
1147 enum resume_state get_resume_state () const
1149 return m_resume_state;
1152 /* Put the thread in the NOT_RESUMED state. */
1153 void set_not_resumed ()
1155 m_resume_state = resume_state::NOT_RESUMED;
1158 /* Put the thread in the RESUMED_PENDING_VCONT state. */
1159 void set_resumed_pending_vcont (bool step, gdb_signal sig)
1161 m_resume_state = resume_state::RESUMED_PENDING_VCONT;
1162 m_resumed_pending_vcont_info.step = step;
1163 m_resumed_pending_vcont_info.sig = sig;
1166 /* Get the information this thread's pending vCont-resumption.
1168 Must only be called if the thread is in the RESUMED_PENDING_VCONT resume
1169 state. */
1170 const struct resumed_pending_vcont_info &resumed_pending_vcont_info () const
1172 gdb_assert (m_resume_state == resume_state::RESUMED_PENDING_VCONT);
1174 return m_resumed_pending_vcont_info;
1177 /* Put the thread in the VCONT_RESUMED state. */
1178 void set_resumed ()
1180 m_resume_state = resume_state::RESUMED;
1183 private:
1184 /* Resume state for this thread. This is used to implement vCont action
1185 coalescing (only when the target operates in non-stop mode).
1187 remote_target::resume moves the thread to the RESUMED_PENDING_VCONT state,
1188 which notes that this thread must be considered in the next commit_resume
1189 call.
1191 remote_target::commit_resume sends a vCont packet with actions for the
1192 threads in the RESUMED_PENDING_VCONT state and moves them to the
1193 VCONT_RESUMED state.
1195 When reporting a stop to the core for a thread, that thread is moved back
1196 to the NOT_RESUMED state. */
1197 enum resume_state m_resume_state = resume_state::NOT_RESUMED;
1199 /* Extra info used if the thread is in the RESUMED_PENDING_VCONT state. */
1200 struct resumed_pending_vcont_info m_resumed_pending_vcont_info;
1203 remote_state::remote_state ()
1204 : buf (400)
1208 remote_state::~remote_state ()
1210 xfree (this->last_pass_packet);
1211 xfree (this->last_program_signals_packet);
1212 xfree (this->finished_object);
1213 xfree (this->finished_annex);
1216 /* Utility: generate error from an incoming stub packet. */
1217 static void
1218 trace_error (char *buf)
1220 if (*buf++ != 'E')
1221 return; /* not an error msg */
1222 switch (*buf)
1224 case '1': /* malformed packet error */
1225 if (*++buf == '0') /* general case: */
1226 error (_("remote.c: error in outgoing packet."));
1227 else
1228 error (_("remote.c: error in outgoing packet at field #%ld."),
1229 strtol (buf, NULL, 16));
1230 default:
1231 error (_("Target returns error code '%s'."), buf);
1235 /* Utility: wait for reply from stub, while accepting "O" packets. */
1237 char *
1238 remote_target::remote_get_noisy_reply ()
1240 struct remote_state *rs = get_remote_state ();
1242 do /* Loop on reply from remote stub. */
1244 char *buf;
1246 QUIT; /* Allow user to bail out with ^C. */
1247 getpkt (&rs->buf, 0);
1248 buf = rs->buf.data ();
1249 if (buf[0] == 'E')
1250 trace_error (buf);
1251 else if (startswith (buf, "qRelocInsn:"))
1253 ULONGEST ul;
1254 CORE_ADDR from, to, org_to;
1255 const char *p, *pp;
1256 int adjusted_size = 0;
1257 int relocated = 0;
1259 p = buf + strlen ("qRelocInsn:");
1260 pp = unpack_varlen_hex (p, &ul);
1261 if (*pp != ';')
1262 error (_("invalid qRelocInsn packet: %s"), buf);
1263 from = ul;
1265 p = pp + 1;
1266 unpack_varlen_hex (p, &ul);
1267 to = ul;
1269 org_to = to;
1273 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
1274 relocated = 1;
1276 catch (const gdb_exception &ex)
1278 if (ex.error == MEMORY_ERROR)
1280 /* Propagate memory errors silently back to the
1281 target. The stub may have limited the range of
1282 addresses we can write to, for example. */
1284 else
1286 /* Something unexpectedly bad happened. Be verbose
1287 so we can tell what, and propagate the error back
1288 to the stub, so it doesn't get stuck waiting for
1289 a response. */
1290 exception_fprintf (gdb_stderr, ex,
1291 _("warning: relocating instruction: "));
1293 putpkt ("E01");
1296 if (relocated)
1298 adjusted_size = to - org_to;
1300 xsnprintf (buf, rs->buf.size (), "qRelocInsn:%x", adjusted_size);
1301 putpkt (buf);
1304 else if (buf[0] == 'O' && buf[1] != 'K')
1305 remote_console_output (buf + 1); /* 'O' message from stub */
1306 else
1307 return buf; /* Here's the actual reply. */
1309 while (1);
1312 struct remote_arch_state *
1313 remote_state::get_remote_arch_state (struct gdbarch *gdbarch)
1315 remote_arch_state *rsa;
1317 auto it = this->m_arch_states.find (gdbarch);
1318 if (it == this->m_arch_states.end ())
1320 auto p = this->m_arch_states.emplace (std::piecewise_construct,
1321 std::forward_as_tuple (gdbarch),
1322 std::forward_as_tuple (gdbarch));
1323 rsa = &p.first->second;
1325 /* Make sure that the packet buffer is plenty big enough for
1326 this architecture. */
1327 if (this->buf.size () < rsa->remote_packet_size)
1328 this->buf.resize (2 * rsa->remote_packet_size);
1330 else
1331 rsa = &it->second;
1333 return rsa;
1336 /* Fetch the global remote target state. */
1338 remote_state *
1339 remote_target::get_remote_state ()
1341 /* Make sure that the remote architecture state has been
1342 initialized, because doing so might reallocate rs->buf. Any
1343 function which calls getpkt also needs to be mindful of changes
1344 to rs->buf, but this call limits the number of places which run
1345 into trouble. */
1346 m_remote_state.get_remote_arch_state (target_gdbarch ());
1348 return &m_remote_state;
1351 /* Fetch the remote exec-file from the current program space. */
1353 static const char *
1354 get_remote_exec_file (void)
1356 char *remote_exec_file;
1358 remote_exec_file = remote_pspace_data.get (current_program_space);
1359 if (remote_exec_file == NULL)
1360 return "";
1362 return remote_exec_file;
1365 /* Set the remote exec file for PSPACE. */
1367 static void
1368 set_pspace_remote_exec_file (struct program_space *pspace,
1369 const char *remote_exec_file)
1371 char *old_file = remote_pspace_data.get (pspace);
1373 xfree (old_file);
1374 remote_pspace_data.set (pspace, xstrdup (remote_exec_file));
1377 /* The "set/show remote exec-file" set command hook. */
1379 static void
1380 set_remote_exec_file (const char *ignored, int from_tty,
1381 struct cmd_list_element *c)
1383 set_pspace_remote_exec_file (current_program_space,
1384 remote_exec_file_var.c_str ());
1387 /* The "set/show remote exec-file" show command hook. */
1389 static void
1390 show_remote_exec_file (struct ui_file *file, int from_tty,
1391 struct cmd_list_element *cmd, const char *value)
1393 gdb_printf (file, "%s\n", get_remote_exec_file ());
1396 static int
1397 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
1399 int regnum, num_remote_regs, offset;
1400 struct packet_reg **remote_regs;
1402 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
1404 struct packet_reg *r = &regs[regnum];
1406 if (register_size (gdbarch, regnum) == 0)
1407 /* Do not try to fetch zero-sized (placeholder) registers. */
1408 r->pnum = -1;
1409 else
1410 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
1412 r->regnum = regnum;
1415 /* Define the g/G packet format as the contents of each register
1416 with a remote protocol number, in order of ascending protocol
1417 number. */
1419 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
1420 for (num_remote_regs = 0, regnum = 0;
1421 regnum < gdbarch_num_regs (gdbarch);
1422 regnum++)
1423 if (regs[regnum].pnum != -1)
1424 remote_regs[num_remote_regs++] = &regs[regnum];
1426 std::sort (remote_regs, remote_regs + num_remote_regs,
1427 [] (const packet_reg *a, const packet_reg *b)
1428 { return a->pnum < b->pnum; });
1430 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
1432 remote_regs[regnum]->in_g_packet = 1;
1433 remote_regs[regnum]->offset = offset;
1434 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
1437 return offset;
1440 /* Given the architecture described by GDBARCH, return the remote
1441 protocol register's number and the register's offset in the g/G
1442 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
1443 If the target does not have a mapping for REGNUM, return false,
1444 otherwise, return true. */
1447 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
1448 int *pnum, int *poffset)
1450 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
1452 std::vector<packet_reg> regs (gdbarch_num_regs (gdbarch));
1454 map_regcache_remote_table (gdbarch, regs.data ());
1456 *pnum = regs[regnum].pnum;
1457 *poffset = regs[regnum].offset;
1459 return *pnum != -1;
1462 remote_arch_state::remote_arch_state (struct gdbarch *gdbarch)
1464 /* Use the architecture to build a regnum<->pnum table, which will be
1465 1:1 unless a feature set specifies otherwise. */
1466 this->regs.reset (new packet_reg [gdbarch_num_regs (gdbarch)] ());
1468 /* Record the maximum possible size of the g packet - it may turn out
1469 to be smaller. */
1470 this->sizeof_g_packet
1471 = map_regcache_remote_table (gdbarch, this->regs.get ());
1473 /* Default maximum number of characters in a packet body. Many
1474 remote stubs have a hardwired buffer size of 400 bytes
1475 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
1476 as the maximum packet-size to ensure that the packet and an extra
1477 NUL character can always fit in the buffer. This stops GDB
1478 trashing stubs that try to squeeze an extra NUL into what is
1479 already a full buffer (As of 1999-12-04 that was most stubs). */
1480 this->remote_packet_size = 400 - 1;
1482 /* This one is filled in when a ``g'' packet is received. */
1483 this->actual_register_packet_size = 0;
1485 /* Should rsa->sizeof_g_packet needs more space than the
1486 default, adjust the size accordingly. Remember that each byte is
1487 encoded as two characters. 32 is the overhead for the packet
1488 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
1489 (``$NN:G...#NN'') is a better guess, the below has been padded a
1490 little. */
1491 if (this->sizeof_g_packet > ((this->remote_packet_size - 32) / 2))
1492 this->remote_packet_size = (this->sizeof_g_packet * 2 + 32);
1495 /* Get a pointer to the current remote target. If not connected to a
1496 remote target, return NULL. */
1498 static remote_target *
1499 get_current_remote_target ()
1501 target_ops *proc_target = current_inferior ()->process_target ();
1502 return dynamic_cast<remote_target *> (proc_target);
1505 /* Return the current allowed size of a remote packet. This is
1506 inferred from the current architecture, and should be used to
1507 limit the length of outgoing packets. */
1508 long
1509 remote_target::get_remote_packet_size ()
1511 struct remote_state *rs = get_remote_state ();
1512 remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
1514 if (rs->explicit_packet_size)
1515 return rs->explicit_packet_size;
1517 return rsa->remote_packet_size;
1520 static struct packet_reg *
1521 packet_reg_from_regnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1522 long regnum)
1524 if (regnum < 0 && regnum >= gdbarch_num_regs (gdbarch))
1525 return NULL;
1526 else
1528 struct packet_reg *r = &rsa->regs[regnum];
1530 gdb_assert (r->regnum == regnum);
1531 return r;
1535 static struct packet_reg *
1536 packet_reg_from_pnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1537 LONGEST pnum)
1539 int i;
1541 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
1543 struct packet_reg *r = &rsa->regs[i];
1545 if (r->pnum == pnum)
1546 return r;
1548 return NULL;
1551 /* Allow the user to specify what sequence to send to the remote
1552 when he requests a program interruption: Although ^C is usually
1553 what remote systems expect (this is the default, here), it is
1554 sometimes preferable to send a break. On other systems such
1555 as the Linux kernel, a break followed by g, which is Magic SysRq g
1556 is required in order to interrupt the execution. */
1557 const char interrupt_sequence_control_c[] = "Ctrl-C";
1558 const char interrupt_sequence_break[] = "BREAK";
1559 const char interrupt_sequence_break_g[] = "BREAK-g";
1560 static const char *const interrupt_sequence_modes[] =
1562 interrupt_sequence_control_c,
1563 interrupt_sequence_break,
1564 interrupt_sequence_break_g,
1565 NULL
1567 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
1569 static void
1570 show_interrupt_sequence (struct ui_file *file, int from_tty,
1571 struct cmd_list_element *c,
1572 const char *value)
1574 if (interrupt_sequence_mode == interrupt_sequence_control_c)
1575 gdb_printf (file,
1576 _("Send the ASCII ETX character (Ctrl-c) "
1577 "to the remote target to interrupt the "
1578 "execution of the program.\n"));
1579 else if (interrupt_sequence_mode == interrupt_sequence_break)
1580 gdb_printf (file,
1581 _("send a break signal to the remote target "
1582 "to interrupt the execution of the program.\n"));
1583 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
1584 gdb_printf (file,
1585 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
1586 "the remote target to interrupt the execution "
1587 "of Linux kernel.\n"));
1588 else
1589 internal_error (__FILE__, __LINE__,
1590 _("Invalid value for interrupt_sequence_mode: %s."),
1591 interrupt_sequence_mode);
1594 /* This boolean variable specifies whether interrupt_sequence is sent
1595 to the remote target when gdb connects to it.
1596 This is mostly needed when you debug the Linux kernel: The Linux kernel
1597 expects BREAK g which is Magic SysRq g for connecting gdb. */
1598 static bool interrupt_on_connect = false;
1600 /* This variable is used to implement the "set/show remotebreak" commands.
1601 Since these commands are now deprecated in favor of "set/show remote
1602 interrupt-sequence", it no longer has any effect on the code. */
1603 static bool remote_break;
1605 static void
1606 set_remotebreak (const char *args, int from_tty, struct cmd_list_element *c)
1608 if (remote_break)
1609 interrupt_sequence_mode = interrupt_sequence_break;
1610 else
1611 interrupt_sequence_mode = interrupt_sequence_control_c;
1614 static void
1615 show_remotebreak (struct ui_file *file, int from_tty,
1616 struct cmd_list_element *c,
1617 const char *value)
1621 /* This variable sets the number of bits in an address that are to be
1622 sent in a memory ("M" or "m") packet. Normally, after stripping
1623 leading zeros, the entire address would be sent. This variable
1624 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
1625 initial implementation of remote.c restricted the address sent in
1626 memory packets to ``host::sizeof long'' bytes - (typically 32
1627 bits). Consequently, for 64 bit targets, the upper 32 bits of an
1628 address was never sent. Since fixing this bug may cause a break in
1629 some remote targets this variable is principally provided to
1630 facilitate backward compatibility. */
1632 static unsigned int remote_address_size;
1635 /* User configurable variables for the number of characters in a
1636 memory read/write packet. MIN (rsa->remote_packet_size,
1637 rsa->sizeof_g_packet) is the default. Some targets need smaller
1638 values (fifo overruns, et.al.) and some users need larger values
1639 (speed up transfers). The variables ``preferred_*'' (the user
1640 request), ``current_*'' (what was actually set) and ``forced_*''
1641 (Positive - a soft limit, negative - a hard limit). */
1643 struct memory_packet_config
1645 const char *name;
1646 long size;
1647 int fixed_p;
1650 /* The default max memory-write-packet-size, when the setting is
1651 "fixed". The 16k is historical. (It came from older GDB's using
1652 alloca for buffers and the knowledge (folklore?) that some hosts
1653 don't cope very well with large alloca calls.) */
1654 #define DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED 16384
1656 /* The minimum remote packet size for memory transfers. Ensures we
1657 can write at least one byte. */
1658 #define MIN_MEMORY_PACKET_SIZE 20
1660 /* Get the memory packet size, assuming it is fixed. */
1662 static long
1663 get_fixed_memory_packet_size (struct memory_packet_config *config)
1665 gdb_assert (config->fixed_p);
1667 if (config->size <= 0)
1668 return DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED;
1669 else
1670 return config->size;
1673 /* Compute the current size of a read/write packet. Since this makes
1674 use of ``actual_register_packet_size'' the computation is dynamic. */
1676 long
1677 remote_target::get_memory_packet_size (struct memory_packet_config *config)
1679 struct remote_state *rs = get_remote_state ();
1680 remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
1682 long what_they_get;
1683 if (config->fixed_p)
1684 what_they_get = get_fixed_memory_packet_size (config);
1685 else
1687 what_they_get = get_remote_packet_size ();
1688 /* Limit the packet to the size specified by the user. */
1689 if (config->size > 0
1690 && what_they_get > config->size)
1691 what_they_get = config->size;
1693 /* Limit it to the size of the targets ``g'' response unless we have
1694 permission from the stub to use a larger packet size. */
1695 if (rs->explicit_packet_size == 0
1696 && rsa->actual_register_packet_size > 0
1697 && what_they_get > rsa->actual_register_packet_size)
1698 what_they_get = rsa->actual_register_packet_size;
1700 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1701 what_they_get = MIN_MEMORY_PACKET_SIZE;
1703 /* Make sure there is room in the global buffer for this packet
1704 (including its trailing NUL byte). */
1705 if (rs->buf.size () < what_they_get + 1)
1706 rs->buf.resize (2 * what_they_get);
1708 return what_they_get;
1711 /* Update the size of a read/write packet. If they user wants
1712 something really big then do a sanity check. */
1714 static void
1715 set_memory_packet_size (const char *args, struct memory_packet_config *config)
1717 int fixed_p = config->fixed_p;
1718 long size = config->size;
1720 if (args == NULL)
1721 error (_("Argument required (integer, `fixed' or `limited')."));
1722 else if (strcmp (args, "hard") == 0
1723 || strcmp (args, "fixed") == 0)
1724 fixed_p = 1;
1725 else if (strcmp (args, "soft") == 0
1726 || strcmp (args, "limit") == 0)
1727 fixed_p = 0;
1728 else
1730 char *end;
1732 size = strtoul (args, &end, 0);
1733 if (args == end)
1734 error (_("Invalid %s (bad syntax)."), config->name);
1736 /* Instead of explicitly capping the size of a packet to or
1737 disallowing it, the user is allowed to set the size to
1738 something arbitrarily large. */
1741 /* Extra checks? */
1742 if (fixed_p && !config->fixed_p)
1744 /* So that the query shows the correct value. */
1745 long query_size = (size <= 0
1746 ? DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED
1747 : size);
1749 if (! query (_("The target may not be able to correctly handle a %s\n"
1750 "of %ld bytes. Change the packet size? "),
1751 config->name, query_size))
1752 error (_("Packet size not changed."));
1754 /* Update the config. */
1755 config->fixed_p = fixed_p;
1756 config->size = size;
1759 static void
1760 show_memory_packet_size (struct memory_packet_config *config)
1762 if (config->size == 0)
1763 gdb_printf (_("The %s is 0 (default). "), config->name);
1764 else
1765 gdb_printf (_("The %s is %ld. "), config->name, config->size);
1766 if (config->fixed_p)
1767 gdb_printf (_("Packets are fixed at %ld bytes.\n"),
1768 get_fixed_memory_packet_size (config));
1769 else
1771 remote_target *remote = get_current_remote_target ();
1773 if (remote != NULL)
1774 gdb_printf (_("Packets are limited to %ld bytes.\n"),
1775 remote->get_memory_packet_size (config));
1776 else
1777 gdb_puts ("The actual limit will be further reduced "
1778 "dependent on the target.\n");
1782 /* FIXME: needs to be per-remote-target. */
1783 static struct memory_packet_config memory_write_packet_config =
1785 "memory-write-packet-size",
1788 static void
1789 set_memory_write_packet_size (const char *args, int from_tty)
1791 set_memory_packet_size (args, &memory_write_packet_config);
1794 static void
1795 show_memory_write_packet_size (const char *args, int from_tty)
1797 show_memory_packet_size (&memory_write_packet_config);
1800 /* Show the number of hardware watchpoints that can be used. */
1802 static void
1803 show_hardware_watchpoint_limit (struct ui_file *file, int from_tty,
1804 struct cmd_list_element *c,
1805 const char *value)
1807 gdb_printf (file, _("The maximum number of target hardware "
1808 "watchpoints is %s.\n"), value);
1811 /* Show the length limit (in bytes) for hardware watchpoints. */
1813 static void
1814 show_hardware_watchpoint_length_limit (struct ui_file *file, int from_tty,
1815 struct cmd_list_element *c,
1816 const char *value)
1818 gdb_printf (file, _("The maximum length (in bytes) of a target "
1819 "hardware watchpoint is %s.\n"), value);
1822 /* Show the number of hardware breakpoints that can be used. */
1824 static void
1825 show_hardware_breakpoint_limit (struct ui_file *file, int from_tty,
1826 struct cmd_list_element *c,
1827 const char *value)
1829 gdb_printf (file, _("The maximum number of target hardware "
1830 "breakpoints is %s.\n"), value);
1833 /* Controls the maximum number of characters to display in the debug output
1834 for each remote packet. The remaining characters are omitted. */
1836 static int remote_packet_max_chars = 512;
1838 /* Show the maximum number of characters to display for each remote packet
1839 when remote debugging is enabled. */
1841 static void
1842 show_remote_packet_max_chars (struct ui_file *file, int from_tty,
1843 struct cmd_list_element *c,
1844 const char *value)
1846 gdb_printf (file, _("Number of remote packet characters to "
1847 "display is %s.\n"), value);
1850 long
1851 remote_target::get_memory_write_packet_size ()
1853 return get_memory_packet_size (&memory_write_packet_config);
1856 /* FIXME: needs to be per-remote-target. */
1857 static struct memory_packet_config memory_read_packet_config =
1859 "memory-read-packet-size",
1862 static void
1863 set_memory_read_packet_size (const char *args, int from_tty)
1865 set_memory_packet_size (args, &memory_read_packet_config);
1868 static void
1869 show_memory_read_packet_size (const char *args, int from_tty)
1871 show_memory_packet_size (&memory_read_packet_config);
1874 long
1875 remote_target::get_memory_read_packet_size ()
1877 long size = get_memory_packet_size (&memory_read_packet_config);
1879 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1880 extra buffer size argument before the memory read size can be
1881 increased beyond this. */
1882 if (size > get_remote_packet_size ())
1883 size = get_remote_packet_size ();
1884 return size;
1889 struct packet_config
1891 const char *name;
1892 const char *title;
1894 /* If auto, GDB auto-detects support for this packet or feature,
1895 either through qSupported, or by trying the packet and looking
1896 at the response. If true, GDB assumes the target supports this
1897 packet. If false, the packet is disabled. Configs that don't
1898 have an associated command always have this set to auto. */
1899 enum auto_boolean detect;
1901 /* The "show remote foo-packet" command created for this packet. */
1902 cmd_list_element *show_cmd;
1904 /* Does the target support this packet? */
1905 enum packet_support support;
1908 static enum packet_support packet_config_support (struct packet_config *config);
1909 static enum packet_support packet_support (int packet);
1911 static void
1912 show_packet_config_cmd (ui_file *file, struct packet_config *config)
1914 const char *support = "internal-error";
1916 switch (packet_config_support (config))
1918 case PACKET_ENABLE:
1919 support = "enabled";
1920 break;
1921 case PACKET_DISABLE:
1922 support = "disabled";
1923 break;
1924 case PACKET_SUPPORT_UNKNOWN:
1925 support = "unknown";
1926 break;
1928 switch (config->detect)
1930 case AUTO_BOOLEAN_AUTO:
1931 gdb_printf (file,
1932 _("Support for the `%s' packet "
1933 "is auto-detected, currently %s.\n"),
1934 config->name, support);
1935 break;
1936 case AUTO_BOOLEAN_TRUE:
1937 case AUTO_BOOLEAN_FALSE:
1938 gdb_printf (file,
1939 _("Support for the `%s' packet is currently %s.\n"),
1940 config->name, support);
1941 break;
1945 static void
1946 add_packet_config_cmd (struct packet_config *config, const char *name,
1947 const char *title, int legacy)
1949 config->name = name;
1950 config->title = title;
1951 gdb::unique_xmalloc_ptr<char> set_doc
1952 = xstrprintf ("Set use of remote protocol `%s' (%s) packet.",
1953 name, title);
1954 gdb::unique_xmalloc_ptr<char> show_doc
1955 = xstrprintf ("Show current use of remote protocol `%s' (%s) packet.",
1956 name, title);
1957 /* set/show TITLE-packet {auto,on,off} */
1958 gdb::unique_xmalloc_ptr<char> cmd_name = xstrprintf ("%s-packet", title);
1959 set_show_commands cmds
1960 = add_setshow_auto_boolean_cmd (cmd_name.release (), class_obscure,
1961 &config->detect, set_doc.get (),
1962 show_doc.get (), NULL, /* help_doc */
1963 NULL,
1964 show_remote_protocol_packet_cmd,
1965 &remote_set_cmdlist, &remote_show_cmdlist);
1966 config->show_cmd = cmds.show;
1968 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
1969 if (legacy)
1971 /* It's not clear who should take ownership of this string, so, for
1972 now, make it static, and give copies to each of the add_alias_cmd
1973 calls below. */
1974 static gdb::unique_xmalloc_ptr<char> legacy_name
1975 = xstrprintf ("%s-packet", name);
1976 add_alias_cmd (legacy_name.get (), cmds.set, class_obscure, 0,
1977 &remote_set_cmdlist);
1978 add_alias_cmd (legacy_name.get (), cmds.show, class_obscure, 0,
1979 &remote_show_cmdlist);
1983 static enum packet_result
1984 packet_check_result (const char *buf)
1986 if (buf[0] != '\0')
1988 /* The stub recognized the packet request. Check that the
1989 operation succeeded. */
1990 if (buf[0] == 'E'
1991 && isxdigit (buf[1]) && isxdigit (buf[2])
1992 && buf[3] == '\0')
1993 /* "Enn" - definitely an error. */
1994 return PACKET_ERROR;
1996 /* Always treat "E." as an error. This will be used for
1997 more verbose error messages, such as E.memtypes. */
1998 if (buf[0] == 'E' && buf[1] == '.')
1999 return PACKET_ERROR;
2001 /* The packet may or may not be OK. Just assume it is. */
2002 return PACKET_OK;
2004 else
2005 /* The stub does not support the packet. */
2006 return PACKET_UNKNOWN;
2009 static enum packet_result
2010 packet_check_result (const gdb::char_vector &buf)
2012 return packet_check_result (buf.data ());
2015 static enum packet_result
2016 packet_ok (const char *buf, struct packet_config *config)
2018 enum packet_result result;
2020 if (config->detect != AUTO_BOOLEAN_TRUE
2021 && config->support == PACKET_DISABLE)
2022 internal_error (__FILE__, __LINE__,
2023 _("packet_ok: attempt to use a disabled packet"));
2025 result = packet_check_result (buf);
2026 switch (result)
2028 case PACKET_OK:
2029 case PACKET_ERROR:
2030 /* The stub recognized the packet request. */
2031 if (config->support == PACKET_SUPPORT_UNKNOWN)
2033 remote_debug_printf ("Packet %s (%s) is supported",
2034 config->name, config->title);
2035 config->support = PACKET_ENABLE;
2037 break;
2038 case PACKET_UNKNOWN:
2039 /* The stub does not support the packet. */
2040 if (config->detect == AUTO_BOOLEAN_AUTO
2041 && config->support == PACKET_ENABLE)
2043 /* If the stub previously indicated that the packet was
2044 supported then there is a protocol error. */
2045 error (_("Protocol error: %s (%s) conflicting enabled responses."),
2046 config->name, config->title);
2048 else if (config->detect == AUTO_BOOLEAN_TRUE)
2050 /* The user set it wrong. */
2051 error (_("Enabled packet %s (%s) not recognized by stub"),
2052 config->name, config->title);
2055 remote_debug_printf ("Packet %s (%s) is NOT supported",
2056 config->name, config->title);
2057 config->support = PACKET_DISABLE;
2058 break;
2061 return result;
2064 static enum packet_result
2065 packet_ok (const gdb::char_vector &buf, struct packet_config *config)
2067 return packet_ok (buf.data (), config);
2070 enum {
2071 PACKET_vCont = 0,
2072 PACKET_X,
2073 PACKET_qSymbol,
2074 PACKET_P,
2075 PACKET_p,
2076 PACKET_Z0,
2077 PACKET_Z1,
2078 PACKET_Z2,
2079 PACKET_Z3,
2080 PACKET_Z4,
2081 PACKET_vFile_setfs,
2082 PACKET_vFile_open,
2083 PACKET_vFile_pread,
2084 PACKET_vFile_pwrite,
2085 PACKET_vFile_close,
2086 PACKET_vFile_unlink,
2087 PACKET_vFile_readlink,
2088 PACKET_vFile_fstat,
2089 PACKET_qXfer_auxv,
2090 PACKET_qXfer_features,
2091 PACKET_qXfer_exec_file,
2092 PACKET_qXfer_libraries,
2093 PACKET_qXfer_libraries_svr4,
2094 PACKET_qXfer_memory_map,
2095 PACKET_qXfer_osdata,
2096 PACKET_qXfer_threads,
2097 PACKET_qXfer_statictrace_read,
2098 PACKET_qXfer_traceframe_info,
2099 PACKET_qXfer_uib,
2100 PACKET_qGetTIBAddr,
2101 PACKET_qGetTLSAddr,
2102 PACKET_qSupported,
2103 PACKET_qTStatus,
2104 PACKET_QPassSignals,
2105 PACKET_QCatchSyscalls,
2106 PACKET_QProgramSignals,
2107 PACKET_QSetWorkingDir,
2108 PACKET_QStartupWithShell,
2109 PACKET_QEnvironmentHexEncoded,
2110 PACKET_QEnvironmentReset,
2111 PACKET_QEnvironmentUnset,
2112 PACKET_qCRC,
2113 PACKET_qSearch_memory,
2114 PACKET_vAttach,
2115 PACKET_vRun,
2116 PACKET_QStartNoAckMode,
2117 PACKET_vKill,
2118 PACKET_qXfer_siginfo_read,
2119 PACKET_qXfer_siginfo_write,
2120 PACKET_qAttached,
2122 /* Support for conditional tracepoints. */
2123 PACKET_ConditionalTracepoints,
2125 /* Support for target-side breakpoint conditions. */
2126 PACKET_ConditionalBreakpoints,
2128 /* Support for target-side breakpoint commands. */
2129 PACKET_BreakpointCommands,
2131 /* Support for fast tracepoints. */
2132 PACKET_FastTracepoints,
2134 /* Support for static tracepoints. */
2135 PACKET_StaticTracepoints,
2137 /* Support for installing tracepoints while a trace experiment is
2138 running. */
2139 PACKET_InstallInTrace,
2141 PACKET_bc,
2142 PACKET_bs,
2143 PACKET_TracepointSource,
2144 PACKET_QAllow,
2145 PACKET_qXfer_fdpic,
2146 PACKET_QDisableRandomization,
2147 PACKET_QAgent,
2148 PACKET_QTBuffer_size,
2149 PACKET_Qbtrace_off,
2150 PACKET_Qbtrace_bts,
2151 PACKET_Qbtrace_pt,
2152 PACKET_qXfer_btrace,
2154 /* Support for the QNonStop packet. */
2155 PACKET_QNonStop,
2157 /* Support for the QThreadEvents packet. */
2158 PACKET_QThreadEvents,
2160 /* Support for multi-process extensions. */
2161 PACKET_multiprocess_feature,
2163 /* Support for enabling and disabling tracepoints while a trace
2164 experiment is running. */
2165 PACKET_EnableDisableTracepoints_feature,
2167 /* Support for collecting strings using the tracenz bytecode. */
2168 PACKET_tracenz_feature,
2170 /* Support for continuing to run a trace experiment while GDB is
2171 disconnected. */
2172 PACKET_DisconnectedTracing_feature,
2174 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
2175 PACKET_augmented_libraries_svr4_read_feature,
2177 /* Support for the qXfer:btrace-conf:read packet. */
2178 PACKET_qXfer_btrace_conf,
2180 /* Support for the Qbtrace-conf:bts:size packet. */
2181 PACKET_Qbtrace_conf_bts_size,
2183 /* Support for swbreak+ feature. */
2184 PACKET_swbreak_feature,
2186 /* Support for hwbreak+ feature. */
2187 PACKET_hwbreak_feature,
2189 /* Support for fork events. */
2190 PACKET_fork_event_feature,
2192 /* Support for vfork events. */
2193 PACKET_vfork_event_feature,
2195 /* Support for the Qbtrace-conf:pt:size packet. */
2196 PACKET_Qbtrace_conf_pt_size,
2198 /* Support for exec events. */
2199 PACKET_exec_event_feature,
2201 /* Support for query supported vCont actions. */
2202 PACKET_vContSupported,
2204 /* Support remote CTRL-C. */
2205 PACKET_vCtrlC,
2207 /* Support TARGET_WAITKIND_NO_RESUMED. */
2208 PACKET_no_resumed,
2210 /* Support for memory tagging, allocation tag fetch/store
2211 packets and the tag violation stop replies. */
2212 PACKET_memory_tagging_feature,
2214 PACKET_MAX
2217 /* FIXME: needs to be per-remote-target. Ignoring this for now,
2218 assuming all remote targets are the same server (thus all support
2219 the same packets). */
2220 static struct packet_config remote_protocol_packets[PACKET_MAX];
2222 /* Returns the packet's corresponding "set remote foo-packet" command
2223 state. See struct packet_config for more details. */
2225 static enum auto_boolean
2226 packet_set_cmd_state (int packet)
2228 return remote_protocol_packets[packet].detect;
2231 /* Returns whether a given packet or feature is supported. This takes
2232 into account the state of the corresponding "set remote foo-packet"
2233 command, which may be used to bypass auto-detection. */
2235 static enum packet_support
2236 packet_config_support (struct packet_config *config)
2238 switch (config->detect)
2240 case AUTO_BOOLEAN_TRUE:
2241 return PACKET_ENABLE;
2242 case AUTO_BOOLEAN_FALSE:
2243 return PACKET_DISABLE;
2244 case AUTO_BOOLEAN_AUTO:
2245 return config->support;
2246 default:
2247 gdb_assert_not_reached ("bad switch");
2251 /* Same as packet_config_support, but takes the packet's enum value as
2252 argument. */
2254 static enum packet_support
2255 packet_support (int packet)
2257 struct packet_config *config = &remote_protocol_packets[packet];
2259 return packet_config_support (config);
2262 static void
2263 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
2264 struct cmd_list_element *c,
2265 const char *value)
2267 struct packet_config *packet;
2268 gdb_assert (c->var.has_value ());
2270 for (packet = remote_protocol_packets;
2271 packet < &remote_protocol_packets[PACKET_MAX];
2272 packet++)
2274 if (c == packet->show_cmd)
2276 show_packet_config_cmd (file, packet);
2277 return;
2280 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
2281 c->name);
2284 /* Should we try one of the 'Z' requests? */
2286 enum Z_packet_type
2288 Z_PACKET_SOFTWARE_BP,
2289 Z_PACKET_HARDWARE_BP,
2290 Z_PACKET_WRITE_WP,
2291 Z_PACKET_READ_WP,
2292 Z_PACKET_ACCESS_WP,
2293 NR_Z_PACKET_TYPES
2296 /* For compatibility with older distributions. Provide a ``set remote
2297 Z-packet ...'' command that updates all the Z packet types. */
2299 static enum auto_boolean remote_Z_packet_detect;
2301 static void
2302 set_remote_protocol_Z_packet_cmd (const char *args, int from_tty,
2303 struct cmd_list_element *c)
2305 int i;
2307 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2308 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
2311 static void
2312 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
2313 struct cmd_list_element *c,
2314 const char *value)
2316 int i;
2318 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2320 show_packet_config_cmd (file, &remote_protocol_packets[PACKET_Z0 + i]);
2324 /* Returns true if the multi-process extensions are in effect. */
2326 static int
2327 remote_multi_process_p (struct remote_state *rs)
2329 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
2332 /* Returns true if fork events are supported. */
2334 static int
2335 remote_fork_event_p (struct remote_state *rs)
2337 return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
2340 /* Returns true if vfork events are supported. */
2342 static int
2343 remote_vfork_event_p (struct remote_state *rs)
2345 return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
2348 /* Returns true if exec events are supported. */
2350 static int
2351 remote_exec_event_p (struct remote_state *rs)
2353 return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
2356 /* Returns true if memory tagging is supported, false otherwise. */
2358 static bool
2359 remote_memory_tagging_p ()
2361 return packet_support (PACKET_memory_tagging_feature) == PACKET_ENABLE;
2364 /* Insert fork catchpoint target routine. If fork events are enabled
2365 then return success, nothing more to do. */
2368 remote_target::insert_fork_catchpoint (int pid)
2370 struct remote_state *rs = get_remote_state ();
2372 return !remote_fork_event_p (rs);
2375 /* Remove fork catchpoint target routine. Nothing to do, just
2376 return success. */
2379 remote_target::remove_fork_catchpoint (int pid)
2381 return 0;
2384 /* Insert vfork catchpoint target routine. If vfork events are enabled
2385 then return success, nothing more to do. */
2388 remote_target::insert_vfork_catchpoint (int pid)
2390 struct remote_state *rs = get_remote_state ();
2392 return !remote_vfork_event_p (rs);
2395 /* Remove vfork catchpoint target routine. Nothing to do, just
2396 return success. */
2399 remote_target::remove_vfork_catchpoint (int pid)
2401 return 0;
2404 /* Insert exec catchpoint target routine. If exec events are
2405 enabled, just return success. */
2408 remote_target::insert_exec_catchpoint (int pid)
2410 struct remote_state *rs = get_remote_state ();
2412 return !remote_exec_event_p (rs);
2415 /* Remove exec catchpoint target routine. Nothing to do, just
2416 return success. */
2419 remote_target::remove_exec_catchpoint (int pid)
2421 return 0;
2426 /* Take advantage of the fact that the TID field is not used, to tag
2427 special ptids with it set to != 0. */
2428 static const ptid_t magic_null_ptid (42000, -1, 1);
2429 static const ptid_t not_sent_ptid (42000, -2, 1);
2430 static const ptid_t any_thread_ptid (42000, 0, 1);
2432 /* Find out if the stub attached to PID (and hence GDB should offer to
2433 detach instead of killing it when bailing out). */
2436 remote_target::remote_query_attached (int pid)
2438 struct remote_state *rs = get_remote_state ();
2439 size_t size = get_remote_packet_size ();
2441 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
2442 return 0;
2444 if (remote_multi_process_p (rs))
2445 xsnprintf (rs->buf.data (), size, "qAttached:%x", pid);
2446 else
2447 xsnprintf (rs->buf.data (), size, "qAttached");
2449 putpkt (rs->buf);
2450 getpkt (&rs->buf, 0);
2452 switch (packet_ok (rs->buf,
2453 &remote_protocol_packets[PACKET_qAttached]))
2455 case PACKET_OK:
2456 if (strcmp (rs->buf.data (), "1") == 0)
2457 return 1;
2458 break;
2459 case PACKET_ERROR:
2460 warning (_("Remote failure reply: %s"), rs->buf.data ());
2461 break;
2462 case PACKET_UNKNOWN:
2463 break;
2466 return 0;
2469 /* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
2470 has been invented by GDB, instead of reported by the target. Since
2471 we can be connected to a remote system before before knowing about
2472 any inferior, mark the target with execution when we find the first
2473 inferior. If ATTACHED is 1, then we had just attached to this
2474 inferior. If it is 0, then we just created this inferior. If it
2475 is -1, then try querying the remote stub to find out if it had
2476 attached to the inferior or not. If TRY_OPEN_EXEC is true then
2477 attempt to open this inferior's executable as the main executable
2478 if no main executable is open already. */
2480 inferior *
2481 remote_target::remote_add_inferior (bool fake_pid_p, int pid, int attached,
2482 int try_open_exec)
2484 struct inferior *inf;
2486 /* Check whether this process we're learning about is to be
2487 considered attached, or if is to be considered to have been
2488 spawned by the stub. */
2489 if (attached == -1)
2490 attached = remote_query_attached (pid);
2492 if (gdbarch_has_global_solist (target_gdbarch ()))
2494 /* If the target shares code across all inferiors, then every
2495 attach adds a new inferior. */
2496 inf = add_inferior (pid);
2498 /* ... and every inferior is bound to the same program space.
2499 However, each inferior may still have its own address
2500 space. */
2501 inf->aspace = maybe_new_address_space ();
2502 inf->pspace = current_program_space;
2504 else
2506 /* In the traditional debugging scenario, there's a 1-1 match
2507 between program/address spaces. We simply bind the inferior
2508 to the program space's address space. */
2509 inf = current_inferior ();
2511 /* However, if the current inferior is already bound to a
2512 process, find some other empty inferior. */
2513 if (inf->pid != 0)
2515 inf = nullptr;
2516 for (inferior *it : all_inferiors ())
2517 if (it->pid == 0)
2519 inf = it;
2520 break;
2523 if (inf == nullptr)
2525 /* Since all inferiors were already bound to a process, add
2526 a new inferior. */
2527 inf = add_inferior_with_spaces ();
2529 switch_to_inferior_no_thread (inf);
2530 inf->push_target (this);
2531 inferior_appeared (inf, pid);
2534 inf->attach_flag = attached;
2535 inf->fake_pid_p = fake_pid_p;
2537 /* If no main executable is currently open then attempt to
2538 open the file that was executed to create this inferior. */
2539 if (try_open_exec && get_exec_file (0) == NULL)
2540 exec_file_locate_attach (pid, 0, 1);
2542 /* Check for exec file mismatch, and let the user solve it. */
2543 validate_exec_file (1);
2545 return inf;
2548 static remote_thread_info *get_remote_thread_info (thread_info *thread);
2549 static remote_thread_info *get_remote_thread_info (remote_target *target,
2550 ptid_t ptid);
2552 /* Add thread PTID to GDB's thread list. Tag it as executing/running
2553 according to EXECUTING and RUNNING respectively. If SILENT_P (or the
2554 remote_state::starting_up flag) is true then the new thread is added
2555 silently, otherwise the new thread will be announced to the user. */
2557 thread_info *
2558 remote_target::remote_add_thread (ptid_t ptid, bool running, bool executing,
2559 bool silent_p)
2561 struct remote_state *rs = get_remote_state ();
2562 struct thread_info *thread;
2564 /* GDB historically didn't pull threads in the initial connection
2565 setup. If the remote target doesn't even have a concept of
2566 threads (e.g., a bare-metal target), even if internally we
2567 consider that a single-threaded target, mentioning a new thread
2568 might be confusing to the user. Be silent then, preserving the
2569 age old behavior. */
2570 if (rs->starting_up || silent_p)
2571 thread = add_thread_silent (this, ptid);
2572 else
2573 thread = add_thread (this, ptid);
2575 /* We start by assuming threads are resumed. That state then gets updated
2576 when we process a matching stop reply. */
2577 get_remote_thread_info (thread)->set_resumed ();
2579 set_executing (this, ptid, executing);
2580 set_running (this, ptid, running);
2582 return thread;
2585 /* Come here when we learn about a thread id from the remote target.
2586 It may be the first time we hear about such thread, so take the
2587 opportunity to add it to GDB's thread list. In case this is the
2588 first time we're noticing its corresponding inferior, add it to
2589 GDB's inferior list as well. EXECUTING indicates whether the
2590 thread is (internally) executing or stopped. */
2592 void
2593 remote_target::remote_notice_new_inferior (ptid_t currthread, bool executing)
2595 /* In non-stop mode, we assume new found threads are (externally)
2596 running until proven otherwise with a stop reply. In all-stop,
2597 we can only get here if all threads are stopped. */
2598 bool running = target_is_non_stop_p ();
2600 /* If this is a new thread, add it to GDB's thread list.
2601 If we leave it up to WFI to do this, bad things will happen. */
2603 thread_info *tp = find_thread_ptid (this, currthread);
2604 if (tp != NULL && tp->state == THREAD_EXITED)
2606 /* We're seeing an event on a thread id we knew had exited.
2607 This has to be a new thread reusing the old id. Add it. */
2608 remote_add_thread (currthread, running, executing, false);
2609 return;
2612 if (!in_thread_list (this, currthread))
2614 struct inferior *inf = NULL;
2615 int pid = currthread.pid ();
2617 if (inferior_ptid.is_pid ()
2618 && pid == inferior_ptid.pid ())
2620 /* inferior_ptid has no thread member yet. This can happen
2621 with the vAttach -> remote_wait,"TAAthread:" path if the
2622 stub doesn't support qC. This is the first stop reported
2623 after an attach, so this is the main thread. Update the
2624 ptid in the thread list. */
2625 if (in_thread_list (this, ptid_t (pid)))
2626 thread_change_ptid (this, inferior_ptid, currthread);
2627 else
2629 thread_info *thr
2630 = remote_add_thread (currthread, running, executing, false);
2631 switch_to_thread (thr);
2633 return;
2636 if (magic_null_ptid == inferior_ptid)
2638 /* inferior_ptid is not set yet. This can happen with the
2639 vRun -> remote_wait,"TAAthread:" path if the stub
2640 doesn't support qC. This is the first stop reported
2641 after an attach, so this is the main thread. Update the
2642 ptid in the thread list. */
2643 thread_change_ptid (this, inferior_ptid, currthread);
2644 return;
2647 /* When connecting to a target remote, or to a target
2648 extended-remote which already was debugging an inferior, we
2649 may not know about it yet. Add it before adding its child
2650 thread, so notifications are emitted in a sensible order. */
2651 if (find_inferior_pid (this, currthread.pid ()) == NULL)
2653 struct remote_state *rs = get_remote_state ();
2654 bool fake_pid_p = !remote_multi_process_p (rs);
2656 inf = remote_add_inferior (fake_pid_p,
2657 currthread.pid (), -1, 1);
2660 /* This is really a new thread. Add it. */
2661 thread_info *new_thr
2662 = remote_add_thread (currthread, running, executing, false);
2664 /* If we found a new inferior, let the common code do whatever
2665 it needs to with it (e.g., read shared libraries, insert
2666 breakpoints), unless we're just setting up an all-stop
2667 connection. */
2668 if (inf != NULL)
2670 struct remote_state *rs = get_remote_state ();
2672 if (!rs->starting_up)
2673 notice_new_inferior (new_thr, executing, 0);
2678 /* Return THREAD's private thread data, creating it if necessary. */
2680 static remote_thread_info *
2681 get_remote_thread_info (thread_info *thread)
2683 gdb_assert (thread != NULL);
2685 if (thread->priv == NULL)
2686 thread->priv.reset (new remote_thread_info);
2688 return static_cast<remote_thread_info *> (thread->priv.get ());
2691 /* Return PTID's private thread data, creating it if necessary. */
2693 static remote_thread_info *
2694 get_remote_thread_info (remote_target *target, ptid_t ptid)
2696 thread_info *thr = find_thread_ptid (target, ptid);
2697 return get_remote_thread_info (thr);
2700 /* Call this function as a result of
2701 1) A halt indication (T packet) containing a thread id
2702 2) A direct query of currthread
2703 3) Successful execution of set thread */
2705 static void
2706 record_currthread (struct remote_state *rs, ptid_t currthread)
2708 rs->general_thread = currthread;
2711 /* If 'QPassSignals' is supported, tell the remote stub what signals
2712 it can simply pass through to the inferior without reporting. */
2714 void
2715 remote_target::pass_signals (gdb::array_view<const unsigned char> pass_signals)
2717 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
2719 char *pass_packet, *p;
2720 int count = 0;
2721 struct remote_state *rs = get_remote_state ();
2723 gdb_assert (pass_signals.size () < 256);
2724 for (size_t i = 0; i < pass_signals.size (); i++)
2726 if (pass_signals[i])
2727 count++;
2729 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
2730 strcpy (pass_packet, "QPassSignals:");
2731 p = pass_packet + strlen (pass_packet);
2732 for (size_t i = 0; i < pass_signals.size (); i++)
2734 if (pass_signals[i])
2736 if (i >= 16)
2737 *p++ = tohex (i >> 4);
2738 *p++ = tohex (i & 15);
2739 if (count)
2740 *p++ = ';';
2741 else
2742 break;
2743 count--;
2746 *p = 0;
2747 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
2749 putpkt (pass_packet);
2750 getpkt (&rs->buf, 0);
2751 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
2752 xfree (rs->last_pass_packet);
2753 rs->last_pass_packet = pass_packet;
2755 else
2756 xfree (pass_packet);
2760 /* If 'QCatchSyscalls' is supported, tell the remote stub
2761 to report syscalls to GDB. */
2764 remote_target::set_syscall_catchpoint (int pid, bool needed, int any_count,
2765 gdb::array_view<const int> syscall_counts)
2767 const char *catch_packet;
2768 enum packet_result result;
2769 int n_sysno = 0;
2771 if (packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2773 /* Not supported. */
2774 return 1;
2777 if (needed && any_count == 0)
2779 /* Count how many syscalls are to be caught. */
2780 for (size_t i = 0; i < syscall_counts.size (); i++)
2782 if (syscall_counts[i] != 0)
2783 n_sysno++;
2787 remote_debug_printf ("pid %d needed %d any_count %d n_sysno %d",
2788 pid, needed, any_count, n_sysno);
2790 std::string built_packet;
2791 if (needed)
2793 /* Prepare a packet with the sysno list, assuming max 8+1
2794 characters for a sysno. If the resulting packet size is too
2795 big, fallback on the non-selective packet. */
2796 const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
2797 built_packet.reserve (maxpktsz);
2798 built_packet = "QCatchSyscalls:1";
2799 if (any_count == 0)
2801 /* Add in each syscall to be caught. */
2802 for (size_t i = 0; i < syscall_counts.size (); i++)
2804 if (syscall_counts[i] != 0)
2805 string_appendf (built_packet, ";%zx", i);
2808 if (built_packet.size () > get_remote_packet_size ())
2810 /* catch_packet too big. Fallback to less efficient
2811 non selective mode, with GDB doing the filtering. */
2812 catch_packet = "QCatchSyscalls:1";
2814 else
2815 catch_packet = built_packet.c_str ();
2817 else
2818 catch_packet = "QCatchSyscalls:0";
2820 struct remote_state *rs = get_remote_state ();
2822 putpkt (catch_packet);
2823 getpkt (&rs->buf, 0);
2824 result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_QCatchSyscalls]);
2825 if (result == PACKET_OK)
2826 return 0;
2827 else
2828 return -1;
2831 /* If 'QProgramSignals' is supported, tell the remote stub what
2832 signals it should pass through to the inferior when detaching. */
2834 void
2835 remote_target::program_signals (gdb::array_view<const unsigned char> signals)
2837 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
2839 char *packet, *p;
2840 int count = 0;
2841 struct remote_state *rs = get_remote_state ();
2843 gdb_assert (signals.size () < 256);
2844 for (size_t i = 0; i < signals.size (); i++)
2846 if (signals[i])
2847 count++;
2849 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
2850 strcpy (packet, "QProgramSignals:");
2851 p = packet + strlen (packet);
2852 for (size_t i = 0; i < signals.size (); i++)
2854 if (signal_pass_state (i))
2856 if (i >= 16)
2857 *p++ = tohex (i >> 4);
2858 *p++ = tohex (i & 15);
2859 if (count)
2860 *p++ = ';';
2861 else
2862 break;
2863 count--;
2866 *p = 0;
2867 if (!rs->last_program_signals_packet
2868 || strcmp (rs->last_program_signals_packet, packet) != 0)
2870 putpkt (packet);
2871 getpkt (&rs->buf, 0);
2872 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
2873 xfree (rs->last_program_signals_packet);
2874 rs->last_program_signals_packet = packet;
2876 else
2877 xfree (packet);
2881 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
2882 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2883 thread. If GEN is set, set the general thread, if not, then set
2884 the step/continue thread. */
2885 void
2886 remote_target::set_thread (ptid_t ptid, int gen)
2888 struct remote_state *rs = get_remote_state ();
2889 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
2890 char *buf = rs->buf.data ();
2891 char *endbuf = buf + get_remote_packet_size ();
2893 if (state == ptid)
2894 return;
2896 *buf++ = 'H';
2897 *buf++ = gen ? 'g' : 'c';
2898 if (ptid == magic_null_ptid)
2899 xsnprintf (buf, endbuf - buf, "0");
2900 else if (ptid == any_thread_ptid)
2901 xsnprintf (buf, endbuf - buf, "0");
2902 else if (ptid == minus_one_ptid)
2903 xsnprintf (buf, endbuf - buf, "-1");
2904 else
2905 write_ptid (buf, endbuf, ptid);
2906 putpkt (rs->buf);
2907 getpkt (&rs->buf, 0);
2908 if (gen)
2909 rs->general_thread = ptid;
2910 else
2911 rs->continue_thread = ptid;
2914 void
2915 remote_target::set_general_thread (ptid_t ptid)
2917 set_thread (ptid, 1);
2920 void
2921 remote_target::set_continue_thread (ptid_t ptid)
2923 set_thread (ptid, 0);
2926 /* Change the remote current process. Which thread within the process
2927 ends up selected isn't important, as long as it is the same process
2928 as what INFERIOR_PTID points to.
2930 This comes from that fact that there is no explicit notion of
2931 "selected process" in the protocol. The selected process for
2932 general operations is the process the selected general thread
2933 belongs to. */
2935 void
2936 remote_target::set_general_process ()
2938 struct remote_state *rs = get_remote_state ();
2940 /* If the remote can't handle multiple processes, don't bother. */
2941 if (!remote_multi_process_p (rs))
2942 return;
2944 /* We only need to change the remote current thread if it's pointing
2945 at some other process. */
2946 if (rs->general_thread.pid () != inferior_ptid.pid ())
2947 set_general_thread (inferior_ptid);
2951 /* Return nonzero if this is the main thread that we made up ourselves
2952 to model non-threaded targets as single-threaded. */
2954 static int
2955 remote_thread_always_alive (ptid_t ptid)
2957 if (ptid == magic_null_ptid)
2958 /* The main thread is always alive. */
2959 return 1;
2961 if (ptid.pid () != 0 && ptid.lwp () == 0)
2962 /* The main thread is always alive. This can happen after a
2963 vAttach, if the remote side doesn't support
2964 multi-threading. */
2965 return 1;
2967 return 0;
2970 /* Return nonzero if the thread PTID is still alive on the remote
2971 system. */
2973 bool
2974 remote_target::thread_alive (ptid_t ptid)
2976 struct remote_state *rs = get_remote_state ();
2977 char *p, *endp;
2979 /* Check if this is a thread that we made up ourselves to model
2980 non-threaded targets as single-threaded. */
2981 if (remote_thread_always_alive (ptid))
2982 return 1;
2984 p = rs->buf.data ();
2985 endp = p + get_remote_packet_size ();
2987 *p++ = 'T';
2988 write_ptid (p, endp, ptid);
2990 putpkt (rs->buf);
2991 getpkt (&rs->buf, 0);
2992 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
2995 /* Return a pointer to a thread name if we know it and NULL otherwise.
2996 The thread_info object owns the memory for the name. */
2998 const char *
2999 remote_target::thread_name (struct thread_info *info)
3001 if (info->priv != NULL)
3003 const std::string &name = get_remote_thread_info (info)->name;
3004 return !name.empty () ? name.c_str () : NULL;
3007 return NULL;
3010 /* About these extended threadlist and threadinfo packets. They are
3011 variable length packets but, the fields within them are often fixed
3012 length. They are redundant enough to send over UDP as is the
3013 remote protocol in general. There is a matching unit test module
3014 in libstub. */
3016 /* WARNING: This threadref data structure comes from the remote O.S.,
3017 libstub protocol encoding, and remote.c. It is not particularly
3018 changable. */
3020 /* Right now, the internal structure is int. We want it to be bigger.
3021 Plan to fix this. */
3023 typedef int gdb_threadref; /* Internal GDB thread reference. */
3025 /* gdb_ext_thread_info is an internal GDB data structure which is
3026 equivalent to the reply of the remote threadinfo packet. */
3028 struct gdb_ext_thread_info
3030 threadref threadid; /* External form of thread reference. */
3031 int active; /* Has state interesting to GDB?
3032 regs, stack. */
3033 char display[256]; /* Brief state display, name,
3034 blocked/suspended. */
3035 char shortname[32]; /* To be used to name threads. */
3036 char more_display[256]; /* Long info, statistics, queue depth,
3037 whatever. */
3040 /* The volume of remote transfers can be limited by submitting
3041 a mask containing bits specifying the desired information.
3042 Use a union of these values as the 'selection' parameter to
3043 get_thread_info. FIXME: Make these TAG names more thread specific. */
3045 #define TAG_THREADID 1
3046 #define TAG_EXISTS 2
3047 #define TAG_DISPLAY 4
3048 #define TAG_THREADNAME 8
3049 #define TAG_MOREDISPLAY 16
3051 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
3053 static const char *unpack_nibble (const char *buf, int *val);
3055 static const char *unpack_byte (const char *buf, int *value);
3057 static char *pack_int (char *buf, int value);
3059 static const char *unpack_int (const char *buf, int *value);
3061 static const char *unpack_string (const char *src, char *dest, int length);
3063 static char *pack_threadid (char *pkt, threadref *id);
3065 static const char *unpack_threadid (const char *inbuf, threadref *id);
3067 void int_to_threadref (threadref *id, int value);
3069 static int threadref_to_int (threadref *ref);
3071 static void copy_threadref (threadref *dest, threadref *src);
3073 static int threadmatch (threadref *dest, threadref *src);
3075 static char *pack_threadinfo_request (char *pkt, int mode,
3076 threadref *id);
3078 static char *pack_threadlist_request (char *pkt, int startflag,
3079 int threadcount,
3080 threadref *nextthread);
3082 static int remote_newthread_step (threadref *ref, void *context);
3085 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
3086 buffer we're allowed to write to. Returns
3087 BUF+CHARACTERS_WRITTEN. */
3089 char *
3090 remote_target::write_ptid (char *buf, const char *endbuf, ptid_t ptid)
3092 int pid, tid;
3093 struct remote_state *rs = get_remote_state ();
3095 if (remote_multi_process_p (rs))
3097 pid = ptid.pid ();
3098 if (pid < 0)
3099 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
3100 else
3101 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
3103 tid = ptid.lwp ();
3104 if (tid < 0)
3105 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
3106 else
3107 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
3109 return buf;
3112 /* Extract a PTID from BUF. If non-null, OBUF is set to one past the
3113 last parsed char. Returns null_ptid if no thread id is found, and
3114 throws an error if the thread id has an invalid format. */
3116 static ptid_t
3117 read_ptid (const char *buf, const char **obuf)
3119 const char *p = buf;
3120 const char *pp;
3121 ULONGEST pid = 0, tid = 0;
3123 if (*p == 'p')
3125 /* Multi-process ptid. */
3126 pp = unpack_varlen_hex (p + 1, &pid);
3127 if (*pp != '.')
3128 error (_("invalid remote ptid: %s"), p);
3130 p = pp;
3131 pp = unpack_varlen_hex (p + 1, &tid);
3132 if (obuf)
3133 *obuf = pp;
3134 return ptid_t (pid, tid);
3137 /* No multi-process. Just a tid. */
3138 pp = unpack_varlen_hex (p, &tid);
3140 /* Return null_ptid when no thread id is found. */
3141 if (p == pp)
3143 if (obuf)
3144 *obuf = pp;
3145 return null_ptid;
3148 /* Since the stub is not sending a process id, default to what's
3149 current_inferior, unless it doesn't have a PID yet. If so,
3150 then since there's no way to know the pid of the reported
3151 threads, use the magic number. */
3152 inferior *inf = current_inferior ();
3153 if (inf->pid == 0)
3154 pid = magic_null_ptid.pid ();
3155 else
3156 pid = inf->pid;
3158 if (obuf)
3159 *obuf = pp;
3160 return ptid_t (pid, tid);
3163 static int
3164 stubhex (int ch)
3166 if (ch >= 'a' && ch <= 'f')
3167 return ch - 'a' + 10;
3168 if (ch >= '0' && ch <= '9')
3169 return ch - '0';
3170 if (ch >= 'A' && ch <= 'F')
3171 return ch - 'A' + 10;
3172 return -1;
3175 static int
3176 stub_unpack_int (const char *buff, int fieldlength)
3178 int nibble;
3179 int retval = 0;
3181 while (fieldlength)
3183 nibble = stubhex (*buff++);
3184 retval |= nibble;
3185 fieldlength--;
3186 if (fieldlength)
3187 retval = retval << 4;
3189 return retval;
3192 static const char *
3193 unpack_nibble (const char *buf, int *val)
3195 *val = fromhex (*buf++);
3196 return buf;
3199 static const char *
3200 unpack_byte (const char *buf, int *value)
3202 *value = stub_unpack_int (buf, 2);
3203 return buf + 2;
3206 static char *
3207 pack_int (char *buf, int value)
3209 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
3210 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
3211 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
3212 buf = pack_hex_byte (buf, (value & 0xff));
3213 return buf;
3216 static const char *
3217 unpack_int (const char *buf, int *value)
3219 *value = stub_unpack_int (buf, 8);
3220 return buf + 8;
3223 #if 0 /* Currently unused, uncomment when needed. */
3224 static char *pack_string (char *pkt, char *string);
3226 static char *
3227 pack_string (char *pkt, char *string)
3229 char ch;
3230 int len;
3232 len = strlen (string);
3233 if (len > 200)
3234 len = 200; /* Bigger than most GDB packets, junk??? */
3235 pkt = pack_hex_byte (pkt, len);
3236 while (len-- > 0)
3238 ch = *string++;
3239 if ((ch == '\0') || (ch == '#'))
3240 ch = '*'; /* Protect encapsulation. */
3241 *pkt++ = ch;
3243 return pkt;
3245 #endif /* 0 (unused) */
3247 static const char *
3248 unpack_string (const char *src, char *dest, int length)
3250 while (length--)
3251 *dest++ = *src++;
3252 *dest = '\0';
3253 return src;
3256 static char *
3257 pack_threadid (char *pkt, threadref *id)
3259 char *limit;
3260 unsigned char *altid;
3262 altid = (unsigned char *) id;
3263 limit = pkt + BUF_THREAD_ID_SIZE;
3264 while (pkt < limit)
3265 pkt = pack_hex_byte (pkt, *altid++);
3266 return pkt;
3270 static const char *
3271 unpack_threadid (const char *inbuf, threadref *id)
3273 char *altref;
3274 const char *limit = inbuf + BUF_THREAD_ID_SIZE;
3275 int x, y;
3277 altref = (char *) id;
3279 while (inbuf < limit)
3281 x = stubhex (*inbuf++);
3282 y = stubhex (*inbuf++);
3283 *altref++ = (x << 4) | y;
3285 return inbuf;
3288 /* Externally, threadrefs are 64 bits but internally, they are still
3289 ints. This is due to a mismatch of specifications. We would like
3290 to use 64bit thread references internally. This is an adapter
3291 function. */
3293 void
3294 int_to_threadref (threadref *id, int value)
3296 unsigned char *scan;
3298 scan = (unsigned char *) id;
3300 int i = 4;
3301 while (i--)
3302 *scan++ = 0;
3304 *scan++ = (value >> 24) & 0xff;
3305 *scan++ = (value >> 16) & 0xff;
3306 *scan++ = (value >> 8) & 0xff;
3307 *scan++ = (value & 0xff);
3310 static int
3311 threadref_to_int (threadref *ref)
3313 int i, value = 0;
3314 unsigned char *scan;
3316 scan = *ref;
3317 scan += 4;
3318 i = 4;
3319 while (i-- > 0)
3320 value = (value << 8) | ((*scan++) & 0xff);
3321 return value;
3324 static void
3325 copy_threadref (threadref *dest, threadref *src)
3327 int i;
3328 unsigned char *csrc, *cdest;
3330 csrc = (unsigned char *) src;
3331 cdest = (unsigned char *) dest;
3332 i = 8;
3333 while (i--)
3334 *cdest++ = *csrc++;
3337 static int
3338 threadmatch (threadref *dest, threadref *src)
3340 /* Things are broken right now, so just assume we got a match. */
3341 #if 0
3342 unsigned char *srcp, *destp;
3343 int i, result;
3344 srcp = (char *) src;
3345 destp = (char *) dest;
3347 result = 1;
3348 while (i-- > 0)
3349 result &= (*srcp++ == *destp++) ? 1 : 0;
3350 return result;
3351 #endif
3352 return 1;
3356 threadid:1, # always request threadid
3357 context_exists:2,
3358 display:4,
3359 unique_name:8,
3360 more_display:16
3363 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
3365 static char *
3366 pack_threadinfo_request (char *pkt, int mode, threadref *id)
3368 *pkt++ = 'q'; /* Info Query */
3369 *pkt++ = 'P'; /* process or thread info */
3370 pkt = pack_int (pkt, mode); /* mode */
3371 pkt = pack_threadid (pkt, id); /* threadid */
3372 *pkt = '\0'; /* terminate */
3373 return pkt;
3376 /* These values tag the fields in a thread info response packet. */
3377 /* Tagging the fields allows us to request specific fields and to
3378 add more fields as time goes by. */
3380 #define TAG_THREADID 1 /* Echo the thread identifier. */
3381 #define TAG_EXISTS 2 /* Is this process defined enough to
3382 fetch registers and its stack? */
3383 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
3384 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
3385 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
3386 the process. */
3389 remote_target::remote_unpack_thread_info_response (const char *pkt,
3390 threadref *expectedref,
3391 gdb_ext_thread_info *info)
3393 struct remote_state *rs = get_remote_state ();
3394 int mask, length;
3395 int tag;
3396 threadref ref;
3397 const char *limit = pkt + rs->buf.size (); /* Plausible parsing limit. */
3398 int retval = 1;
3400 /* info->threadid = 0; FIXME: implement zero_threadref. */
3401 info->active = 0;
3402 info->display[0] = '\0';
3403 info->shortname[0] = '\0';
3404 info->more_display[0] = '\0';
3406 /* Assume the characters indicating the packet type have been
3407 stripped. */
3408 pkt = unpack_int (pkt, &mask); /* arg mask */
3409 pkt = unpack_threadid (pkt, &ref);
3411 if (mask == 0)
3412 warning (_("Incomplete response to threadinfo request."));
3413 if (!threadmatch (&ref, expectedref))
3414 { /* This is an answer to a different request. */
3415 warning (_("ERROR RMT Thread info mismatch."));
3416 return 0;
3418 copy_threadref (&info->threadid, &ref);
3420 /* Loop on tagged fields , try to bail if something goes wrong. */
3422 /* Packets are terminated with nulls. */
3423 while ((pkt < limit) && mask && *pkt)
3425 pkt = unpack_int (pkt, &tag); /* tag */
3426 pkt = unpack_byte (pkt, &length); /* length */
3427 if (!(tag & mask)) /* Tags out of synch with mask. */
3429 warning (_("ERROR RMT: threadinfo tag mismatch."));
3430 retval = 0;
3431 break;
3433 if (tag == TAG_THREADID)
3435 if (length != 16)
3437 warning (_("ERROR RMT: length of threadid is not 16."));
3438 retval = 0;
3439 break;
3441 pkt = unpack_threadid (pkt, &ref);
3442 mask = mask & ~TAG_THREADID;
3443 continue;
3445 if (tag == TAG_EXISTS)
3447 info->active = stub_unpack_int (pkt, length);
3448 pkt += length;
3449 mask = mask & ~(TAG_EXISTS);
3450 if (length > 8)
3452 warning (_("ERROR RMT: 'exists' length too long."));
3453 retval = 0;
3454 break;
3456 continue;
3458 if (tag == TAG_THREADNAME)
3460 pkt = unpack_string (pkt, &info->shortname[0], length);
3461 mask = mask & ~TAG_THREADNAME;
3462 continue;
3464 if (tag == TAG_DISPLAY)
3466 pkt = unpack_string (pkt, &info->display[0], length);
3467 mask = mask & ~TAG_DISPLAY;
3468 continue;
3470 if (tag == TAG_MOREDISPLAY)
3472 pkt = unpack_string (pkt, &info->more_display[0], length);
3473 mask = mask & ~TAG_MOREDISPLAY;
3474 continue;
3476 warning (_("ERROR RMT: unknown thread info tag."));
3477 break; /* Not a tag we know about. */
3479 return retval;
3483 remote_target::remote_get_threadinfo (threadref *threadid,
3484 int fieldset,
3485 gdb_ext_thread_info *info)
3487 struct remote_state *rs = get_remote_state ();
3488 int result;
3490 pack_threadinfo_request (rs->buf.data (), fieldset, threadid);
3491 putpkt (rs->buf);
3492 getpkt (&rs->buf, 0);
3494 if (rs->buf[0] == '\0')
3495 return 0;
3497 result = remote_unpack_thread_info_response (&rs->buf[2],
3498 threadid, info);
3499 return result;
3502 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
3504 static char *
3505 pack_threadlist_request (char *pkt, int startflag, int threadcount,
3506 threadref *nextthread)
3508 *pkt++ = 'q'; /* info query packet */
3509 *pkt++ = 'L'; /* Process LIST or threadLIST request */
3510 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
3511 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
3512 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
3513 *pkt = '\0';
3514 return pkt;
3517 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
3520 remote_target::parse_threadlist_response (const char *pkt, int result_limit,
3521 threadref *original_echo,
3522 threadref *resultlist,
3523 int *doneflag)
3525 struct remote_state *rs = get_remote_state ();
3526 int count, resultcount, done;
3528 resultcount = 0;
3529 /* Assume the 'q' and 'M chars have been stripped. */
3530 const char *limit = pkt + (rs->buf.size () - BUF_THREAD_ID_SIZE);
3531 /* done parse past here */
3532 pkt = unpack_byte (pkt, &count); /* count field */
3533 pkt = unpack_nibble (pkt, &done);
3534 /* The first threadid is the argument threadid. */
3535 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
3536 while ((count-- > 0) && (pkt < limit))
3538 pkt = unpack_threadid (pkt, resultlist++);
3539 if (resultcount++ >= result_limit)
3540 break;
3542 if (doneflag)
3543 *doneflag = done;
3544 return resultcount;
3547 /* Fetch the next batch of threads from the remote. Returns -1 if the
3548 qL packet is not supported, 0 on error and 1 on success. */
3551 remote_target::remote_get_threadlist (int startflag, threadref *nextthread,
3552 int result_limit, int *done, int *result_count,
3553 threadref *threadlist)
3555 struct remote_state *rs = get_remote_state ();
3556 int result = 1;
3558 /* Truncate result limit to be smaller than the packet size. */
3559 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
3560 >= get_remote_packet_size ())
3561 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
3563 pack_threadlist_request (rs->buf.data (), startflag, result_limit,
3564 nextthread);
3565 putpkt (rs->buf);
3566 getpkt (&rs->buf, 0);
3567 if (rs->buf[0] == '\0')
3569 /* Packet not supported. */
3570 return -1;
3573 *result_count =
3574 parse_threadlist_response (&rs->buf[2], result_limit,
3575 &rs->echo_nextthread, threadlist, done);
3577 if (!threadmatch (&rs->echo_nextthread, nextthread))
3579 /* FIXME: This is a good reason to drop the packet. */
3580 /* Possibly, there is a duplicate response. */
3581 /* Possibilities :
3582 retransmit immediatly - race conditions
3583 retransmit after timeout - yes
3584 exit
3585 wait for packet, then exit
3587 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
3588 return 0; /* I choose simply exiting. */
3590 if (*result_count <= 0)
3592 if (*done != 1)
3594 warning (_("RMT ERROR : failed to get remote thread list."));
3595 result = 0;
3597 return result; /* break; */
3599 if (*result_count > result_limit)
3601 *result_count = 0;
3602 warning (_("RMT ERROR: threadlist response longer than requested."));
3603 return 0;
3605 return result;
3608 /* Fetch the list of remote threads, with the qL packet, and call
3609 STEPFUNCTION for each thread found. Stops iterating and returns 1
3610 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
3611 STEPFUNCTION returns false. If the packet is not supported,
3612 returns -1. */
3615 remote_target::remote_threadlist_iterator (rmt_thread_action stepfunction,
3616 void *context, int looplimit)
3618 struct remote_state *rs = get_remote_state ();
3619 int done, i, result_count;
3620 int startflag = 1;
3621 int result = 1;
3622 int loopcount = 0;
3624 done = 0;
3625 while (!done)
3627 if (loopcount++ > looplimit)
3629 result = 0;
3630 warning (_("Remote fetch threadlist -infinite loop-."));
3631 break;
3633 result = remote_get_threadlist (startflag, &rs->nextthread,
3634 MAXTHREADLISTRESULTS,
3635 &done, &result_count,
3636 rs->resultthreadlist);
3637 if (result <= 0)
3638 break;
3639 /* Clear for later iterations. */
3640 startflag = 0;
3641 /* Setup to resume next batch of thread references, set nextthread. */
3642 if (result_count >= 1)
3643 copy_threadref (&rs->nextthread,
3644 &rs->resultthreadlist[result_count - 1]);
3645 i = 0;
3646 while (result_count--)
3648 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
3650 result = 0;
3651 break;
3655 return result;
3658 /* A thread found on the remote target. */
3660 struct thread_item
3662 explicit thread_item (ptid_t ptid_)
3663 : ptid (ptid_)
3666 thread_item (thread_item &&other) = default;
3667 thread_item &operator= (thread_item &&other) = default;
3669 DISABLE_COPY_AND_ASSIGN (thread_item);
3671 /* The thread's PTID. */
3672 ptid_t ptid;
3674 /* The thread's extra info. */
3675 std::string extra;
3677 /* The thread's name. */
3678 std::string name;
3680 /* The core the thread was running on. -1 if not known. */
3681 int core = -1;
3683 /* The thread handle associated with the thread. */
3684 gdb::byte_vector thread_handle;
3687 /* Context passed around to the various methods listing remote
3688 threads. As new threads are found, they're added to the ITEMS
3689 vector. */
3691 struct threads_listing_context
3693 /* Return true if this object contains an entry for a thread with ptid
3694 PTID. */
3696 bool contains_thread (ptid_t ptid) const
3698 auto match_ptid = [&] (const thread_item &item)
3700 return item.ptid == ptid;
3703 auto it = std::find_if (this->items.begin (),
3704 this->items.end (),
3705 match_ptid);
3707 return it != this->items.end ();
3710 /* Remove the thread with ptid PTID. */
3712 void remove_thread (ptid_t ptid)
3714 auto match_ptid = [&] (const thread_item &item)
3716 return item.ptid == ptid;
3719 auto it = std::remove_if (this->items.begin (),
3720 this->items.end (),
3721 match_ptid);
3723 if (it != this->items.end ())
3724 this->items.erase (it);
3727 /* The threads found on the remote target. */
3728 std::vector<thread_item> items;
3731 static int
3732 remote_newthread_step (threadref *ref, void *data)
3734 struct threads_listing_context *context
3735 = (struct threads_listing_context *) data;
3736 int pid = inferior_ptid.pid ();
3737 int lwp = threadref_to_int (ref);
3738 ptid_t ptid (pid, lwp);
3740 context->items.emplace_back (ptid);
3742 return 1; /* continue iterator */
3745 #define CRAZY_MAX_THREADS 1000
3747 ptid_t
3748 remote_target::remote_current_thread (ptid_t oldpid)
3750 struct remote_state *rs = get_remote_state ();
3752 putpkt ("qC");
3753 getpkt (&rs->buf, 0);
3754 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
3756 const char *obuf;
3757 ptid_t result;
3759 result = read_ptid (&rs->buf[2], &obuf);
3760 if (*obuf != '\0')
3761 remote_debug_printf ("warning: garbage in qC reply");
3763 return result;
3765 else
3766 return oldpid;
3769 /* List remote threads using the deprecated qL packet. */
3772 remote_target::remote_get_threads_with_ql (threads_listing_context *context)
3774 if (remote_threadlist_iterator (remote_newthread_step, context,
3775 CRAZY_MAX_THREADS) >= 0)
3776 return 1;
3778 return 0;
3781 #if defined(HAVE_LIBEXPAT)
3783 static void
3784 start_thread (struct gdb_xml_parser *parser,
3785 const struct gdb_xml_element *element,
3786 void *user_data,
3787 std::vector<gdb_xml_value> &attributes)
3789 struct threads_listing_context *data
3790 = (struct threads_listing_context *) user_data;
3791 struct gdb_xml_value *attr;
3793 char *id = (char *) xml_find_attribute (attributes, "id")->value.get ();
3794 ptid_t ptid = read_ptid (id, NULL);
3796 data->items.emplace_back (ptid);
3797 thread_item &item = data->items.back ();
3799 attr = xml_find_attribute (attributes, "core");
3800 if (attr != NULL)
3801 item.core = *(ULONGEST *) attr->value.get ();
3803 attr = xml_find_attribute (attributes, "name");
3804 if (attr != NULL)
3805 item.name = (const char *) attr->value.get ();
3807 attr = xml_find_attribute (attributes, "handle");
3808 if (attr != NULL)
3809 item.thread_handle = hex2bin ((const char *) attr->value.get ());
3812 static void
3813 end_thread (struct gdb_xml_parser *parser,
3814 const struct gdb_xml_element *element,
3815 void *user_data, const char *body_text)
3817 struct threads_listing_context *data
3818 = (struct threads_listing_context *) user_data;
3820 if (body_text != NULL && *body_text != '\0')
3821 data->items.back ().extra = body_text;
3824 const struct gdb_xml_attribute thread_attributes[] = {
3825 { "id", GDB_XML_AF_NONE, NULL, NULL },
3826 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
3827 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
3828 { "handle", GDB_XML_AF_OPTIONAL, NULL, NULL },
3829 { NULL, GDB_XML_AF_NONE, NULL, NULL }
3832 const struct gdb_xml_element thread_children[] = {
3833 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3836 const struct gdb_xml_element threads_children[] = {
3837 { "thread", thread_attributes, thread_children,
3838 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3839 start_thread, end_thread },
3840 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3843 const struct gdb_xml_element threads_elements[] = {
3844 { "threads", NULL, threads_children,
3845 GDB_XML_EF_NONE, NULL, NULL },
3846 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3849 #endif
3851 /* List remote threads using qXfer:threads:read. */
3854 remote_target::remote_get_threads_with_qxfer (threads_listing_context *context)
3856 #if defined(HAVE_LIBEXPAT)
3857 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3859 gdb::optional<gdb::char_vector> xml
3860 = target_read_stralloc (this, TARGET_OBJECT_THREADS, NULL);
3862 if (xml && (*xml)[0] != '\0')
3864 gdb_xml_parse_quick (_("threads"), "threads.dtd",
3865 threads_elements, xml->data (), context);
3868 return 1;
3870 #endif
3872 return 0;
3875 /* List remote threads using qfThreadInfo/qsThreadInfo. */
3878 remote_target::remote_get_threads_with_qthreadinfo (threads_listing_context *context)
3880 struct remote_state *rs = get_remote_state ();
3882 if (rs->use_threadinfo_query)
3884 const char *bufp;
3886 putpkt ("qfThreadInfo");
3887 getpkt (&rs->buf, 0);
3888 bufp = rs->buf.data ();
3889 if (bufp[0] != '\0') /* q packet recognized */
3891 while (*bufp++ == 'm') /* reply contains one or more TID */
3895 ptid_t ptid = read_ptid (bufp, &bufp);
3896 context->items.emplace_back (ptid);
3898 while (*bufp++ == ','); /* comma-separated list */
3899 putpkt ("qsThreadInfo");
3900 getpkt (&rs->buf, 0);
3901 bufp = rs->buf.data ();
3903 return 1;
3905 else
3907 /* Packet not recognized. */
3908 rs->use_threadinfo_query = 0;
3912 return 0;
3915 /* Return true if INF only has one non-exited thread. */
3917 static bool
3918 has_single_non_exited_thread (inferior *inf)
3920 int count = 0;
3921 for (thread_info *tp ATTRIBUTE_UNUSED : inf->non_exited_threads ())
3922 if (++count > 1)
3923 break;
3924 return count == 1;
3927 /* Implement the to_update_thread_list function for the remote
3928 targets. */
3930 void
3931 remote_target::update_thread_list ()
3933 struct threads_listing_context context;
3934 int got_list = 0;
3936 /* We have a few different mechanisms to fetch the thread list. Try
3937 them all, starting with the most preferred one first, falling
3938 back to older methods. */
3939 if (remote_get_threads_with_qxfer (&context)
3940 || remote_get_threads_with_qthreadinfo (&context)
3941 || remote_get_threads_with_ql (&context))
3943 got_list = 1;
3945 if (context.items.empty ()
3946 && remote_thread_always_alive (inferior_ptid))
3948 /* Some targets don't really support threads, but still
3949 reply an (empty) thread list in response to the thread
3950 listing packets, instead of replying "packet not
3951 supported". Exit early so we don't delete the main
3952 thread. */
3953 return;
3956 /* CONTEXT now holds the current thread list on the remote
3957 target end. Delete GDB-side threads no longer found on the
3958 target. */
3959 for (thread_info *tp : all_threads_safe ())
3961 if (tp->inf->process_target () != this)
3962 continue;
3964 if (!context.contains_thread (tp->ptid))
3966 /* Do not remove the thread if it is the last thread in
3967 the inferior. This situation happens when we have a
3968 pending exit process status to process. Otherwise we
3969 may end up with a seemingly live inferior (i.e. pid
3970 != 0) that has no threads. */
3971 if (has_single_non_exited_thread (tp->inf))
3972 continue;
3974 /* Not found. */
3975 delete_thread (tp);
3979 /* Remove any unreported fork child threads from CONTEXT so
3980 that we don't interfere with follow fork, which is where
3981 creation of such threads is handled. */
3982 remove_new_fork_children (&context);
3984 /* And now add threads we don't know about yet to our list. */
3985 for (thread_item &item : context.items)
3987 if (item.ptid != null_ptid)
3989 /* In non-stop mode, we assume new found threads are
3990 executing until proven otherwise with a stop reply.
3991 In all-stop, we can only get here if all threads are
3992 stopped. */
3993 bool executing = target_is_non_stop_p ();
3995 remote_notice_new_inferior (item.ptid, executing);
3997 thread_info *tp = find_thread_ptid (this, item.ptid);
3998 remote_thread_info *info = get_remote_thread_info (tp);
3999 info->core = item.core;
4000 info->extra = std::move (item.extra);
4001 info->name = std::move (item.name);
4002 info->thread_handle = std::move (item.thread_handle);
4007 if (!got_list)
4009 /* If no thread listing method is supported, then query whether
4010 each known thread is alive, one by one, with the T packet.
4011 If the target doesn't support threads at all, then this is a
4012 no-op. See remote_thread_alive. */
4013 prune_threads ();
4018 * Collect a descriptive string about the given thread.
4019 * The target may say anything it wants to about the thread
4020 * (typically info about its blocked / runnable state, name, etc.).
4021 * This string will appear in the info threads display.
4023 * Optional: targets are not required to implement this function.
4026 const char *
4027 remote_target::extra_thread_info (thread_info *tp)
4029 struct remote_state *rs = get_remote_state ();
4030 int set;
4031 threadref id;
4032 struct gdb_ext_thread_info threadinfo;
4034 if (rs->remote_desc == 0) /* paranoia */
4035 internal_error (__FILE__, __LINE__,
4036 _("remote_threads_extra_info"));
4038 if (tp->ptid == magic_null_ptid
4039 || (tp->ptid.pid () != 0 && tp->ptid.lwp () == 0))
4040 /* This is the main thread which was added by GDB. The remote
4041 server doesn't know about it. */
4042 return NULL;
4044 std::string &extra = get_remote_thread_info (tp)->extra;
4046 /* If already have cached info, use it. */
4047 if (!extra.empty ())
4048 return extra.c_str ();
4050 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
4052 /* If we're using qXfer:threads:read, then the extra info is
4053 included in the XML. So if we didn't have anything cached,
4054 it's because there's really no extra info. */
4055 return NULL;
4058 if (rs->use_threadextra_query)
4060 char *b = rs->buf.data ();
4061 char *endb = b + get_remote_packet_size ();
4063 xsnprintf (b, endb - b, "qThreadExtraInfo,");
4064 b += strlen (b);
4065 write_ptid (b, endb, tp->ptid);
4067 putpkt (rs->buf);
4068 getpkt (&rs->buf, 0);
4069 if (rs->buf[0] != 0)
4071 extra.resize (strlen (rs->buf.data ()) / 2);
4072 hex2bin (rs->buf.data (), (gdb_byte *) &extra[0], extra.size ());
4073 return extra.c_str ();
4077 /* If the above query fails, fall back to the old method. */
4078 rs->use_threadextra_query = 0;
4079 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
4080 | TAG_MOREDISPLAY | TAG_DISPLAY;
4081 int_to_threadref (&id, tp->ptid.lwp ());
4082 if (remote_get_threadinfo (&id, set, &threadinfo))
4083 if (threadinfo.active)
4085 if (*threadinfo.shortname)
4086 string_appendf (extra, " Name: %s", threadinfo.shortname);
4087 if (*threadinfo.display)
4089 if (!extra.empty ())
4090 extra += ',';
4091 string_appendf (extra, " State: %s", threadinfo.display);
4093 if (*threadinfo.more_display)
4095 if (!extra.empty ())
4096 extra += ',';
4097 string_appendf (extra, " Priority: %s", threadinfo.more_display);
4099 return extra.c_str ();
4101 return NULL;
4105 bool
4106 remote_target::static_tracepoint_marker_at (CORE_ADDR addr,
4107 struct static_tracepoint_marker *marker)
4109 struct remote_state *rs = get_remote_state ();
4110 char *p = rs->buf.data ();
4112 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
4113 p += strlen (p);
4114 p += hexnumstr (p, addr);
4115 putpkt (rs->buf);
4116 getpkt (&rs->buf, 0);
4117 p = rs->buf.data ();
4119 if (*p == 'E')
4120 error (_("Remote failure reply: %s"), p);
4122 if (*p++ == 'm')
4124 parse_static_tracepoint_marker_definition (p, NULL, marker);
4125 return true;
4128 return false;
4131 std::vector<static_tracepoint_marker>
4132 remote_target::static_tracepoint_markers_by_strid (const char *strid)
4134 struct remote_state *rs = get_remote_state ();
4135 std::vector<static_tracepoint_marker> markers;
4136 const char *p;
4137 static_tracepoint_marker marker;
4139 /* Ask for a first packet of static tracepoint marker
4140 definition. */
4141 putpkt ("qTfSTM");
4142 getpkt (&rs->buf, 0);
4143 p = rs->buf.data ();
4144 if (*p == 'E')
4145 error (_("Remote failure reply: %s"), p);
4147 while (*p++ == 'm')
4151 parse_static_tracepoint_marker_definition (p, &p, &marker);
4153 if (strid == NULL || marker.str_id == strid)
4154 markers.push_back (std::move (marker));
4156 while (*p++ == ','); /* comma-separated list */
4157 /* Ask for another packet of static tracepoint definition. */
4158 putpkt ("qTsSTM");
4159 getpkt (&rs->buf, 0);
4160 p = rs->buf.data ();
4163 return markers;
4167 /* Implement the to_get_ada_task_ptid function for the remote targets. */
4169 ptid_t
4170 remote_target::get_ada_task_ptid (long lwp, ULONGEST thread)
4172 return ptid_t (inferior_ptid.pid (), lwp);
4176 /* Restart the remote side; this is an extended protocol operation. */
4178 void
4179 remote_target::extended_remote_restart ()
4181 struct remote_state *rs = get_remote_state ();
4183 /* Send the restart command; for reasons I don't understand the
4184 remote side really expects a number after the "R". */
4185 xsnprintf (rs->buf.data (), get_remote_packet_size (), "R%x", 0);
4186 putpkt (rs->buf);
4188 remote_fileio_reset ();
4191 /* Clean up connection to a remote debugger. */
4193 void
4194 remote_target::close ()
4196 /* Make sure we leave stdin registered in the event loop. */
4197 terminal_ours ();
4199 trace_reset_local_state ();
4201 delete this;
4204 remote_target::~remote_target ()
4206 struct remote_state *rs = get_remote_state ();
4208 /* Check for NULL because we may get here with a partially
4209 constructed target/connection. */
4210 if (rs->remote_desc == nullptr)
4211 return;
4213 serial_close (rs->remote_desc);
4215 /* We are destroying the remote target, so we should discard
4216 everything of this target. */
4217 discard_pending_stop_replies_in_queue ();
4219 if (rs->remote_async_inferior_event_token)
4220 delete_async_event_handler (&rs->remote_async_inferior_event_token);
4222 delete rs->notif_state;
4225 /* Query the remote side for the text, data and bss offsets. */
4227 void
4228 remote_target::get_offsets ()
4230 struct remote_state *rs = get_remote_state ();
4231 char *buf;
4232 char *ptr;
4233 int lose, num_segments = 0, do_sections, do_segments;
4234 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
4236 if (current_program_space->symfile_object_file == NULL)
4237 return;
4239 putpkt ("qOffsets");
4240 getpkt (&rs->buf, 0);
4241 buf = rs->buf.data ();
4243 if (buf[0] == '\000')
4244 return; /* Return silently. Stub doesn't support
4245 this command. */
4246 if (buf[0] == 'E')
4248 warning (_("Remote failure reply: %s"), buf);
4249 return;
4252 /* Pick up each field in turn. This used to be done with scanf, but
4253 scanf will make trouble if CORE_ADDR size doesn't match
4254 conversion directives correctly. The following code will work
4255 with any size of CORE_ADDR. */
4256 text_addr = data_addr = bss_addr = 0;
4257 ptr = buf;
4258 lose = 0;
4260 if (startswith (ptr, "Text="))
4262 ptr += 5;
4263 /* Don't use strtol, could lose on big values. */
4264 while (*ptr && *ptr != ';')
4265 text_addr = (text_addr << 4) + fromhex (*ptr++);
4267 if (startswith (ptr, ";Data="))
4269 ptr += 6;
4270 while (*ptr && *ptr != ';')
4271 data_addr = (data_addr << 4) + fromhex (*ptr++);
4273 else
4274 lose = 1;
4276 if (!lose && startswith (ptr, ";Bss="))
4278 ptr += 5;
4279 while (*ptr && *ptr != ';')
4280 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
4282 if (bss_addr != data_addr)
4283 warning (_("Target reported unsupported offsets: %s"), buf);
4285 else
4286 lose = 1;
4288 else if (startswith (ptr, "TextSeg="))
4290 ptr += 8;
4291 /* Don't use strtol, could lose on big values. */
4292 while (*ptr && *ptr != ';')
4293 text_addr = (text_addr << 4) + fromhex (*ptr++);
4294 num_segments = 1;
4296 if (startswith (ptr, ";DataSeg="))
4298 ptr += 9;
4299 while (*ptr && *ptr != ';')
4300 data_addr = (data_addr << 4) + fromhex (*ptr++);
4301 num_segments++;
4304 else
4305 lose = 1;
4307 if (lose)
4308 error (_("Malformed response to offset query, %s"), buf);
4309 else if (*ptr != '\0')
4310 warning (_("Target reported unsupported offsets: %s"), buf);
4312 objfile *objf = current_program_space->symfile_object_file;
4313 section_offsets offs = objf->section_offsets;
4315 symfile_segment_data_up data = get_symfile_segment_data (objf->obfd);
4316 do_segments = (data != NULL);
4317 do_sections = num_segments == 0;
4319 if (num_segments > 0)
4321 segments[0] = text_addr;
4322 segments[1] = data_addr;
4324 /* If we have two segments, we can still try to relocate everything
4325 by assuming that the .text and .data offsets apply to the whole
4326 text and data segments. Convert the offsets given in the packet
4327 to base addresses for symfile_map_offsets_to_segments. */
4328 else if (data != nullptr && data->segments.size () == 2)
4330 segments[0] = data->segments[0].base + text_addr;
4331 segments[1] = data->segments[1].base + data_addr;
4332 num_segments = 2;
4334 /* If the object file has only one segment, assume that it is text
4335 rather than data; main programs with no writable data are rare,
4336 but programs with no code are useless. Of course the code might
4337 have ended up in the data segment... to detect that we would need
4338 the permissions here. */
4339 else if (data && data->segments.size () == 1)
4341 segments[0] = data->segments[0].base + text_addr;
4342 num_segments = 1;
4344 /* There's no way to relocate by segment. */
4345 else
4346 do_segments = 0;
4348 if (do_segments)
4350 int ret = symfile_map_offsets_to_segments (objf->obfd,
4351 data.get (), offs,
4352 num_segments, segments);
4354 if (ret == 0 && !do_sections)
4355 error (_("Can not handle qOffsets TextSeg "
4356 "response with this symbol file"));
4358 if (ret > 0)
4359 do_sections = 0;
4362 if (do_sections)
4364 offs[SECT_OFF_TEXT (objf)] = text_addr;
4366 /* This is a temporary kludge to force data and bss to use the
4367 same offsets because that's what nlmconv does now. The real
4368 solution requires changes to the stub and remote.c that I
4369 don't have time to do right now. */
4371 offs[SECT_OFF_DATA (objf)] = data_addr;
4372 offs[SECT_OFF_BSS (objf)] = data_addr;
4375 objfile_relocate (objf, offs);
4378 /* Send interrupt_sequence to remote target. */
4380 void
4381 remote_target::send_interrupt_sequence ()
4383 struct remote_state *rs = get_remote_state ();
4385 if (interrupt_sequence_mode == interrupt_sequence_control_c)
4386 remote_serial_write ("\x03", 1);
4387 else if (interrupt_sequence_mode == interrupt_sequence_break)
4388 serial_send_break (rs->remote_desc);
4389 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
4391 serial_send_break (rs->remote_desc);
4392 remote_serial_write ("g", 1);
4394 else
4395 internal_error (__FILE__, __LINE__,
4396 _("Invalid value for interrupt_sequence_mode: %s."),
4397 interrupt_sequence_mode);
4401 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
4402 and extract the PTID. Returns NULL_PTID if not found. */
4404 static ptid_t
4405 stop_reply_extract_thread (const char *stop_reply)
4407 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
4409 const char *p;
4411 /* Txx r:val ; r:val (...) */
4412 p = &stop_reply[3];
4414 /* Look for "register" named "thread". */
4415 while (*p != '\0')
4417 const char *p1;
4419 p1 = strchr (p, ':');
4420 if (p1 == NULL)
4421 return null_ptid;
4423 if (strncmp (p, "thread", p1 - p) == 0)
4424 return read_ptid (++p1, &p);
4426 p1 = strchr (p, ';');
4427 if (p1 == NULL)
4428 return null_ptid;
4429 p1++;
4431 p = p1;
4435 return null_ptid;
4438 /* Determine the remote side's current thread. If we have a stop
4439 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
4440 "thread" register we can extract the current thread from. If not,
4441 ask the remote which is the current thread with qC. The former
4442 method avoids a roundtrip. */
4444 ptid_t
4445 remote_target::get_current_thread (const char *wait_status)
4447 ptid_t ptid = null_ptid;
4449 /* Note we don't use remote_parse_stop_reply as that makes use of
4450 the target architecture, which we haven't yet fully determined at
4451 this point. */
4452 if (wait_status != NULL)
4453 ptid = stop_reply_extract_thread (wait_status);
4454 if (ptid == null_ptid)
4455 ptid = remote_current_thread (inferior_ptid);
4457 return ptid;
4460 /* Query the remote target for which is the current thread/process,
4461 add it to our tables, and update INFERIOR_PTID. The caller is
4462 responsible for setting the state such that the remote end is ready
4463 to return the current thread.
4465 This function is called after handling the '?' or 'vRun' packets,
4466 whose response is a stop reply from which we can also try
4467 extracting the thread. If the target doesn't support the explicit
4468 qC query, we infer the current thread from that stop reply, passed
4469 in in WAIT_STATUS, which may be NULL.
4471 The function returns pointer to the main thread of the inferior. */
4473 thread_info *
4474 remote_target::add_current_inferior_and_thread (const char *wait_status)
4476 struct remote_state *rs = get_remote_state ();
4477 bool fake_pid_p = false;
4479 switch_to_no_thread ();
4481 /* Now, if we have thread information, update the current thread's
4482 ptid. */
4483 ptid_t curr_ptid = get_current_thread (wait_status);
4485 if (curr_ptid != null_ptid)
4487 if (!remote_multi_process_p (rs))
4488 fake_pid_p = true;
4490 else
4492 /* Without this, some commands which require an active target
4493 (such as kill) won't work. This variable serves (at least)
4494 double duty as both the pid of the target process (if it has
4495 such), and as a flag indicating that a target is active. */
4496 curr_ptid = magic_null_ptid;
4497 fake_pid_p = true;
4500 remote_add_inferior (fake_pid_p, curr_ptid.pid (), -1, 1);
4502 /* Add the main thread and switch to it. Don't try reading
4503 registers yet, since we haven't fetched the target description
4504 yet. */
4505 thread_info *tp = add_thread_silent (this, curr_ptid);
4506 switch_to_thread_no_regs (tp);
4508 return tp;
4511 /* Print info about a thread that was found already stopped on
4512 connection. */
4514 void
4515 remote_target::print_one_stopped_thread (thread_info *thread)
4517 target_waitstatus ws;
4519 /* If there is a pending waitstatus, use it. If there isn't it's because
4520 the thread's stop was reported with TARGET_WAITKIND_STOPPED / GDB_SIGNAL_0
4521 and process_initial_stop_replies decided it wasn't interesting to save
4522 and report to the core. */
4523 if (thread->has_pending_waitstatus ())
4525 ws = thread->pending_waitstatus ();
4526 thread->clear_pending_waitstatus ();
4528 else
4530 ws.set_stopped (GDB_SIGNAL_0);
4533 switch_to_thread (thread);
4534 thread->set_stop_pc (get_frame_pc (get_current_frame ()));
4535 set_current_sal_from_frame (get_current_frame ());
4537 /* For "info program". */
4538 set_last_target_status (this, thread->ptid, ws);
4540 if (ws.kind () == TARGET_WAITKIND_STOPPED)
4542 enum gdb_signal sig = ws.sig ();
4544 if (signal_print_state (sig))
4545 gdb::observers::signal_received.notify (sig);
4547 gdb::observers::normal_stop.notify (NULL, 1);
4550 /* Process all initial stop replies the remote side sent in response
4551 to the ? packet. These indicate threads that were already stopped
4552 on initial connection. We mark these threads as stopped and print
4553 their current frame before giving the user the prompt. */
4555 void
4556 remote_target::process_initial_stop_replies (int from_tty)
4558 int pending_stop_replies = stop_reply_queue_length ();
4559 struct thread_info *selected = NULL;
4560 struct thread_info *lowest_stopped = NULL;
4561 struct thread_info *first = NULL;
4563 /* This is only used when the target is non-stop. */
4564 gdb_assert (target_is_non_stop_p ());
4566 /* Consume the initial pending events. */
4567 while (pending_stop_replies-- > 0)
4569 ptid_t waiton_ptid = minus_one_ptid;
4570 ptid_t event_ptid;
4571 struct target_waitstatus ws;
4572 int ignore_event = 0;
4574 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
4575 if (remote_debug)
4576 print_target_wait_results (waiton_ptid, event_ptid, ws);
4578 switch (ws.kind ())
4580 case TARGET_WAITKIND_IGNORE:
4581 case TARGET_WAITKIND_NO_RESUMED:
4582 case TARGET_WAITKIND_SIGNALLED:
4583 case TARGET_WAITKIND_EXITED:
4584 /* We shouldn't see these, but if we do, just ignore. */
4585 remote_debug_printf ("event ignored");
4586 ignore_event = 1;
4587 break;
4589 default:
4590 break;
4593 if (ignore_event)
4594 continue;
4596 thread_info *evthread = find_thread_ptid (this, event_ptid);
4598 if (ws.kind () == TARGET_WAITKIND_STOPPED)
4600 enum gdb_signal sig = ws.sig ();
4602 /* Stubs traditionally report SIGTRAP as initial signal,
4603 instead of signal 0. Suppress it. */
4604 if (sig == GDB_SIGNAL_TRAP)
4605 sig = GDB_SIGNAL_0;
4606 evthread->set_stop_signal (sig);
4607 ws.set_stopped (sig);
4610 if (ws.kind () != TARGET_WAITKIND_STOPPED
4611 || ws.sig () != GDB_SIGNAL_0)
4612 evthread->set_pending_waitstatus (ws);
4614 set_executing (this, event_ptid, false);
4615 set_running (this, event_ptid, false);
4616 get_remote_thread_info (evthread)->set_not_resumed ();
4619 /* "Notice" the new inferiors before anything related to
4620 registers/memory. */
4621 for (inferior *inf : all_non_exited_inferiors (this))
4623 inf->needs_setup = 1;
4625 if (non_stop)
4627 thread_info *thread = any_live_thread_of_inferior (inf);
4628 notice_new_inferior (thread, thread->state == THREAD_RUNNING,
4629 from_tty);
4633 /* If all-stop on top of non-stop, pause all threads. Note this
4634 records the threads' stop pc, so must be done after "noticing"
4635 the inferiors. */
4636 if (!non_stop)
4639 /* At this point, the remote target is not async. It needs to be for
4640 the poll in stop_all_threads to consider events from it, so enable
4641 it temporarily. */
4642 gdb_assert (!this->is_async_p ());
4643 SCOPE_EXIT { target_async (0); };
4644 target_async (1);
4645 stop_all_threads ("remote connect in all-stop");
4648 /* If all threads of an inferior were already stopped, we
4649 haven't setup the inferior yet. */
4650 for (inferior *inf : all_non_exited_inferiors (this))
4652 if (inf->needs_setup)
4654 thread_info *thread = any_live_thread_of_inferior (inf);
4655 switch_to_thread_no_regs (thread);
4656 setup_inferior (0);
4661 /* Now go over all threads that are stopped, and print their current
4662 frame. If all-stop, then if there's a signalled thread, pick
4663 that as current. */
4664 for (thread_info *thread : all_non_exited_threads (this))
4666 if (first == NULL)
4667 first = thread;
4669 if (!non_stop)
4670 thread->set_running (false);
4671 else if (thread->state != THREAD_STOPPED)
4672 continue;
4674 if (selected == nullptr && thread->has_pending_waitstatus ())
4675 selected = thread;
4677 if (lowest_stopped == NULL
4678 || thread->inf->num < lowest_stopped->inf->num
4679 || thread->per_inf_num < lowest_stopped->per_inf_num)
4680 lowest_stopped = thread;
4682 if (non_stop)
4683 print_one_stopped_thread (thread);
4686 /* In all-stop, we only print the status of one thread, and leave
4687 others with their status pending. */
4688 if (!non_stop)
4690 thread_info *thread = selected;
4691 if (thread == NULL)
4692 thread = lowest_stopped;
4693 if (thread == NULL)
4694 thread = first;
4696 print_one_stopped_thread (thread);
4700 /* Mark a remote_target as marking (by setting the starting_up flag within
4701 its remote_state) for the lifetime of this object. The reference count
4702 on the remote target is temporarily incremented, to prevent the target
4703 being deleted under our feet. */
4705 struct scoped_mark_target_starting
4707 /* Constructor, TARGET is the target to be marked as starting, its
4708 reference count will be incremented. */
4709 scoped_mark_target_starting (remote_target *target)
4710 : m_remote_target (target)
4712 m_remote_target->incref ();
4713 remote_state *rs = m_remote_target->get_remote_state ();
4714 rs->starting_up = true;
4717 /* Destructor, mark the target being worked on as no longer starting, and
4718 decrement the reference count. */
4719 ~scoped_mark_target_starting ()
4721 remote_state *rs = m_remote_target->get_remote_state ();
4722 rs->starting_up = false;
4723 decref_target (m_remote_target);
4726 private:
4728 /* The target on which we are operating. */
4729 remote_target *m_remote_target;
4732 /* Helper for remote_target::start_remote, start the remote connection and
4733 sync state. Return true if everything goes OK, otherwise, return false.
4734 This function exists so that the scoped_restore created within it will
4735 expire before we return to remote_target::start_remote. */
4737 bool
4738 remote_target::start_remote_1 (int from_tty, int extended_p)
4740 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
4742 struct remote_state *rs = get_remote_state ();
4743 struct packet_config *noack_config;
4745 /* Signal other parts that we're going through the initial setup,
4746 and so things may not be stable yet. E.g., we don't try to
4747 install tracepoints until we've relocated symbols. Also, a
4748 Ctrl-C before we're connected and synced up can't interrupt the
4749 target. Instead, it offers to drop the (potentially wedged)
4750 connection. */
4751 scoped_mark_target_starting target_is_starting (this);
4753 QUIT;
4755 if (interrupt_on_connect)
4756 send_interrupt_sequence ();
4758 /* Ack any packet which the remote side has already sent. */
4759 remote_serial_write ("+", 1);
4761 /* The first packet we send to the target is the optional "supported
4762 packets" request. If the target can answer this, it will tell us
4763 which later probes to skip. */
4764 remote_query_supported ();
4766 /* If the stub wants to get a QAllow, compose one and send it. */
4767 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
4768 set_permissions ();
4770 /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
4771 unknown 'v' packet with string "OK". "OK" gets interpreted by GDB
4772 as a reply to known packet. For packet "vFile:setfs:" it is an
4773 invalid reply and GDB would return error in
4774 remote_hostio_set_filesystem, making remote files access impossible.
4775 Disable "vFile:setfs:" in such case. Do not disable other 'v' packets as
4776 other "vFile" packets get correctly detected even on gdbserver < 7.7. */
4778 const char v_mustreplyempty[] = "vMustReplyEmpty";
4780 putpkt (v_mustreplyempty);
4781 getpkt (&rs->buf, 0);
4782 if (strcmp (rs->buf.data (), "OK") == 0)
4783 remote_protocol_packets[PACKET_vFile_setfs].support = PACKET_DISABLE;
4784 else if (strcmp (rs->buf.data (), "") != 0)
4785 error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
4786 rs->buf.data ());
4789 /* Next, we possibly activate noack mode.
4791 If the QStartNoAckMode packet configuration is set to AUTO,
4792 enable noack mode if the stub reported a wish for it with
4793 qSupported.
4795 If set to TRUE, then enable noack mode even if the stub didn't
4796 report it in qSupported. If the stub doesn't reply OK, the
4797 session ends with an error.
4799 If FALSE, then don't activate noack mode, regardless of what the
4800 stub claimed should be the default with qSupported. */
4802 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4803 if (packet_config_support (noack_config) != PACKET_DISABLE)
4805 putpkt ("QStartNoAckMode");
4806 getpkt (&rs->buf, 0);
4807 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
4808 rs->noack_mode = 1;
4811 if (extended_p)
4813 /* Tell the remote that we are using the extended protocol. */
4814 putpkt ("!");
4815 getpkt (&rs->buf, 0);
4818 /* Let the target know which signals it is allowed to pass down to
4819 the program. */
4820 update_signals_program_target ();
4822 /* Next, if the target can specify a description, read it. We do
4823 this before anything involving memory or registers. */
4824 target_find_description ();
4826 /* Next, now that we know something about the target, update the
4827 address spaces in the program spaces. */
4828 update_address_spaces ();
4830 /* On OSs where the list of libraries is global to all
4831 processes, we fetch them early. */
4832 if (gdbarch_has_global_solist (target_gdbarch ()))
4833 solib_add (NULL, from_tty, auto_solib_add);
4835 if (target_is_non_stop_p ())
4837 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
4838 error (_("Non-stop mode requested, but remote "
4839 "does not support non-stop"));
4841 putpkt ("QNonStop:1");
4842 getpkt (&rs->buf, 0);
4844 if (strcmp (rs->buf.data (), "OK") != 0)
4845 error (_("Remote refused setting non-stop mode with: %s"),
4846 rs->buf.data ());
4848 /* Find about threads and processes the stub is already
4849 controlling. We default to adding them in the running state.
4850 The '?' query below will then tell us about which threads are
4851 stopped. */
4852 this->update_thread_list ();
4854 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
4856 /* Don't assume that the stub can operate in all-stop mode.
4857 Request it explicitly. */
4858 putpkt ("QNonStop:0");
4859 getpkt (&rs->buf, 0);
4861 if (strcmp (rs->buf.data (), "OK") != 0)
4862 error (_("Remote refused setting all-stop mode with: %s"),
4863 rs->buf.data ());
4866 /* Upload TSVs regardless of whether the target is running or not. The
4867 remote stub, such as GDBserver, may have some predefined or builtin
4868 TSVs, even if the target is not running. */
4869 if (get_trace_status (current_trace_status ()) != -1)
4871 struct uploaded_tsv *uploaded_tsvs = NULL;
4873 upload_trace_state_variables (&uploaded_tsvs);
4874 merge_uploaded_trace_state_variables (&uploaded_tsvs);
4877 /* Check whether the target is running now. */
4878 putpkt ("?");
4879 getpkt (&rs->buf, 0);
4881 if (!target_is_non_stop_p ())
4883 char *wait_status = NULL;
4885 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
4887 if (!extended_p)
4888 error (_("The target is not running (try extended-remote?)"));
4889 return false;
4891 else
4893 /* Save the reply for later. */
4894 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
4895 strcpy (wait_status, rs->buf.data ());
4898 /* Fetch thread list. */
4899 target_update_thread_list ();
4901 /* Let the stub know that we want it to return the thread. */
4902 set_continue_thread (minus_one_ptid);
4904 if (thread_count (this) == 0)
4906 /* Target has no concept of threads at all. GDB treats
4907 non-threaded target as single-threaded; add a main
4908 thread. */
4909 thread_info *tp = add_current_inferior_and_thread (wait_status);
4910 get_remote_thread_info (tp)->set_resumed ();
4912 else
4914 /* We have thread information; select the thread the target
4915 says should be current. If we're reconnecting to a
4916 multi-threaded program, this will ideally be the thread
4917 that last reported an event before GDB disconnected. */
4918 ptid_t curr_thread = get_current_thread (wait_status);
4919 if (curr_thread == null_ptid)
4921 /* Odd... The target was able to list threads, but not
4922 tell us which thread was current (no "thread"
4923 register in T stop reply?). Just pick the first
4924 thread in the thread list then. */
4926 remote_debug_printf ("warning: couldn't determine remote "
4927 "current thread; picking first in list.");
4929 for (thread_info *tp : all_non_exited_threads (this,
4930 minus_one_ptid))
4932 switch_to_thread (tp);
4933 break;
4936 else
4937 switch_to_thread (find_thread_ptid (this, curr_thread));
4940 /* init_wait_for_inferior should be called before get_offsets in order
4941 to manage `inserted' flag in bp loc in a correct state.
4942 breakpoint_init_inferior, called from init_wait_for_inferior, set
4943 `inserted' flag to 0, while before breakpoint_re_set, called from
4944 start_remote, set `inserted' flag to 1. In the initialization of
4945 inferior, breakpoint_init_inferior should be called first, and then
4946 breakpoint_re_set can be called. If this order is broken, state of
4947 `inserted' flag is wrong, and cause some problems on breakpoint
4948 manipulation. */
4949 init_wait_for_inferior ();
4951 get_offsets (); /* Get text, data & bss offsets. */
4953 /* If we could not find a description using qXfer, and we know
4954 how to do it some other way, try again. This is not
4955 supported for non-stop; it could be, but it is tricky if
4956 there are no stopped threads when we connect. */
4957 if (remote_read_description_p (this)
4958 && gdbarch_target_desc (target_gdbarch ()) == NULL)
4960 target_clear_description ();
4961 target_find_description ();
4964 /* Use the previously fetched status. */
4965 gdb_assert (wait_status != NULL);
4966 struct notif_event *reply
4967 = remote_notif_parse (this, &notif_client_stop, wait_status);
4968 push_stop_reply ((struct stop_reply *) reply);
4970 ::start_remote (from_tty); /* Initialize gdb process mechanisms. */
4972 else
4974 /* Clear WFI global state. Do this before finding about new
4975 threads and inferiors, and setting the current inferior.
4976 Otherwise we would clear the proceed status of the current
4977 inferior when we want its stop_soon state to be preserved
4978 (see notice_new_inferior). */
4979 init_wait_for_inferior ();
4981 /* In non-stop, we will either get an "OK", meaning that there
4982 are no stopped threads at this time; or, a regular stop
4983 reply. In the latter case, there may be more than one thread
4984 stopped --- we pull them all out using the vStopped
4985 mechanism. */
4986 if (strcmp (rs->buf.data (), "OK") != 0)
4988 struct notif_client *notif = &notif_client_stop;
4990 /* remote_notif_get_pending_replies acks this one, and gets
4991 the rest out. */
4992 rs->notif_state->pending_event[notif_client_stop.id]
4993 = remote_notif_parse (this, notif, rs->buf.data ());
4994 remote_notif_get_pending_events (notif);
4997 if (thread_count (this) == 0)
4999 if (!extended_p)
5000 error (_("The target is not running (try extended-remote?)"));
5001 return false;
5004 /* Report all signals during attach/startup. */
5005 pass_signals ({});
5007 /* If there are already stopped threads, mark them stopped and
5008 report their stops before giving the prompt to the user. */
5009 process_initial_stop_replies (from_tty);
5011 if (target_can_async_p ())
5012 target_async (1);
5015 /* If we connected to a live target, do some additional setup. */
5016 if (target_has_execution ())
5018 /* No use without a symbol-file. */
5019 if (current_program_space->symfile_object_file)
5020 remote_check_symbols ();
5023 /* Possibly the target has been engaged in a trace run started
5024 previously; find out where things are at. */
5025 if (get_trace_status (current_trace_status ()) != -1)
5027 struct uploaded_tp *uploaded_tps = NULL;
5029 if (current_trace_status ()->running)
5030 gdb_printf (_("Trace is already running on the target.\n"));
5032 upload_tracepoints (&uploaded_tps);
5034 merge_uploaded_tracepoints (&uploaded_tps);
5037 /* Possibly the target has been engaged in a btrace record started
5038 previously; find out where things are at. */
5039 remote_btrace_maybe_reopen ();
5041 return true;
5044 /* Start the remote connection and sync state. */
5046 void
5047 remote_target::start_remote (int from_tty, int extended_p)
5049 if (start_remote_1 (from_tty, extended_p)
5050 && breakpoints_should_be_inserted_now ())
5051 insert_breakpoints ();
5054 const char *
5055 remote_target::connection_string ()
5057 remote_state *rs = get_remote_state ();
5059 if (rs->remote_desc->name != NULL)
5060 return rs->remote_desc->name;
5061 else
5062 return NULL;
5065 /* Open a connection to a remote debugger.
5066 NAME is the filename used for communication. */
5068 void
5069 remote_target::open (const char *name, int from_tty)
5071 open_1 (name, from_tty, 0);
5074 /* Open a connection to a remote debugger using the extended
5075 remote gdb protocol. NAME is the filename used for communication. */
5077 void
5078 extended_remote_target::open (const char *name, int from_tty)
5080 open_1 (name, from_tty, 1 /*extended_p */);
5083 /* Reset all packets back to "unknown support". Called when opening a
5084 new connection to a remote target. */
5086 static void
5087 reset_all_packet_configs_support (void)
5089 int i;
5091 for (i = 0; i < PACKET_MAX; i++)
5092 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
5095 /* Initialize all packet configs. */
5097 static void
5098 init_all_packet_configs (void)
5100 int i;
5102 for (i = 0; i < PACKET_MAX; i++)
5104 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
5105 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
5109 /* Symbol look-up. */
5111 void
5112 remote_target::remote_check_symbols ()
5114 char *tmp;
5115 int end;
5117 /* The remote side has no concept of inferiors that aren't running
5118 yet, it only knows about running processes. If we're connected
5119 but our current inferior is not running, we should not invite the
5120 remote target to request symbol lookups related to its
5121 (unrelated) current process. */
5122 if (!target_has_execution ())
5123 return;
5125 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
5126 return;
5128 /* Make sure the remote is pointing at the right process. Note
5129 there's no way to select "no process". */
5130 set_general_process ();
5132 /* Allocate a message buffer. We can't reuse the input buffer in RS,
5133 because we need both at the same time. */
5134 gdb::char_vector msg (get_remote_packet_size ());
5135 gdb::char_vector reply (get_remote_packet_size ());
5137 /* Invite target to request symbol lookups. */
5139 putpkt ("qSymbol::");
5140 getpkt (&reply, 0);
5141 packet_ok (reply, &remote_protocol_packets[PACKET_qSymbol]);
5143 while (startswith (reply.data (), "qSymbol:"))
5145 struct bound_minimal_symbol sym;
5147 tmp = &reply[8];
5148 end = hex2bin (tmp, reinterpret_cast <gdb_byte *> (msg.data ()),
5149 strlen (tmp) / 2);
5150 msg[end] = '\0';
5151 sym = lookup_minimal_symbol (msg.data (), NULL, NULL);
5152 if (sym.minsym == NULL)
5153 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol::%s",
5154 &reply[8]);
5155 else
5157 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5158 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
5160 /* If this is a function address, return the start of code
5161 instead of any data function descriptor. */
5162 sym_addr = gdbarch_convert_from_func_ptr_addr
5163 (target_gdbarch (), sym_addr, current_inferior ()->top_target ());
5165 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol:%s:%s",
5166 phex_nz (sym_addr, addr_size), &reply[8]);
5169 putpkt (msg.data ());
5170 getpkt (&reply, 0);
5174 static struct serial *
5175 remote_serial_open (const char *name)
5177 static int udp_warning = 0;
5179 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
5180 of in ser-tcp.c, because it is the remote protocol assuming that the
5181 serial connection is reliable and not the serial connection promising
5182 to be. */
5183 if (!udp_warning && startswith (name, "udp:"))
5185 warning (_("The remote protocol may be unreliable over UDP.\n"
5186 "Some events may be lost, rendering further debugging "
5187 "impossible."));
5188 udp_warning = 1;
5191 return serial_open (name);
5194 /* Inform the target of our permission settings. The permission flags
5195 work without this, but if the target knows the settings, it can do
5196 a couple things. First, it can add its own check, to catch cases
5197 that somehow manage to get by the permissions checks in target
5198 methods. Second, if the target is wired to disallow particular
5199 settings (for instance, a system in the field that is not set up to
5200 be able to stop at a breakpoint), it can object to any unavailable
5201 permissions. */
5203 void
5204 remote_target::set_permissions ()
5206 struct remote_state *rs = get_remote_state ();
5208 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAllow:"
5209 "WriteReg:%x;WriteMem:%x;"
5210 "InsertBreak:%x;InsertTrace:%x;"
5211 "InsertFastTrace:%x;Stop:%x",
5212 may_write_registers, may_write_memory,
5213 may_insert_breakpoints, may_insert_tracepoints,
5214 may_insert_fast_tracepoints, may_stop);
5215 putpkt (rs->buf);
5216 getpkt (&rs->buf, 0);
5218 /* If the target didn't like the packet, warn the user. Do not try
5219 to undo the user's settings, that would just be maddening. */
5220 if (strcmp (rs->buf.data (), "OK") != 0)
5221 warning (_("Remote refused setting permissions with: %s"),
5222 rs->buf.data ());
5225 /* This type describes each known response to the qSupported
5226 packet. */
5227 struct protocol_feature
5229 /* The name of this protocol feature. */
5230 const char *name;
5232 /* The default for this protocol feature. */
5233 enum packet_support default_support;
5235 /* The function to call when this feature is reported, or after
5236 qSupported processing if the feature is not supported.
5237 The first argument points to this structure. The second
5238 argument indicates whether the packet requested support be
5239 enabled, disabled, or probed (or the default, if this function
5240 is being called at the end of processing and this feature was
5241 not reported). The third argument may be NULL; if not NULL, it
5242 is a NUL-terminated string taken from the packet following
5243 this feature's name and an equals sign. */
5244 void (*func) (remote_target *remote, const struct protocol_feature *,
5245 enum packet_support, const char *);
5247 /* The corresponding packet for this feature. Only used if
5248 FUNC is remote_supported_packet. */
5249 int packet;
5252 static void
5253 remote_supported_packet (remote_target *remote,
5254 const struct protocol_feature *feature,
5255 enum packet_support support,
5256 const char *argument)
5258 if (argument)
5260 warning (_("Remote qSupported response supplied an unexpected value for"
5261 " \"%s\"."), feature->name);
5262 return;
5265 remote_protocol_packets[feature->packet].support = support;
5268 void
5269 remote_target::remote_packet_size (const protocol_feature *feature,
5270 enum packet_support support, const char *value)
5272 struct remote_state *rs = get_remote_state ();
5274 int packet_size;
5275 char *value_end;
5277 if (support != PACKET_ENABLE)
5278 return;
5280 if (value == NULL || *value == '\0')
5282 warning (_("Remote target reported \"%s\" without a size."),
5283 feature->name);
5284 return;
5287 errno = 0;
5288 packet_size = strtol (value, &value_end, 16);
5289 if (errno != 0 || *value_end != '\0' || packet_size < 0)
5291 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
5292 feature->name, value);
5293 return;
5296 /* Record the new maximum packet size. */
5297 rs->explicit_packet_size = packet_size;
5300 static void
5301 remote_packet_size (remote_target *remote, const protocol_feature *feature,
5302 enum packet_support support, const char *value)
5304 remote->remote_packet_size (feature, support, value);
5307 static const struct protocol_feature remote_protocol_features[] = {
5308 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
5309 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
5310 PACKET_qXfer_auxv },
5311 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
5312 PACKET_qXfer_exec_file },
5313 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
5314 PACKET_qXfer_features },
5315 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
5316 PACKET_qXfer_libraries },
5317 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
5318 PACKET_qXfer_libraries_svr4 },
5319 { "augmented-libraries-svr4-read", PACKET_DISABLE,
5320 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
5321 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
5322 PACKET_qXfer_memory_map },
5323 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
5324 PACKET_qXfer_osdata },
5325 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
5326 PACKET_qXfer_threads },
5327 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
5328 PACKET_qXfer_traceframe_info },
5329 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
5330 PACKET_QPassSignals },
5331 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
5332 PACKET_QCatchSyscalls },
5333 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
5334 PACKET_QProgramSignals },
5335 { "QSetWorkingDir", PACKET_DISABLE, remote_supported_packet,
5336 PACKET_QSetWorkingDir },
5337 { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
5338 PACKET_QStartupWithShell },
5339 { "QEnvironmentHexEncoded", PACKET_DISABLE, remote_supported_packet,
5340 PACKET_QEnvironmentHexEncoded },
5341 { "QEnvironmentReset", PACKET_DISABLE, remote_supported_packet,
5342 PACKET_QEnvironmentReset },
5343 { "QEnvironmentUnset", PACKET_DISABLE, remote_supported_packet,
5344 PACKET_QEnvironmentUnset },
5345 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
5346 PACKET_QStartNoAckMode },
5347 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
5348 PACKET_multiprocess_feature },
5349 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
5350 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
5351 PACKET_qXfer_siginfo_read },
5352 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
5353 PACKET_qXfer_siginfo_write },
5354 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
5355 PACKET_ConditionalTracepoints },
5356 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
5357 PACKET_ConditionalBreakpoints },
5358 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
5359 PACKET_BreakpointCommands },
5360 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
5361 PACKET_FastTracepoints },
5362 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
5363 PACKET_StaticTracepoints },
5364 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
5365 PACKET_InstallInTrace},
5366 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
5367 PACKET_DisconnectedTracing_feature },
5368 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
5369 PACKET_bc },
5370 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
5371 PACKET_bs },
5372 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
5373 PACKET_TracepointSource },
5374 { "QAllow", PACKET_DISABLE, remote_supported_packet,
5375 PACKET_QAllow },
5376 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
5377 PACKET_EnableDisableTracepoints_feature },
5378 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
5379 PACKET_qXfer_fdpic },
5380 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
5381 PACKET_qXfer_uib },
5382 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
5383 PACKET_QDisableRandomization },
5384 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
5385 { "QTBuffer:size", PACKET_DISABLE,
5386 remote_supported_packet, PACKET_QTBuffer_size},
5387 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
5388 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
5389 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
5390 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
5391 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
5392 PACKET_qXfer_btrace },
5393 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
5394 PACKET_qXfer_btrace_conf },
5395 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
5396 PACKET_Qbtrace_conf_bts_size },
5397 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
5398 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
5399 { "fork-events", PACKET_DISABLE, remote_supported_packet,
5400 PACKET_fork_event_feature },
5401 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
5402 PACKET_vfork_event_feature },
5403 { "exec-events", PACKET_DISABLE, remote_supported_packet,
5404 PACKET_exec_event_feature },
5405 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
5406 PACKET_Qbtrace_conf_pt_size },
5407 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
5408 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
5409 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
5410 { "memory-tagging", PACKET_DISABLE, remote_supported_packet,
5411 PACKET_memory_tagging_feature },
5414 static char *remote_support_xml;
5416 /* Register string appended to "xmlRegisters=" in qSupported query. */
5418 void
5419 register_remote_support_xml (const char *xml)
5421 #if defined(HAVE_LIBEXPAT)
5422 if (remote_support_xml == NULL)
5423 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
5424 else
5426 char *copy = xstrdup (remote_support_xml + 13);
5427 char *saveptr;
5428 char *p = strtok_r (copy, ",", &saveptr);
5432 if (strcmp (p, xml) == 0)
5434 /* already there */
5435 xfree (copy);
5436 return;
5439 while ((p = strtok_r (NULL, ",", &saveptr)) != NULL);
5440 xfree (copy);
5442 remote_support_xml = reconcat (remote_support_xml,
5443 remote_support_xml, ",", xml,
5444 (char *) NULL);
5446 #endif
5449 static void
5450 remote_query_supported_append (std::string *msg, const char *append)
5452 if (!msg->empty ())
5453 msg->append (";");
5454 msg->append (append);
5457 void
5458 remote_target::remote_query_supported ()
5460 struct remote_state *rs = get_remote_state ();
5461 char *next;
5462 int i;
5463 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
5465 /* The packet support flags are handled differently for this packet
5466 than for most others. We treat an error, a disabled packet, and
5467 an empty response identically: any features which must be reported
5468 to be used will be automatically disabled. An empty buffer
5469 accomplishes this, since that is also the representation for a list
5470 containing no features. */
5472 rs->buf[0] = 0;
5473 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
5475 std::string q;
5477 if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
5478 remote_query_supported_append (&q, "multiprocess+");
5480 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
5481 remote_query_supported_append (&q, "swbreak+");
5482 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
5483 remote_query_supported_append (&q, "hwbreak+");
5485 remote_query_supported_append (&q, "qRelocInsn+");
5487 if (packet_set_cmd_state (PACKET_fork_event_feature)
5488 != AUTO_BOOLEAN_FALSE)
5489 remote_query_supported_append (&q, "fork-events+");
5490 if (packet_set_cmd_state (PACKET_vfork_event_feature)
5491 != AUTO_BOOLEAN_FALSE)
5492 remote_query_supported_append (&q, "vfork-events+");
5493 if (packet_set_cmd_state (PACKET_exec_event_feature)
5494 != AUTO_BOOLEAN_FALSE)
5495 remote_query_supported_append (&q, "exec-events+");
5497 if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
5498 remote_query_supported_append (&q, "vContSupported+");
5500 if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
5501 remote_query_supported_append (&q, "QThreadEvents+");
5503 if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
5504 remote_query_supported_append (&q, "no-resumed+");
5506 if (packet_set_cmd_state (PACKET_memory_tagging_feature)
5507 != AUTO_BOOLEAN_FALSE)
5508 remote_query_supported_append (&q, "memory-tagging+");
5510 /* Keep this one last to work around a gdbserver <= 7.10 bug in
5511 the qSupported:xmlRegisters=i386 handling. */
5512 if (remote_support_xml != NULL
5513 && packet_support (PACKET_qXfer_features) != PACKET_DISABLE)
5514 remote_query_supported_append (&q, remote_support_xml);
5516 q = "qSupported:" + q;
5517 putpkt (q.c_str ());
5519 getpkt (&rs->buf, 0);
5521 /* If an error occured, warn, but do not return - just reset the
5522 buffer to empty and go on to disable features. */
5523 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
5524 == PACKET_ERROR)
5526 warning (_("Remote failure reply: %s"), rs->buf.data ());
5527 rs->buf[0] = 0;
5531 memset (seen, 0, sizeof (seen));
5533 next = rs->buf.data ();
5534 while (*next)
5536 enum packet_support is_supported;
5537 char *p, *end, *name_end, *value;
5539 /* First separate out this item from the rest of the packet. If
5540 there's another item after this, we overwrite the separator
5541 (terminated strings are much easier to work with). */
5542 p = next;
5543 end = strchr (p, ';');
5544 if (end == NULL)
5546 end = p + strlen (p);
5547 next = end;
5549 else
5551 *end = '\0';
5552 next = end + 1;
5554 if (end == p)
5556 warning (_("empty item in \"qSupported\" response"));
5557 continue;
5561 name_end = strchr (p, '=');
5562 if (name_end)
5564 /* This is a name=value entry. */
5565 is_supported = PACKET_ENABLE;
5566 value = name_end + 1;
5567 *name_end = '\0';
5569 else
5571 value = NULL;
5572 switch (end[-1])
5574 case '+':
5575 is_supported = PACKET_ENABLE;
5576 break;
5578 case '-':
5579 is_supported = PACKET_DISABLE;
5580 break;
5582 case '?':
5583 is_supported = PACKET_SUPPORT_UNKNOWN;
5584 break;
5586 default:
5587 warning (_("unrecognized item \"%s\" "
5588 "in \"qSupported\" response"), p);
5589 continue;
5591 end[-1] = '\0';
5594 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5595 if (strcmp (remote_protocol_features[i].name, p) == 0)
5597 const struct protocol_feature *feature;
5599 seen[i] = 1;
5600 feature = &remote_protocol_features[i];
5601 feature->func (this, feature, is_supported, value);
5602 break;
5606 /* If we increased the packet size, make sure to increase the global
5607 buffer size also. We delay this until after parsing the entire
5608 qSupported packet, because this is the same buffer we were
5609 parsing. */
5610 if (rs->buf.size () < rs->explicit_packet_size)
5611 rs->buf.resize (rs->explicit_packet_size);
5613 /* Handle the defaults for unmentioned features. */
5614 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5615 if (!seen[i])
5617 const struct protocol_feature *feature;
5619 feature = &remote_protocol_features[i];
5620 feature->func (this, feature, feature->default_support, NULL);
5624 /* Serial QUIT handler for the remote serial descriptor.
5626 Defers handling a Ctrl-C until we're done with the current
5627 command/response packet sequence, unless:
5629 - We're setting up the connection. Don't send a remote interrupt
5630 request, as we're not fully synced yet. Quit immediately
5631 instead.
5633 - The target has been resumed in the foreground
5634 (target_terminal::is_ours is false) with a synchronous resume
5635 packet, and we're blocked waiting for the stop reply, thus a
5636 Ctrl-C should be immediately sent to the target.
5638 - We get a second Ctrl-C while still within the same serial read or
5639 write. In that case the serial is seemingly wedged --- offer to
5640 quit/disconnect.
5642 - We see a second Ctrl-C without target response, after having
5643 previously interrupted the target. In that case the target/stub
5644 is probably wedged --- offer to quit/disconnect.
5647 void
5648 remote_target::remote_serial_quit_handler ()
5650 struct remote_state *rs = get_remote_state ();
5652 if (check_quit_flag ())
5654 /* If we're starting up, we're not fully synced yet. Quit
5655 immediately. */
5656 if (rs->starting_up)
5657 quit ();
5658 else if (rs->got_ctrlc_during_io)
5660 if (query (_("The target is not responding to GDB commands.\n"
5661 "Stop debugging it? ")))
5662 remote_unpush_and_throw (this);
5664 /* If ^C has already been sent once, offer to disconnect. */
5665 else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
5666 interrupt_query ();
5667 /* All-stop protocol, and blocked waiting for stop reply. Send
5668 an interrupt request. */
5669 else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
5670 target_interrupt ();
5671 else
5672 rs->got_ctrlc_during_io = 1;
5676 /* The remote_target that is current while the quit handler is
5677 overridden with remote_serial_quit_handler. */
5678 static remote_target *curr_quit_handler_target;
5680 static void
5681 remote_serial_quit_handler ()
5683 curr_quit_handler_target->remote_serial_quit_handler ();
5686 /* Remove the remote target from the target stack of each inferior
5687 that is using it. Upper targets depend on it so remove them
5688 first. */
5690 static void
5691 remote_unpush_target (remote_target *target)
5693 /* We have to unpush the target from all inferiors, even those that
5694 aren't running. */
5695 scoped_restore_current_inferior restore_current_inferior;
5697 for (inferior *inf : all_inferiors (target))
5699 switch_to_inferior_no_thread (inf);
5700 pop_all_targets_at_and_above (process_stratum);
5701 generic_mourn_inferior ();
5704 /* Don't rely on target_close doing this when the target is popped
5705 from the last remote inferior above, because something may be
5706 holding a reference to the target higher up on the stack, meaning
5707 target_close won't be called yet. We lost the connection to the
5708 target, so clear these now, otherwise we may later throw
5709 TARGET_CLOSE_ERROR while trying to tell the remote target to
5710 close the file. */
5711 fileio_handles_invalidate_target (target);
5714 static void
5715 remote_unpush_and_throw (remote_target *target)
5717 remote_unpush_target (target);
5718 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5721 void
5722 remote_target::open_1 (const char *name, int from_tty, int extended_p)
5724 remote_target *curr_remote = get_current_remote_target ();
5726 if (name == 0)
5727 error (_("To open a remote debug connection, you need to specify what\n"
5728 "serial device is attached to the remote system\n"
5729 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
5731 /* If we're connected to a running target, target_preopen will kill it.
5732 Ask this question first, before target_preopen has a chance to kill
5733 anything. */
5734 if (curr_remote != NULL && !target_has_execution ())
5736 if (from_tty
5737 && !query (_("Already connected to a remote target. Disconnect? ")))
5738 error (_("Still connected."));
5741 /* Here the possibly existing remote target gets unpushed. */
5742 target_preopen (from_tty);
5744 remote_fileio_reset ();
5745 reopen_exec_file ();
5746 reread_symbols (from_tty);
5748 remote_target *remote
5749 = (extended_p ? new extended_remote_target () : new remote_target ());
5750 target_ops_up target_holder (remote);
5752 remote_state *rs = remote->get_remote_state ();
5754 /* See FIXME above. */
5755 if (!target_async_permitted)
5756 rs->wait_forever_enabled_p = 1;
5758 rs->remote_desc = remote_serial_open (name);
5759 if (!rs->remote_desc)
5760 perror_with_name (name);
5762 if (baud_rate != -1)
5764 if (serial_setbaudrate (rs->remote_desc, baud_rate))
5766 /* The requested speed could not be set. Error out to
5767 top level after closing remote_desc. Take care to
5768 set remote_desc to NULL to avoid closing remote_desc
5769 more than once. */
5770 serial_close (rs->remote_desc);
5771 rs->remote_desc = NULL;
5772 perror_with_name (name);
5776 serial_setparity (rs->remote_desc, serial_parity);
5777 serial_raw (rs->remote_desc);
5779 /* If there is something sitting in the buffer we might take it as a
5780 response to a command, which would be bad. */
5781 serial_flush_input (rs->remote_desc);
5783 if (from_tty)
5785 gdb_puts ("Remote debugging using ");
5786 gdb_puts (name);
5787 gdb_puts ("\n");
5790 /* Switch to using the remote target now. */
5791 current_inferior ()->push_target (std::move (target_holder));
5793 /* Register extra event sources in the event loop. */
5794 rs->remote_async_inferior_event_token
5795 = create_async_event_handler (remote_async_inferior_event_handler, nullptr,
5796 "remote");
5797 rs->notif_state = remote_notif_state_allocate (remote);
5799 /* Reset the target state; these things will be queried either by
5800 remote_query_supported or as they are needed. */
5801 reset_all_packet_configs_support ();
5802 rs->explicit_packet_size = 0;
5803 rs->noack_mode = 0;
5804 rs->extended = extended_p;
5805 rs->waiting_for_stop_reply = 0;
5806 rs->ctrlc_pending_p = 0;
5807 rs->got_ctrlc_during_io = 0;
5809 rs->general_thread = not_sent_ptid;
5810 rs->continue_thread = not_sent_ptid;
5811 rs->remote_traceframe_number = -1;
5813 rs->last_resume_exec_dir = EXEC_FORWARD;
5815 /* Probe for ability to use "ThreadInfo" query, as required. */
5816 rs->use_threadinfo_query = 1;
5817 rs->use_threadextra_query = 1;
5819 rs->readahead_cache.invalidate ();
5821 if (target_async_permitted)
5823 /* FIXME: cagney/1999-09-23: During the initial connection it is
5824 assumed that the target is already ready and able to respond to
5825 requests. Unfortunately remote_start_remote() eventually calls
5826 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
5827 around this. Eventually a mechanism that allows
5828 wait_for_inferior() to expect/get timeouts will be
5829 implemented. */
5830 rs->wait_forever_enabled_p = 0;
5833 /* First delete any symbols previously loaded from shared libraries. */
5834 no_shared_libraries (NULL, 0);
5836 /* Start the remote connection. If error() or QUIT, discard this
5837 target (we'd otherwise be in an inconsistent state) and then
5838 propogate the error on up the exception chain. This ensures that
5839 the caller doesn't stumble along blindly assuming that the
5840 function succeeded. The CLI doesn't have this problem but other
5841 UI's, such as MI do.
5843 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
5844 this function should return an error indication letting the
5845 caller restore the previous state. Unfortunately the command
5846 ``target remote'' is directly wired to this function making that
5847 impossible. On a positive note, the CLI side of this problem has
5848 been fixed - the function set_cmd_context() makes it possible for
5849 all the ``target ....'' commands to share a common callback
5850 function. See cli-dump.c. */
5855 remote->start_remote (from_tty, extended_p);
5857 catch (const gdb_exception &ex)
5859 /* Pop the partially set up target - unless something else did
5860 already before throwing the exception. */
5861 if (ex.error != TARGET_CLOSE_ERROR)
5862 remote_unpush_target (remote);
5863 throw;
5867 remote_btrace_reset (rs);
5869 if (target_async_permitted)
5870 rs->wait_forever_enabled_p = 1;
5873 /* Determine if WS represents a fork status. */
5875 static bool
5876 is_fork_status (target_waitkind kind)
5878 return (kind == TARGET_WAITKIND_FORKED
5879 || kind == TARGET_WAITKIND_VFORKED);
5882 /* Return THREAD's pending status if it is a pending fork parent, else
5883 return nullptr. */
5885 static const target_waitstatus *
5886 thread_pending_fork_status (struct thread_info *thread)
5888 const target_waitstatus &ws
5889 = (thread->has_pending_waitstatus ()
5890 ? thread->pending_waitstatus ()
5891 : thread->pending_follow);
5893 if (!is_fork_status (ws.kind ()))
5894 return nullptr;
5896 return &ws;
5899 /* Detach the specified process. */
5901 void
5902 remote_target::remote_detach_pid (int pid)
5904 struct remote_state *rs = get_remote_state ();
5906 /* This should not be necessary, but the handling for D;PID in
5907 GDBserver versions prior to 8.2 incorrectly assumes that the
5908 selected process points to the same process we're detaching,
5909 leading to misbehavior (and possibly GDBserver crashing) when it
5910 does not. Since it's easy and cheap, work around it by forcing
5911 GDBserver to select GDB's current process. */
5912 set_general_process ();
5914 if (remote_multi_process_p (rs))
5915 xsnprintf (rs->buf.data (), get_remote_packet_size (), "D;%x", pid);
5916 else
5917 strcpy (rs->buf.data (), "D");
5919 putpkt (rs->buf);
5920 getpkt (&rs->buf, 0);
5922 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
5924 else if (rs->buf[0] == '\0')
5925 error (_("Remote doesn't know how to detach"));
5926 else
5927 error (_("Can't detach process."));
5930 /* This detaches a program to which we previously attached, using
5931 inferior_ptid to identify the process. After this is done, GDB
5932 can be used to debug some other program. We better not have left
5933 any breakpoints in the target program or it'll die when it hits
5934 one. */
5936 void
5937 remote_target::remote_detach_1 (inferior *inf, int from_tty)
5939 int pid = inferior_ptid.pid ();
5940 struct remote_state *rs = get_remote_state ();
5941 int is_fork_parent;
5943 if (!target_has_execution ())
5944 error (_("No process to detach from."));
5946 target_announce_detach (from_tty);
5948 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
5950 /* If we're in breakpoints-always-inserted mode, or the inferior
5951 is running, we have to remove breakpoints before detaching.
5952 We don't do this in common code instead because not all
5953 targets support removing breakpoints while the target is
5954 running. The remote target / gdbserver does, though. */
5955 remove_breakpoints_inf (current_inferior ());
5958 /* Tell the remote target to detach. */
5959 remote_detach_pid (pid);
5961 /* Exit only if this is the only active inferior. */
5962 if (from_tty && !rs->extended && number_of_live_inferiors (this) == 1)
5963 gdb_puts (_("Ending remote debugging.\n"));
5965 /* See if any thread of the inferior we are detaching has a pending fork
5966 status. In that case, we must detach from the child resulting from
5967 that fork. */
5968 for (thread_info *thread : inf->non_exited_threads ())
5970 const target_waitstatus *ws = thread_pending_fork_status (thread);
5972 if (ws == nullptr)
5973 continue;
5975 remote_detach_pid (ws->child_ptid ().pid ());
5978 /* Check also for any pending fork events in the stop reply queue. */
5979 remote_notif_get_pending_events (&notif_client_stop);
5980 for (stop_reply_up &reply : rs->stop_reply_queue)
5982 if (reply->ptid.pid () != pid)
5983 continue;
5985 if (!is_fork_status (reply->ws.kind ()))
5986 continue;
5988 remote_detach_pid (reply->ws.child_ptid ().pid ());
5991 thread_info *tp = find_thread_ptid (this, inferior_ptid);
5993 /* Check to see if we are detaching a fork parent. Note that if we
5994 are detaching a fork child, tp == NULL. */
5995 is_fork_parent = (tp != NULL
5996 && tp->pending_follow.kind () == TARGET_WAITKIND_FORKED);
5998 /* If doing detach-on-fork, we don't mourn, because that will delete
5999 breakpoints that should be available for the followed inferior. */
6000 if (!is_fork_parent)
6002 /* Save the pid as a string before mourning, since that will
6003 unpush the remote target, and we need the string after. */
6004 std::string infpid = target_pid_to_str (ptid_t (pid));
6006 target_mourn_inferior (inferior_ptid);
6007 if (print_inferior_events)
6008 gdb_printf (_("[Inferior %d (%s) detached]\n"),
6009 inf->num, infpid.c_str ());
6011 else
6013 switch_to_no_thread ();
6014 detach_inferior (current_inferior ());
6018 void
6019 remote_target::detach (inferior *inf, int from_tty)
6021 remote_detach_1 (inf, from_tty);
6024 void
6025 extended_remote_target::detach (inferior *inf, int from_tty)
6027 remote_detach_1 (inf, from_tty);
6030 /* Target follow-fork function for remote targets. On entry, and
6031 at return, the current inferior is the fork parent.
6033 Note that although this is currently only used for extended-remote,
6034 it is named remote_follow_fork in anticipation of using it for the
6035 remote target as well. */
6037 void
6038 remote_target::follow_fork (inferior *child_inf, ptid_t child_ptid,
6039 target_waitkind fork_kind, bool follow_child,
6040 bool detach_fork)
6042 process_stratum_target::follow_fork (child_inf, child_ptid,
6043 fork_kind, follow_child, detach_fork);
6045 struct remote_state *rs = get_remote_state ();
6047 if ((fork_kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
6048 || (fork_kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
6050 /* When following the parent and detaching the child, we detach
6051 the child here. For the case of following the child and
6052 detaching the parent, the detach is done in the target-
6053 independent follow fork code in infrun.c. We can't use
6054 target_detach when detaching an unfollowed child because
6055 the client side doesn't know anything about the child. */
6056 if (detach_fork && !follow_child)
6058 /* Detach the fork child. */
6059 remote_detach_pid (child_ptid.pid ());
6064 /* Target follow-exec function for remote targets. Save EXECD_PATHNAME
6065 in the program space of the new inferior. */
6067 void
6068 remote_target::follow_exec (inferior *follow_inf, ptid_t ptid,
6069 const char *execd_pathname)
6071 process_stratum_target::follow_exec (follow_inf, ptid, execd_pathname);
6073 /* We know that this is a target file name, so if it has the "target:"
6074 prefix we strip it off before saving it in the program space. */
6075 if (is_target_filename (execd_pathname))
6076 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
6078 set_pspace_remote_exec_file (follow_inf->pspace, execd_pathname);
6081 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
6083 void
6084 remote_target::disconnect (const char *args, int from_tty)
6086 if (args)
6087 error (_("Argument given to \"disconnect\" when remotely debugging."));
6089 /* Make sure we unpush even the extended remote targets. Calling
6090 target_mourn_inferior won't unpush, and
6091 remote_target::mourn_inferior won't unpush if there is more than
6092 one inferior left. */
6093 remote_unpush_target (this);
6095 if (from_tty)
6096 gdb_puts ("Ending remote debugging.\n");
6099 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
6100 be chatty about it. */
6102 void
6103 extended_remote_target::attach (const char *args, int from_tty)
6105 struct remote_state *rs = get_remote_state ();
6106 int pid;
6107 char *wait_status = NULL;
6109 pid = parse_pid_to_attach (args);
6111 /* Remote PID can be freely equal to getpid, do not check it here the same
6112 way as in other targets. */
6114 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
6115 error (_("This target does not support attaching to a process"));
6117 target_announce_attach (from_tty, pid);
6119 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vAttach;%x", pid);
6120 putpkt (rs->buf);
6121 getpkt (&rs->buf, 0);
6123 switch (packet_ok (rs->buf,
6124 &remote_protocol_packets[PACKET_vAttach]))
6126 case PACKET_OK:
6127 if (!target_is_non_stop_p ())
6129 /* Save the reply for later. */
6130 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
6131 strcpy (wait_status, rs->buf.data ());
6133 else if (strcmp (rs->buf.data (), "OK") != 0)
6134 error (_("Attaching to %s failed with: %s"),
6135 target_pid_to_str (ptid_t (pid)).c_str (),
6136 rs->buf.data ());
6137 break;
6138 case PACKET_UNKNOWN:
6139 error (_("This target does not support attaching to a process"));
6140 default:
6141 error (_("Attaching to %s failed"),
6142 target_pid_to_str (ptid_t (pid)).c_str ());
6145 switch_to_inferior_no_thread (remote_add_inferior (false, pid, 1, 0));
6147 inferior_ptid = ptid_t (pid);
6149 if (target_is_non_stop_p ())
6151 /* Get list of threads. */
6152 update_thread_list ();
6154 thread_info *thread = first_thread_of_inferior (current_inferior ());
6155 if (thread != nullptr)
6156 switch_to_thread (thread);
6158 /* Invalidate our notion of the remote current thread. */
6159 record_currthread (rs, minus_one_ptid);
6161 else
6163 /* Now, if we have thread information, update the main thread's
6164 ptid. */
6165 ptid_t curr_ptid = remote_current_thread (ptid_t (pid));
6167 /* Add the main thread to the thread list. We add the thread
6168 silently in this case (the final true parameter). */
6169 thread_info *thr = remote_add_thread (curr_ptid, true, true, true);
6171 switch_to_thread (thr);
6174 /* Next, if the target can specify a description, read it. We do
6175 this before anything involving memory or registers. */
6176 target_find_description ();
6178 if (!target_is_non_stop_p ())
6180 /* Use the previously fetched status. */
6181 gdb_assert (wait_status != NULL);
6183 struct notif_event *reply
6184 = remote_notif_parse (this, &notif_client_stop, wait_status);
6186 push_stop_reply ((struct stop_reply *) reply);
6188 else
6190 gdb_assert (wait_status == NULL);
6192 gdb_assert (target_can_async_p ());
6196 /* Implementation of the to_post_attach method. */
6198 void
6199 extended_remote_target::post_attach (int pid)
6201 /* Get text, data & bss offsets. */
6202 get_offsets ();
6204 /* In certain cases GDB might not have had the chance to start
6205 symbol lookup up until now. This could happen if the debugged
6206 binary is not using shared libraries, the vsyscall page is not
6207 present (on Linux) and the binary itself hadn't changed since the
6208 debugging process was started. */
6209 if (current_program_space->symfile_object_file != NULL)
6210 remote_check_symbols();
6214 /* Check for the availability of vCont. This function should also check
6215 the response. */
6217 void
6218 remote_target::remote_vcont_probe ()
6220 remote_state *rs = get_remote_state ();
6221 char *buf;
6223 strcpy (rs->buf.data (), "vCont?");
6224 putpkt (rs->buf);
6225 getpkt (&rs->buf, 0);
6226 buf = rs->buf.data ();
6228 /* Make sure that the features we assume are supported. */
6229 if (startswith (buf, "vCont"))
6231 char *p = &buf[5];
6232 int support_c, support_C;
6234 rs->supports_vCont.s = 0;
6235 rs->supports_vCont.S = 0;
6236 support_c = 0;
6237 support_C = 0;
6238 rs->supports_vCont.t = 0;
6239 rs->supports_vCont.r = 0;
6240 while (p && *p == ';')
6242 p++;
6243 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
6244 rs->supports_vCont.s = 1;
6245 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
6246 rs->supports_vCont.S = 1;
6247 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
6248 support_c = 1;
6249 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
6250 support_C = 1;
6251 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
6252 rs->supports_vCont.t = 1;
6253 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
6254 rs->supports_vCont.r = 1;
6256 p = strchr (p, ';');
6259 /* If c, and C are not all supported, we can't use vCont. Clearing
6260 BUF will make packet_ok disable the packet. */
6261 if (!support_c || !support_C)
6262 buf[0] = 0;
6265 packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCont]);
6266 rs->supports_vCont_probed = true;
6269 /* Helper function for building "vCont" resumptions. Write a
6270 resumption to P. ENDP points to one-passed-the-end of the buffer
6271 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
6272 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
6273 resumed thread should be single-stepped and/or signalled. If PTID
6274 equals minus_one_ptid, then all threads are resumed; if PTID
6275 represents a process, then all threads of the process are resumed;
6276 the thread to be stepped and/or signalled is given in the global
6277 INFERIOR_PTID. */
6279 char *
6280 remote_target::append_resumption (char *p, char *endp,
6281 ptid_t ptid, int step, gdb_signal siggnal)
6283 struct remote_state *rs = get_remote_state ();
6285 if (step && siggnal != GDB_SIGNAL_0)
6286 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
6287 else if (step
6288 /* GDB is willing to range step. */
6289 && use_range_stepping
6290 /* Target supports range stepping. */
6291 && rs->supports_vCont.r
6292 /* We don't currently support range stepping multiple
6293 threads with a wildcard (though the protocol allows it,
6294 so stubs shouldn't make an active effort to forbid
6295 it). */
6296 && !(remote_multi_process_p (rs) && ptid.is_pid ()))
6298 struct thread_info *tp;
6300 if (ptid == minus_one_ptid)
6302 /* If we don't know about the target thread's tid, then
6303 we're resuming magic_null_ptid (see caller). */
6304 tp = find_thread_ptid (this, magic_null_ptid);
6306 else
6307 tp = find_thread_ptid (this, ptid);
6308 gdb_assert (tp != NULL);
6310 if (tp->control.may_range_step)
6312 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
6314 p += xsnprintf (p, endp - p, ";r%s,%s",
6315 phex_nz (tp->control.step_range_start,
6316 addr_size),
6317 phex_nz (tp->control.step_range_end,
6318 addr_size));
6320 else
6321 p += xsnprintf (p, endp - p, ";s");
6323 else if (step)
6324 p += xsnprintf (p, endp - p, ";s");
6325 else if (siggnal != GDB_SIGNAL_0)
6326 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
6327 else
6328 p += xsnprintf (p, endp - p, ";c");
6330 if (remote_multi_process_p (rs) && ptid.is_pid ())
6332 ptid_t nptid;
6334 /* All (-1) threads of process. */
6335 nptid = ptid_t (ptid.pid (), -1);
6337 p += xsnprintf (p, endp - p, ":");
6338 p = write_ptid (p, endp, nptid);
6340 else if (ptid != minus_one_ptid)
6342 p += xsnprintf (p, endp - p, ":");
6343 p = write_ptid (p, endp, ptid);
6346 return p;
6349 /* Clear the thread's private info on resume. */
6351 static void
6352 resume_clear_thread_private_info (struct thread_info *thread)
6354 if (thread->priv != NULL)
6356 remote_thread_info *priv = get_remote_thread_info (thread);
6358 priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6359 priv->watch_data_address = 0;
6363 /* Append a vCont continue-with-signal action for threads that have a
6364 non-zero stop signal. */
6366 char *
6367 remote_target::append_pending_thread_resumptions (char *p, char *endp,
6368 ptid_t ptid)
6370 for (thread_info *thread : all_non_exited_threads (this, ptid))
6371 if (inferior_ptid != thread->ptid
6372 && thread->stop_signal () != GDB_SIGNAL_0)
6374 p = append_resumption (p, endp, thread->ptid,
6375 0, thread->stop_signal ());
6376 thread->set_stop_signal (GDB_SIGNAL_0);
6377 resume_clear_thread_private_info (thread);
6380 return p;
6383 /* Set the target running, using the packets that use Hc
6384 (c/s/C/S). */
6386 void
6387 remote_target::remote_resume_with_hc (ptid_t ptid, int step,
6388 gdb_signal siggnal)
6390 struct remote_state *rs = get_remote_state ();
6391 char *buf;
6393 rs->last_sent_signal = siggnal;
6394 rs->last_sent_step = step;
6396 /* The c/s/C/S resume packets use Hc, so set the continue
6397 thread. */
6398 if (ptid == minus_one_ptid)
6399 set_continue_thread (any_thread_ptid);
6400 else
6401 set_continue_thread (ptid);
6403 for (thread_info *thread : all_non_exited_threads (this))
6404 resume_clear_thread_private_info (thread);
6406 buf = rs->buf.data ();
6407 if (::execution_direction == EXEC_REVERSE)
6409 /* We don't pass signals to the target in reverse exec mode. */
6410 if (info_verbose && siggnal != GDB_SIGNAL_0)
6411 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
6412 siggnal);
6414 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
6415 error (_("Remote reverse-step not supported."));
6416 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
6417 error (_("Remote reverse-continue not supported."));
6419 strcpy (buf, step ? "bs" : "bc");
6421 else if (siggnal != GDB_SIGNAL_0)
6423 buf[0] = step ? 'S' : 'C';
6424 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
6425 buf[2] = tohex (((int) siggnal) & 0xf);
6426 buf[3] = '\0';
6428 else
6429 strcpy (buf, step ? "s" : "c");
6431 putpkt (buf);
6434 /* Resume the remote inferior by using a "vCont" packet. The thread
6435 to be resumed is PTID; STEP and SIGGNAL indicate whether the
6436 resumed thread should be single-stepped and/or signalled. If PTID
6437 equals minus_one_ptid, then all threads are resumed; the thread to
6438 be stepped and/or signalled is given in the global INFERIOR_PTID.
6439 This function returns non-zero iff it resumes the inferior.
6441 This function issues a strict subset of all possible vCont commands
6442 at the moment. */
6445 remote_target::remote_resume_with_vcont (ptid_t ptid, int step,
6446 enum gdb_signal siggnal)
6448 struct remote_state *rs = get_remote_state ();
6449 char *p;
6450 char *endp;
6452 /* No reverse execution actions defined for vCont. */
6453 if (::execution_direction == EXEC_REVERSE)
6454 return 0;
6456 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6457 remote_vcont_probe ();
6459 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
6460 return 0;
6462 p = rs->buf.data ();
6463 endp = p + get_remote_packet_size ();
6465 /* If we could generate a wider range of packets, we'd have to worry
6466 about overflowing BUF. Should there be a generic
6467 "multi-part-packet" packet? */
6469 p += xsnprintf (p, endp - p, "vCont");
6471 if (ptid == magic_null_ptid)
6473 /* MAGIC_NULL_PTID means that we don't have any active threads,
6474 so we don't have any TID numbers the inferior will
6475 understand. Make sure to only send forms that do not specify
6476 a TID. */
6477 append_resumption (p, endp, minus_one_ptid, step, siggnal);
6479 else if (ptid == minus_one_ptid || ptid.is_pid ())
6481 /* Resume all threads (of all processes, or of a single
6482 process), with preference for INFERIOR_PTID. This assumes
6483 inferior_ptid belongs to the set of all threads we are about
6484 to resume. */
6485 if (step || siggnal != GDB_SIGNAL_0)
6487 /* Step inferior_ptid, with or without signal. */
6488 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
6491 /* Also pass down any pending signaled resumption for other
6492 threads not the current. */
6493 p = append_pending_thread_resumptions (p, endp, ptid);
6495 /* And continue others without a signal. */
6496 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
6498 else
6500 /* Scheduler locking; resume only PTID. */
6501 append_resumption (p, endp, ptid, step, siggnal);
6504 gdb_assert (strlen (rs->buf.data ()) < get_remote_packet_size ());
6505 putpkt (rs->buf);
6507 if (target_is_non_stop_p ())
6509 /* In non-stop, the stub replies to vCont with "OK". The stop
6510 reply will be reported asynchronously by means of a `%Stop'
6511 notification. */
6512 getpkt (&rs->buf, 0);
6513 if (strcmp (rs->buf.data (), "OK") != 0)
6514 error (_("Unexpected vCont reply in non-stop mode: %s"),
6515 rs->buf.data ());
6518 return 1;
6521 /* Tell the remote machine to resume. */
6523 void
6524 remote_target::resume (ptid_t ptid, int step, enum gdb_signal siggnal)
6526 struct remote_state *rs = get_remote_state ();
6528 /* When connected in non-stop mode, the core resumes threads
6529 individually. Resuming remote threads directly in target_resume
6530 would thus result in sending one packet per thread. Instead, to
6531 minimize roundtrip latency, here we just store the resume
6532 request (put the thread in RESUMED_PENDING_VCONT state); the actual remote
6533 resumption will be done in remote_target::commit_resume, where we'll be
6534 able to do vCont action coalescing. */
6535 if (target_is_non_stop_p () && ::execution_direction != EXEC_REVERSE)
6537 remote_thread_info *remote_thr;
6539 if (minus_one_ptid == ptid || ptid.is_pid ())
6540 remote_thr = get_remote_thread_info (this, inferior_ptid);
6541 else
6542 remote_thr = get_remote_thread_info (this, ptid);
6544 /* We don't expect the core to ask to resume an already resumed (from
6545 its point of view) thread. */
6546 gdb_assert (remote_thr->get_resume_state () == resume_state::NOT_RESUMED);
6548 remote_thr->set_resumed_pending_vcont (step, siggnal);
6549 return;
6552 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
6553 (explained in remote-notif.c:handle_notification) so
6554 remote_notif_process is not called. We need find a place where
6555 it is safe to start a 'vNotif' sequence. It is good to do it
6556 before resuming inferior, because inferior was stopped and no RSP
6557 traffic at that moment. */
6558 if (!target_is_non_stop_p ())
6559 remote_notif_process (rs->notif_state, &notif_client_stop);
6561 rs->last_resume_exec_dir = ::execution_direction;
6563 /* Prefer vCont, and fallback to s/c/S/C, which use Hc. */
6564 if (!remote_resume_with_vcont (ptid, step, siggnal))
6565 remote_resume_with_hc (ptid, step, siggnal);
6567 /* Update resumed state tracked by the remote target. */
6568 for (thread_info *tp : all_non_exited_threads (this, ptid))
6569 get_remote_thread_info (tp)->set_resumed ();
6571 /* We've just told the target to resume. The remote server will
6572 wait for the inferior to stop, and then send a stop reply. In
6573 the mean time, we can't start another command/query ourselves
6574 because the stub wouldn't be ready to process it. This applies
6575 only to the base all-stop protocol, however. In non-stop (which
6576 only supports vCont), the stub replies with an "OK", and is
6577 immediate able to process further serial input. */
6578 if (!target_is_non_stop_p ())
6579 rs->waiting_for_stop_reply = 1;
6582 /* Private per-inferior info for target remote processes. */
6584 struct remote_inferior : public private_inferior
6586 /* Whether we can send a wildcard vCont for this process. */
6587 bool may_wildcard_vcont = true;
6590 /* Get the remote private inferior data associated to INF. */
6592 static remote_inferior *
6593 get_remote_inferior (inferior *inf)
6595 if (inf->priv == NULL)
6596 inf->priv.reset (new remote_inferior);
6598 return static_cast<remote_inferior *> (inf->priv.get ());
6601 /* Class used to track the construction of a vCont packet in the
6602 outgoing packet buffer. This is used to send multiple vCont
6603 packets if we have more actions than would fit a single packet. */
6605 class vcont_builder
6607 public:
6608 explicit vcont_builder (remote_target *remote)
6609 : m_remote (remote)
6611 restart ();
6614 void flush ();
6615 void push_action (ptid_t ptid, bool step, gdb_signal siggnal);
6617 private:
6618 void restart ();
6620 /* The remote target. */
6621 remote_target *m_remote;
6623 /* Pointer to the first action. P points here if no action has been
6624 appended yet. */
6625 char *m_first_action;
6627 /* Where the next action will be appended. */
6628 char *m_p;
6630 /* The end of the buffer. Must never write past this. */
6631 char *m_endp;
6634 /* Prepare the outgoing buffer for a new vCont packet. */
6636 void
6637 vcont_builder::restart ()
6639 struct remote_state *rs = m_remote->get_remote_state ();
6641 m_p = rs->buf.data ();
6642 m_endp = m_p + m_remote->get_remote_packet_size ();
6643 m_p += xsnprintf (m_p, m_endp - m_p, "vCont");
6644 m_first_action = m_p;
6647 /* If the vCont packet being built has any action, send it to the
6648 remote end. */
6650 void
6651 vcont_builder::flush ()
6653 struct remote_state *rs;
6655 if (m_p == m_first_action)
6656 return;
6658 rs = m_remote->get_remote_state ();
6659 m_remote->putpkt (rs->buf);
6660 m_remote->getpkt (&rs->buf, 0);
6661 if (strcmp (rs->buf.data (), "OK") != 0)
6662 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf.data ());
6665 /* The largest action is range-stepping, with its two addresses. This
6666 is more than sufficient. If a new, bigger action is created, it'll
6667 quickly trigger a failed assertion in append_resumption (and we'll
6668 just bump this). */
6669 #define MAX_ACTION_SIZE 200
6671 /* Append a new vCont action in the outgoing packet being built. If
6672 the action doesn't fit the packet along with previous actions, push
6673 what we've got so far to the remote end and start over a new vCont
6674 packet (with the new action). */
6676 void
6677 vcont_builder::push_action (ptid_t ptid, bool step, gdb_signal siggnal)
6679 char buf[MAX_ACTION_SIZE + 1];
6681 char *endp = m_remote->append_resumption (buf, buf + sizeof (buf),
6682 ptid, step, siggnal);
6684 /* Check whether this new action would fit in the vCont packet along
6685 with previous actions. If not, send what we've got so far and
6686 start a new vCont packet. */
6687 size_t rsize = endp - buf;
6688 if (rsize > m_endp - m_p)
6690 flush ();
6691 restart ();
6693 /* Should now fit. */
6694 gdb_assert (rsize <= m_endp - m_p);
6697 memcpy (m_p, buf, rsize);
6698 m_p += rsize;
6699 *m_p = '\0';
6702 /* to_commit_resume implementation. */
6704 void
6705 remote_target::commit_resumed ()
6707 /* If connected in all-stop mode, we'd send the remote resume
6708 request directly from remote_resume. Likewise if
6709 reverse-debugging, as there are no defined vCont actions for
6710 reverse execution. */
6711 if (!target_is_non_stop_p () || ::execution_direction == EXEC_REVERSE)
6712 return;
6714 /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
6715 instead of resuming all threads of each process individually.
6716 However, if any thread of a process must remain halted, we can't
6717 send wildcard resumes and must send one action per thread.
6719 Care must be taken to not resume threads/processes the server
6720 side already told us are stopped, but the core doesn't know about
6721 yet, because the events are still in the vStopped notification
6722 queue. For example:
6724 #1 => vCont s:p1.1;c
6725 #2 <= OK
6726 #3 <= %Stopped T05 p1.1
6727 #4 => vStopped
6728 #5 <= T05 p1.2
6729 #6 => vStopped
6730 #7 <= OK
6731 #8 (infrun handles the stop for p1.1 and continues stepping)
6732 #9 => vCont s:p1.1;c
6734 The last vCont above would resume thread p1.2 by mistake, because
6735 the server has no idea that the event for p1.2 had not been
6736 handled yet.
6738 The server side must similarly ignore resume actions for the
6739 thread that has a pending %Stopped notification (and any other
6740 threads with events pending), until GDB acks the notification
6741 with vStopped. Otherwise, e.g., the following case is
6742 mishandled:
6744 #1 => g (or any other packet)
6745 #2 <= [registers]
6746 #3 <= %Stopped T05 p1.2
6747 #4 => vCont s:p1.1;c
6748 #5 <= OK
6750 Above, the server must not resume thread p1.2. GDB can't know
6751 that p1.2 stopped until it acks the %Stopped notification, and
6752 since from GDB's perspective all threads should be running, it
6753 sends a "c" action.
6755 Finally, special care must also be given to handling fork/vfork
6756 events. A (v)fork event actually tells us that two processes
6757 stopped -- the parent and the child. Until we follow the fork,
6758 we must not resume the child. Therefore, if we have a pending
6759 fork follow, we must not send a global wildcard resume action
6760 (vCont;c). We can still send process-wide wildcards though. */
6762 /* Start by assuming a global wildcard (vCont;c) is possible. */
6763 bool may_global_wildcard_vcont = true;
6765 /* And assume every process is individually wildcard-able too. */
6766 for (inferior *inf : all_non_exited_inferiors (this))
6768 remote_inferior *priv = get_remote_inferior (inf);
6770 priv->may_wildcard_vcont = true;
6773 /* Check for any pending events (not reported or processed yet) and
6774 disable process and global wildcard resumes appropriately. */
6775 check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
6777 bool any_pending_vcont_resume = false;
6779 for (thread_info *tp : all_non_exited_threads (this))
6781 remote_thread_info *priv = get_remote_thread_info (tp);
6783 /* If a thread of a process is not meant to be resumed, then we
6784 can't wildcard that process. */
6785 if (priv->get_resume_state () == resume_state::NOT_RESUMED)
6787 get_remote_inferior (tp->inf)->may_wildcard_vcont = false;
6789 /* And if we can't wildcard a process, we can't wildcard
6790 everything either. */
6791 may_global_wildcard_vcont = false;
6792 continue;
6795 if (priv->get_resume_state () == resume_state::RESUMED_PENDING_VCONT)
6796 any_pending_vcont_resume = true;
6798 /* If a thread is the parent of an unfollowed fork, then we
6799 can't do a global wildcard, as that would resume the fork
6800 child. */
6801 if (thread_pending_fork_status (tp) != nullptr)
6802 may_global_wildcard_vcont = false;
6805 /* We didn't have any resumed thread pending a vCont resume, so nothing to
6806 do. */
6807 if (!any_pending_vcont_resume)
6808 return;
6810 /* Now let's build the vCont packet(s). Actions must be appended
6811 from narrower to wider scopes (thread -> process -> global). If
6812 we end up with too many actions for a single packet vcont_builder
6813 flushes the current vCont packet to the remote side and starts a
6814 new one. */
6815 struct vcont_builder vcont_builder (this);
6817 /* Threads first. */
6818 for (thread_info *tp : all_non_exited_threads (this))
6820 remote_thread_info *remote_thr = get_remote_thread_info (tp);
6822 /* If the thread was previously vCont-resumed, no need to send a specific
6823 action for it. If we didn't receive a resume request for it, don't
6824 send an action for it either. */
6825 if (remote_thr->get_resume_state () != resume_state::RESUMED_PENDING_VCONT)
6826 continue;
6828 gdb_assert (!thread_is_in_step_over_chain (tp));
6830 /* We should never be commit-resuming a thread that has a stop reply.
6831 Otherwise, we would end up reporting a stop event for a thread while
6832 it is running on the remote target. */
6833 remote_state *rs = get_remote_state ();
6834 for (const auto &stop_reply : rs->stop_reply_queue)
6835 gdb_assert (stop_reply->ptid != tp->ptid);
6837 const resumed_pending_vcont_info &info
6838 = remote_thr->resumed_pending_vcont_info ();
6840 /* Check if we need to send a specific action for this thread. If not,
6841 it will be included in a wildcard resume instead. */
6842 if (info.step || info.sig != GDB_SIGNAL_0
6843 || !get_remote_inferior (tp->inf)->may_wildcard_vcont)
6844 vcont_builder.push_action (tp->ptid, info.step, info.sig);
6846 remote_thr->set_resumed ();
6849 /* Now check whether we can send any process-wide wildcard. This is
6850 to avoid sending a global wildcard in the case nothing is
6851 supposed to be resumed. */
6852 bool any_process_wildcard = false;
6854 for (inferior *inf : all_non_exited_inferiors (this))
6856 if (get_remote_inferior (inf)->may_wildcard_vcont)
6858 any_process_wildcard = true;
6859 break;
6863 if (any_process_wildcard)
6865 /* If all processes are wildcard-able, then send a single "c"
6866 action, otherwise, send an "all (-1) threads of process"
6867 continue action for each running process, if any. */
6868 if (may_global_wildcard_vcont)
6870 vcont_builder.push_action (minus_one_ptid,
6871 false, GDB_SIGNAL_0);
6873 else
6875 for (inferior *inf : all_non_exited_inferiors (this))
6877 if (get_remote_inferior (inf)->may_wildcard_vcont)
6879 vcont_builder.push_action (ptid_t (inf->pid),
6880 false, GDB_SIGNAL_0);
6886 vcont_builder.flush ();
6889 /* Implementation of target_has_pending_events. */
6891 bool
6892 remote_target::has_pending_events ()
6894 if (target_can_async_p ())
6896 remote_state *rs = get_remote_state ();
6898 if (async_event_handler_marked (rs->remote_async_inferior_event_token))
6899 return true;
6901 /* Note that BUFCNT can be negative, indicating sticky
6902 error. */
6903 if (rs->remote_desc->bufcnt != 0)
6904 return true;
6906 return false;
6911 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
6912 thread, all threads of a remote process, or all threads of all
6913 processes. */
6915 void
6916 remote_target::remote_stop_ns (ptid_t ptid)
6918 struct remote_state *rs = get_remote_state ();
6919 char *p = rs->buf.data ();
6920 char *endp = p + get_remote_packet_size ();
6922 /* If any thread that needs to stop was resumed but pending a vCont
6923 resume, generate a phony stop_reply. However, first check
6924 whether the thread wasn't resumed with a signal. Generating a
6925 phony stop in that case would result in losing the signal. */
6926 bool needs_commit = false;
6927 for (thread_info *tp : all_non_exited_threads (this, ptid))
6929 remote_thread_info *remote_thr = get_remote_thread_info (tp);
6931 if (remote_thr->get_resume_state ()
6932 == resume_state::RESUMED_PENDING_VCONT)
6934 const resumed_pending_vcont_info &info
6935 = remote_thr->resumed_pending_vcont_info ();
6936 if (info.sig != GDB_SIGNAL_0)
6938 /* This signal must be forwarded to the inferior. We
6939 could commit-resume just this thread, but its simpler
6940 to just commit-resume everything. */
6941 needs_commit = true;
6942 break;
6947 if (needs_commit)
6948 commit_resumed ();
6949 else
6950 for (thread_info *tp : all_non_exited_threads (this, ptid))
6952 remote_thread_info *remote_thr = get_remote_thread_info (tp);
6954 if (remote_thr->get_resume_state ()
6955 == resume_state::RESUMED_PENDING_VCONT)
6957 remote_debug_printf ("Enqueueing phony stop reply for thread pending "
6958 "vCont-resume (%d, %ld, %s)", tp->ptid.pid(),
6959 tp->ptid.lwp (),
6960 pulongest (tp->ptid.tid ()));
6962 /* Check that the thread wasn't resumed with a signal.
6963 Generating a phony stop would result in losing the
6964 signal. */
6965 const resumed_pending_vcont_info &info
6966 = remote_thr->resumed_pending_vcont_info ();
6967 gdb_assert (info.sig == GDB_SIGNAL_0);
6969 stop_reply *sr = new stop_reply ();
6970 sr->ptid = tp->ptid;
6971 sr->rs = rs;
6972 sr->ws.set_stopped (GDB_SIGNAL_0);
6973 sr->arch = tp->inf->gdbarch;
6974 sr->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6975 sr->watch_data_address = 0;
6976 sr->core = 0;
6977 this->push_stop_reply (sr);
6979 /* Pretend that this thread was actually resumed on the
6980 remote target, then stopped. If we leave it in the
6981 RESUMED_PENDING_VCONT state and the commit_resumed
6982 method is called while the stop reply is still in the
6983 queue, we'll end up reporting a stop event to the core
6984 for that thread while it is running on the remote
6985 target... that would be bad. */
6986 remote_thr->set_resumed ();
6990 /* FIXME: This supports_vCont_probed check is a workaround until
6991 packet_support is per-connection. */
6992 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN
6993 || !rs->supports_vCont_probed)
6994 remote_vcont_probe ();
6996 if (!rs->supports_vCont.t)
6997 error (_("Remote server does not support stopping threads"));
6999 if (ptid == minus_one_ptid
7000 || (!remote_multi_process_p (rs) && ptid.is_pid ()))
7001 p += xsnprintf (p, endp - p, "vCont;t");
7002 else
7004 ptid_t nptid;
7006 p += xsnprintf (p, endp - p, "vCont;t:");
7008 if (ptid.is_pid ())
7009 /* All (-1) threads of process. */
7010 nptid = ptid_t (ptid.pid (), -1);
7011 else
7013 /* Small optimization: if we already have a stop reply for
7014 this thread, no use in telling the stub we want this
7015 stopped. */
7016 if (peek_stop_reply (ptid))
7017 return;
7019 nptid = ptid;
7022 write_ptid (p, endp, nptid);
7025 /* In non-stop, we get an immediate OK reply. The stop reply will
7026 come in asynchronously by notification. */
7027 putpkt (rs->buf);
7028 getpkt (&rs->buf, 0);
7029 if (strcmp (rs->buf.data (), "OK") != 0)
7030 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid).c_str (),
7031 rs->buf.data ());
7034 /* All-stop version of target_interrupt. Sends a break or a ^C to
7035 interrupt the remote target. It is undefined which thread of which
7036 process reports the interrupt. */
7038 void
7039 remote_target::remote_interrupt_as ()
7041 struct remote_state *rs = get_remote_state ();
7043 rs->ctrlc_pending_p = 1;
7045 /* If the inferior is stopped already, but the core didn't know
7046 about it yet, just ignore the request. The pending stop events
7047 will be collected in remote_wait. */
7048 if (stop_reply_queue_length () > 0)
7049 return;
7051 /* Send interrupt_sequence to remote target. */
7052 send_interrupt_sequence ();
7055 /* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
7056 the remote target. It is undefined which thread of which process
7057 reports the interrupt. Throws an error if the packet is not
7058 supported by the server. */
7060 void
7061 remote_target::remote_interrupt_ns ()
7063 struct remote_state *rs = get_remote_state ();
7064 char *p = rs->buf.data ();
7065 char *endp = p + get_remote_packet_size ();
7067 xsnprintf (p, endp - p, "vCtrlC");
7069 /* In non-stop, we get an immediate OK reply. The stop reply will
7070 come in asynchronously by notification. */
7071 putpkt (rs->buf);
7072 getpkt (&rs->buf, 0);
7074 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
7076 case PACKET_OK:
7077 break;
7078 case PACKET_UNKNOWN:
7079 error (_("No support for interrupting the remote target."));
7080 case PACKET_ERROR:
7081 error (_("Interrupting target failed: %s"), rs->buf.data ());
7085 /* Implement the to_stop function for the remote targets. */
7087 void
7088 remote_target::stop (ptid_t ptid)
7090 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7092 if (target_is_non_stop_p ())
7093 remote_stop_ns (ptid);
7094 else
7096 /* We don't currently have a way to transparently pause the
7097 remote target in all-stop mode. Interrupt it instead. */
7098 remote_interrupt_as ();
7102 /* Implement the to_interrupt function for the remote targets. */
7104 void
7105 remote_target::interrupt ()
7107 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7109 if (target_is_non_stop_p ())
7110 remote_interrupt_ns ();
7111 else
7112 remote_interrupt_as ();
7115 /* Implement the to_pass_ctrlc function for the remote targets. */
7117 void
7118 remote_target::pass_ctrlc ()
7120 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7122 struct remote_state *rs = get_remote_state ();
7124 /* If we're starting up, we're not fully synced yet. Quit
7125 immediately. */
7126 if (rs->starting_up)
7127 quit ();
7128 /* If ^C has already been sent once, offer to disconnect. */
7129 else if (rs->ctrlc_pending_p)
7130 interrupt_query ();
7131 else
7132 target_interrupt ();
7135 /* Ask the user what to do when an interrupt is received. */
7137 void
7138 remote_target::interrupt_query ()
7140 struct remote_state *rs = get_remote_state ();
7142 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
7144 if (query (_("The target is not responding to interrupt requests.\n"
7145 "Stop debugging it? ")))
7147 remote_unpush_target (this);
7148 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
7151 else
7153 if (query (_("Interrupted while waiting for the program.\n"
7154 "Give up waiting? ")))
7155 quit ();
7159 /* Enable/disable target terminal ownership. Most targets can use
7160 terminal groups to control terminal ownership. Remote targets are
7161 different in that explicit transfer of ownership to/from GDB/target
7162 is required. */
7164 void
7165 remote_target::terminal_inferior ()
7167 /* NOTE: At this point we could also register our selves as the
7168 recipient of all input. Any characters typed could then be
7169 passed on down to the target. */
7172 void
7173 remote_target::terminal_ours ()
7177 static void
7178 remote_console_output (const char *msg)
7180 const char *p;
7182 for (p = msg; p[0] && p[1]; p += 2)
7184 char tb[2];
7185 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
7187 tb[0] = c;
7188 tb[1] = 0;
7189 gdb_stdtarg->puts (tb);
7191 gdb_stdtarg->flush ();
7194 /* Return the length of the stop reply queue. */
7197 remote_target::stop_reply_queue_length ()
7199 remote_state *rs = get_remote_state ();
7200 return rs->stop_reply_queue.size ();
7203 static void
7204 remote_notif_stop_parse (remote_target *remote,
7205 struct notif_client *self, const char *buf,
7206 struct notif_event *event)
7208 remote->remote_parse_stop_reply (buf, (struct stop_reply *) event);
7211 static void
7212 remote_notif_stop_ack (remote_target *remote,
7213 struct notif_client *self, const char *buf,
7214 struct notif_event *event)
7216 struct stop_reply *stop_reply = (struct stop_reply *) event;
7218 /* acknowledge */
7219 putpkt (remote, self->ack_command);
7221 /* Kind can be TARGET_WAITKIND_IGNORE if we have meanwhile discarded
7222 the notification. It was left in the queue because we need to
7223 acknowledge it and pull the rest of the notifications out. */
7224 if (stop_reply->ws.kind () != TARGET_WAITKIND_IGNORE)
7225 remote->push_stop_reply (stop_reply);
7228 static int
7229 remote_notif_stop_can_get_pending_events (remote_target *remote,
7230 struct notif_client *self)
7232 /* We can't get pending events in remote_notif_process for
7233 notification stop, and we have to do this in remote_wait_ns
7234 instead. If we fetch all queued events from stub, remote stub
7235 may exit and we have no chance to process them back in
7236 remote_wait_ns. */
7237 remote_state *rs = remote->get_remote_state ();
7238 mark_async_event_handler (rs->remote_async_inferior_event_token);
7239 return 0;
7242 stop_reply::~stop_reply ()
7244 for (cached_reg_t &reg : regcache)
7245 xfree (reg.data);
7248 static notif_event_up
7249 remote_notif_stop_alloc_reply ()
7251 return notif_event_up (new struct stop_reply ());
7254 /* A client of notification Stop. */
7256 struct notif_client notif_client_stop =
7258 "Stop",
7259 "vStopped",
7260 remote_notif_stop_parse,
7261 remote_notif_stop_ack,
7262 remote_notif_stop_can_get_pending_events,
7263 remote_notif_stop_alloc_reply,
7264 REMOTE_NOTIF_STOP,
7267 /* If CONTEXT contains any fork child threads that have not been
7268 reported yet, remove them from the CONTEXT list. If such a
7269 thread exists it is because we are stopped at a fork catchpoint
7270 and have not yet called follow_fork, which will set up the
7271 host-side data structures for the new process. */
7273 void
7274 remote_target::remove_new_fork_children (threads_listing_context *context)
7276 struct notif_client *notif = &notif_client_stop;
7278 /* For any threads stopped at a fork event, remove the corresponding
7279 fork child threads from the CONTEXT list. */
7280 for (thread_info *thread : all_non_exited_threads (this))
7282 const target_waitstatus *ws = thread_pending_fork_status (thread);
7284 if (ws == nullptr)
7285 continue;
7287 context->remove_thread (ws->child_ptid ());
7290 /* Check for any pending fork events (not reported or processed yet)
7291 in process PID and remove those fork child threads from the
7292 CONTEXT list as well. */
7293 remote_notif_get_pending_events (notif);
7294 for (auto &event : get_remote_state ()->stop_reply_queue)
7295 if (event->ws.kind () == TARGET_WAITKIND_FORKED
7296 || event->ws.kind () == TARGET_WAITKIND_VFORKED)
7297 context->remove_thread (event->ws.child_ptid ());
7298 else if (event->ws.kind () == TARGET_WAITKIND_THREAD_EXITED)
7299 context->remove_thread (event->ptid);
7302 /* Check whether any event pending in the vStopped queue would prevent a
7303 global or process wildcard vCont action. Set *may_global_wildcard to
7304 false if we can't do a global wildcard (vCont;c), and clear the event
7305 inferior's may_wildcard_vcont flag if we can't do a process-wide
7306 wildcard resume (vCont;c:pPID.-1). */
7308 void
7309 remote_target::check_pending_events_prevent_wildcard_vcont
7310 (bool *may_global_wildcard)
7312 struct notif_client *notif = &notif_client_stop;
7314 remote_notif_get_pending_events (notif);
7315 for (auto &event : get_remote_state ()->stop_reply_queue)
7317 if (event->ws.kind () == TARGET_WAITKIND_NO_RESUMED
7318 || event->ws.kind () == TARGET_WAITKIND_NO_HISTORY)
7319 continue;
7321 if (event->ws.kind () == TARGET_WAITKIND_FORKED
7322 || event->ws.kind () == TARGET_WAITKIND_VFORKED)
7323 *may_global_wildcard = false;
7325 /* This may be the first time we heard about this process.
7326 Regardless, we must not do a global wildcard resume, otherwise
7327 we'd resume this process too. */
7328 *may_global_wildcard = false;
7329 if (event->ptid != null_ptid)
7331 inferior *inf = find_inferior_ptid (this, event->ptid);
7332 if (inf != NULL)
7333 get_remote_inferior (inf)->may_wildcard_vcont = false;
7338 /* Discard all pending stop replies of inferior INF. */
7340 void
7341 remote_target::discard_pending_stop_replies (struct inferior *inf)
7343 struct stop_reply *reply;
7344 struct remote_state *rs = get_remote_state ();
7345 struct remote_notif_state *rns = rs->notif_state;
7347 /* This function can be notified when an inferior exists. When the
7348 target is not remote, the notification state is NULL. */
7349 if (rs->remote_desc == NULL)
7350 return;
7352 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
7354 /* Discard the in-flight notification. */
7355 if (reply != NULL && reply->ptid.pid () == inf->pid)
7357 /* Leave the notification pending, since the server expects that
7358 we acknowledge it with vStopped. But clear its contents, so
7359 that later on when we acknowledge it, we also discard it. */
7360 remote_debug_printf
7361 ("discarding in-flight notification: ptid: %s, ws: %s\n",
7362 reply->ptid.to_string().c_str(),
7363 reply->ws.to_string ().c_str ());
7364 reply->ws.set_ignore ();
7367 /* Discard the stop replies we have already pulled with
7368 vStopped. */
7369 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7370 rs->stop_reply_queue.end (),
7371 [=] (const stop_reply_up &event)
7373 return event->ptid.pid () == inf->pid;
7375 for (auto it = iter; it != rs->stop_reply_queue.end (); ++it)
7376 remote_debug_printf
7377 ("discarding queued stop reply: ptid: %s, ws: %s\n",
7378 reply->ptid.to_string().c_str(),
7379 reply->ws.to_string ().c_str ());
7380 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7383 /* Discard the stop replies for RS in stop_reply_queue. */
7385 void
7386 remote_target::discard_pending_stop_replies_in_queue ()
7388 remote_state *rs = get_remote_state ();
7390 /* Discard the stop replies we have already pulled with
7391 vStopped. */
7392 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7393 rs->stop_reply_queue.end (),
7394 [=] (const stop_reply_up &event)
7396 return event->rs == rs;
7398 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7401 /* Remove the first reply in 'stop_reply_queue' which matches
7402 PTID. */
7404 struct stop_reply *
7405 remote_target::remote_notif_remove_queued_reply (ptid_t ptid)
7407 remote_state *rs = get_remote_state ();
7409 auto iter = std::find_if (rs->stop_reply_queue.begin (),
7410 rs->stop_reply_queue.end (),
7411 [=] (const stop_reply_up &event)
7413 return event->ptid.matches (ptid);
7415 struct stop_reply *result;
7416 if (iter == rs->stop_reply_queue.end ())
7417 result = nullptr;
7418 else
7420 result = iter->release ();
7421 rs->stop_reply_queue.erase (iter);
7424 if (notif_debug)
7425 gdb_printf (gdb_stdlog,
7426 "notif: discard queued event: 'Stop' in %s\n",
7427 ptid.to_string ().c_str ());
7429 return result;
7432 /* Look for a queued stop reply belonging to PTID. If one is found,
7433 remove it from the queue, and return it. Returns NULL if none is
7434 found. If there are still queued events left to process, tell the
7435 event loop to get back to target_wait soon. */
7437 struct stop_reply *
7438 remote_target::queued_stop_reply (ptid_t ptid)
7440 remote_state *rs = get_remote_state ();
7441 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
7443 if (!rs->stop_reply_queue.empty () && target_can_async_p ())
7445 /* There's still at least an event left. */
7446 mark_async_event_handler (rs->remote_async_inferior_event_token);
7449 return r;
7452 /* Push a fully parsed stop reply in the stop reply queue. Since we
7453 know that we now have at least one queued event left to pass to the
7454 core side, tell the event loop to get back to target_wait soon. */
7456 void
7457 remote_target::push_stop_reply (struct stop_reply *new_event)
7459 remote_state *rs = get_remote_state ();
7460 rs->stop_reply_queue.push_back (stop_reply_up (new_event));
7462 if (notif_debug)
7463 gdb_printf (gdb_stdlog,
7464 "notif: push 'Stop' %s to queue %d\n",
7465 new_event->ptid.to_string ().c_str (),
7466 int (rs->stop_reply_queue.size ()));
7468 /* Mark the pending event queue only if async mode is currently enabled.
7469 If async mode is not currently enabled, then, if it later becomes
7470 enabled, and there are events in this queue, we will mark the event
7471 token at that point, see remote_target::async. */
7472 if (target_is_async_p ())
7473 mark_async_event_handler (rs->remote_async_inferior_event_token);
7476 /* Returns true if we have a stop reply for PTID. */
7479 remote_target::peek_stop_reply (ptid_t ptid)
7481 remote_state *rs = get_remote_state ();
7482 for (auto &event : rs->stop_reply_queue)
7483 if (ptid == event->ptid
7484 && event->ws.kind () == TARGET_WAITKIND_STOPPED)
7485 return 1;
7486 return 0;
7489 /* Helper for remote_parse_stop_reply. Return nonzero if the substring
7490 starting with P and ending with PEND matches PREFIX. */
7492 static int
7493 strprefix (const char *p, const char *pend, const char *prefix)
7495 for ( ; p < pend; p++, prefix++)
7496 if (*p != *prefix)
7497 return 0;
7498 return *prefix == '\0';
7501 /* Parse the stop reply in BUF. Either the function succeeds, and the
7502 result is stored in EVENT, or throws an error. */
7504 void
7505 remote_target::remote_parse_stop_reply (const char *buf, stop_reply *event)
7507 remote_arch_state *rsa = NULL;
7508 ULONGEST addr;
7509 const char *p;
7510 int skipregs = 0;
7512 event->ptid = null_ptid;
7513 event->rs = get_remote_state ();
7514 event->ws.set_ignore ();
7515 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
7516 event->regcache.clear ();
7517 event->core = -1;
7519 switch (buf[0])
7521 case 'T': /* Status with PC, SP, FP, ... */
7522 /* Expedited reply, containing Signal, {regno, reg} repeat. */
7523 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
7524 ss = signal number
7525 n... = register number
7526 r... = register contents
7529 p = &buf[3]; /* after Txx */
7530 while (*p)
7532 const char *p1;
7533 int fieldsize;
7535 p1 = strchr (p, ':');
7536 if (p1 == NULL)
7537 error (_("Malformed packet(a) (missing colon): %s\n\
7538 Packet: '%s'\n"),
7539 p, buf);
7540 if (p == p1)
7541 error (_("Malformed packet(a) (missing register number): %s\n\
7542 Packet: '%s'\n"),
7543 p, buf);
7545 /* Some "registers" are actually extended stop information.
7546 Note if you're adding a new entry here: GDB 7.9 and
7547 earlier assume that all register "numbers" that start
7548 with an hex digit are real register numbers. Make sure
7549 the server only sends such a packet if it knows the
7550 client understands it. */
7552 if (strprefix (p, p1, "thread"))
7553 event->ptid = read_ptid (++p1, &p);
7554 else if (strprefix (p, p1, "syscall_entry"))
7556 ULONGEST sysno;
7558 p = unpack_varlen_hex (++p1, &sysno);
7559 event->ws.set_syscall_entry ((int) sysno);
7561 else if (strprefix (p, p1, "syscall_return"))
7563 ULONGEST sysno;
7565 p = unpack_varlen_hex (++p1, &sysno);
7566 event->ws.set_syscall_return ((int) sysno);
7568 else if (strprefix (p, p1, "watch")
7569 || strprefix (p, p1, "rwatch")
7570 || strprefix (p, p1, "awatch"))
7572 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
7573 p = unpack_varlen_hex (++p1, &addr);
7574 event->watch_data_address = (CORE_ADDR) addr;
7576 else if (strprefix (p, p1, "swbreak"))
7578 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
7580 /* Make sure the stub doesn't forget to indicate support
7581 with qSupported. */
7582 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
7583 error (_("Unexpected swbreak stop reason"));
7585 /* The value part is documented as "must be empty",
7586 though we ignore it, in case we ever decide to make
7587 use of it in a backward compatible way. */
7588 p = strchrnul (p1 + 1, ';');
7590 else if (strprefix (p, p1, "hwbreak"))
7592 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
7594 /* Make sure the stub doesn't forget to indicate support
7595 with qSupported. */
7596 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
7597 error (_("Unexpected hwbreak stop reason"));
7599 /* See above. */
7600 p = strchrnul (p1 + 1, ';');
7602 else if (strprefix (p, p1, "library"))
7604 event->ws.set_loaded ();
7605 p = strchrnul (p1 + 1, ';');
7607 else if (strprefix (p, p1, "replaylog"))
7609 event->ws.set_no_history ();
7610 /* p1 will indicate "begin" or "end", but it makes
7611 no difference for now, so ignore it. */
7612 p = strchrnul (p1 + 1, ';');
7614 else if (strprefix (p, p1, "core"))
7616 ULONGEST c;
7618 p = unpack_varlen_hex (++p1, &c);
7619 event->core = c;
7621 else if (strprefix (p, p1, "fork"))
7622 event->ws.set_forked (read_ptid (++p1, &p));
7623 else if (strprefix (p, p1, "vfork"))
7624 event->ws.set_vforked (read_ptid (++p1, &p));
7625 else if (strprefix (p, p1, "vforkdone"))
7627 event->ws.set_vfork_done ();
7628 p = strchrnul (p1 + 1, ';');
7630 else if (strprefix (p, p1, "exec"))
7632 ULONGEST ignored;
7633 int pathlen;
7635 /* Determine the length of the execd pathname. */
7636 p = unpack_varlen_hex (++p1, &ignored);
7637 pathlen = (p - p1) / 2;
7639 /* Save the pathname for event reporting and for
7640 the next run command. */
7641 gdb::unique_xmalloc_ptr<char> pathname
7642 ((char *) xmalloc (pathlen + 1));
7643 hex2bin (p1, (gdb_byte *) pathname.get (), pathlen);
7644 pathname.get ()[pathlen] = '\0';
7646 /* This is freed during event handling. */
7647 event->ws.set_execd (std::move (pathname));
7649 /* Skip the registers included in this packet, since
7650 they may be for an architecture different from the
7651 one used by the original program. */
7652 skipregs = 1;
7654 else if (strprefix (p, p1, "create"))
7656 event->ws.set_thread_created ();
7657 p = strchrnul (p1 + 1, ';');
7659 else
7661 ULONGEST pnum;
7662 const char *p_temp;
7664 if (skipregs)
7666 p = strchrnul (p1 + 1, ';');
7667 p++;
7668 continue;
7671 /* Maybe a real ``P'' register number. */
7672 p_temp = unpack_varlen_hex (p, &pnum);
7673 /* If the first invalid character is the colon, we got a
7674 register number. Otherwise, it's an unknown stop
7675 reason. */
7676 if (p_temp == p1)
7678 /* If we haven't parsed the event's thread yet, find
7679 it now, in order to find the architecture of the
7680 reported expedited registers. */
7681 if (event->ptid == null_ptid)
7683 /* If there is no thread-id information then leave
7684 the event->ptid as null_ptid. Later in
7685 process_stop_reply we will pick a suitable
7686 thread. */
7687 const char *thr = strstr (p1 + 1, ";thread:");
7688 if (thr != NULL)
7689 event->ptid = read_ptid (thr + strlen (";thread:"),
7690 NULL);
7693 if (rsa == NULL)
7695 inferior *inf
7696 = (event->ptid == null_ptid
7697 ? NULL
7698 : find_inferior_ptid (this, event->ptid));
7699 /* If this is the first time we learn anything
7700 about this process, skip the registers
7701 included in this packet, since we don't yet
7702 know which architecture to use to parse them.
7703 We'll determine the architecture later when
7704 we process the stop reply and retrieve the
7705 target description, via
7706 remote_notice_new_inferior ->
7707 post_create_inferior. */
7708 if (inf == NULL)
7710 p = strchrnul (p1 + 1, ';');
7711 p++;
7712 continue;
7715 event->arch = inf->gdbarch;
7716 rsa = event->rs->get_remote_arch_state (event->arch);
7719 packet_reg *reg
7720 = packet_reg_from_pnum (event->arch, rsa, pnum);
7721 cached_reg_t cached_reg;
7723 if (reg == NULL)
7724 error (_("Remote sent bad register number %s: %s\n\
7725 Packet: '%s'\n"),
7726 hex_string (pnum), p, buf);
7728 cached_reg.num = reg->regnum;
7729 cached_reg.data = (gdb_byte *)
7730 xmalloc (register_size (event->arch, reg->regnum));
7732 p = p1 + 1;
7733 fieldsize = hex2bin (p, cached_reg.data,
7734 register_size (event->arch, reg->regnum));
7735 p += 2 * fieldsize;
7736 if (fieldsize < register_size (event->arch, reg->regnum))
7737 warning (_("Remote reply is too short: %s"), buf);
7739 event->regcache.push_back (cached_reg);
7741 else
7743 /* Not a number. Silently skip unknown optional
7744 info. */
7745 p = strchrnul (p1 + 1, ';');
7749 if (*p != ';')
7750 error (_("Remote register badly formatted: %s\nhere: %s"),
7751 buf, p);
7752 ++p;
7755 if (event->ws.kind () != TARGET_WAITKIND_IGNORE)
7756 break;
7758 /* fall through */
7759 case 'S': /* Old style status, just signal only. */
7761 int sig;
7763 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
7764 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
7765 event->ws.set_stopped ((enum gdb_signal) sig);
7766 else
7767 event->ws.set_stopped (GDB_SIGNAL_UNKNOWN);
7769 break;
7770 case 'w': /* Thread exited. */
7772 ULONGEST value;
7774 p = unpack_varlen_hex (&buf[1], &value);
7775 event->ws.set_thread_exited (value);
7776 if (*p != ';')
7777 error (_("stop reply packet badly formatted: %s"), buf);
7778 event->ptid = read_ptid (++p, NULL);
7779 break;
7781 case 'W': /* Target exited. */
7782 case 'X':
7784 ULONGEST value;
7786 /* GDB used to accept only 2 hex chars here. Stubs should
7787 only send more if they detect GDB supports multi-process
7788 support. */
7789 p = unpack_varlen_hex (&buf[1], &value);
7791 if (buf[0] == 'W')
7793 /* The remote process exited. */
7794 event->ws.set_exited (value);
7796 else
7798 /* The remote process exited with a signal. */
7799 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
7800 event->ws.set_signalled ((enum gdb_signal) value);
7801 else
7802 event->ws.set_signalled (GDB_SIGNAL_UNKNOWN);
7805 /* If no process is specified, return null_ptid, and let the
7806 caller figure out the right process to use. */
7807 int pid = 0;
7808 if (*p == '\0')
7810 else if (*p == ';')
7812 p++;
7814 if (*p == '\0')
7816 else if (startswith (p, "process:"))
7818 ULONGEST upid;
7820 p += sizeof ("process:") - 1;
7821 unpack_varlen_hex (p, &upid);
7822 pid = upid;
7824 else
7825 error (_("unknown stop reply packet: %s"), buf);
7827 else
7828 error (_("unknown stop reply packet: %s"), buf);
7829 event->ptid = ptid_t (pid);
7831 break;
7832 case 'N':
7833 event->ws.set_no_resumed ();
7834 event->ptid = minus_one_ptid;
7835 break;
7839 /* When the stub wants to tell GDB about a new notification reply, it
7840 sends a notification (%Stop, for example). Those can come it at
7841 any time, hence, we have to make sure that any pending
7842 putpkt/getpkt sequence we're making is finished, before querying
7843 the stub for more events with the corresponding ack command
7844 (vStopped, for example). E.g., if we started a vStopped sequence
7845 immediately upon receiving the notification, something like this
7846 could happen:
7848 1.1) --> Hg 1
7849 1.2) <-- OK
7850 1.3) --> g
7851 1.4) <-- %Stop
7852 1.5) --> vStopped
7853 1.6) <-- (registers reply to step #1.3)
7855 Obviously, the reply in step #1.6 would be unexpected to a vStopped
7856 query.
7858 To solve this, whenever we parse a %Stop notification successfully,
7859 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
7860 doing whatever we were doing:
7862 2.1) --> Hg 1
7863 2.2) <-- OK
7864 2.3) --> g
7865 2.4) <-- %Stop
7866 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
7867 2.5) <-- (registers reply to step #2.3)
7869 Eventually after step #2.5, we return to the event loop, which
7870 notices there's an event on the
7871 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
7872 associated callback --- the function below. At this point, we're
7873 always safe to start a vStopped sequence. :
7875 2.6) --> vStopped
7876 2.7) <-- T05 thread:2
7877 2.8) --> vStopped
7878 2.9) --> OK
7881 void
7882 remote_target::remote_notif_get_pending_events (notif_client *nc)
7884 struct remote_state *rs = get_remote_state ();
7886 if (rs->notif_state->pending_event[nc->id] != NULL)
7888 if (notif_debug)
7889 gdb_printf (gdb_stdlog,
7890 "notif: process: '%s' ack pending event\n",
7891 nc->name);
7893 /* acknowledge */
7894 nc->ack (this, nc, rs->buf.data (),
7895 rs->notif_state->pending_event[nc->id]);
7896 rs->notif_state->pending_event[nc->id] = NULL;
7898 while (1)
7900 getpkt (&rs->buf, 0);
7901 if (strcmp (rs->buf.data (), "OK") == 0)
7902 break;
7903 else
7904 remote_notif_ack (this, nc, rs->buf.data ());
7907 else
7909 if (notif_debug)
7910 gdb_printf (gdb_stdlog,
7911 "notif: process: '%s' no pending reply\n",
7912 nc->name);
7916 /* Wrapper around remote_target::remote_notif_get_pending_events to
7917 avoid having to export the whole remote_target class. */
7919 void
7920 remote_notif_get_pending_events (remote_target *remote, notif_client *nc)
7922 remote->remote_notif_get_pending_events (nc);
7925 /* Called from process_stop_reply when the stop packet we are responding
7926 to didn't include a process-id or thread-id. STATUS is the stop event
7927 we are responding to.
7929 It is the task of this function to select a suitable thread (or process)
7930 and return its ptid, this is the thread (or process) we will assume the
7931 stop event came from.
7933 In some cases there isn't really any choice about which thread (or
7934 process) is selected, a basic remote with a single process containing a
7935 single thread might choose not to send any process-id or thread-id in
7936 its stop packets, this function will select and return the one and only
7937 thread.
7939 However, if a target supports multiple threads (or processes) and still
7940 doesn't include a thread-id (or process-id) in its stop packet then
7941 first, this is a badly behaving target, and second, we're going to have
7942 to select a thread (or process) at random and use that. This function
7943 will print a warning to the user if it detects that there is the
7944 possibility that GDB is guessing which thread (or process) to
7945 report.
7947 Note that this is called before GDB fetches the updated thread list from the
7948 target. So it's possible for the stop reply to be ambiguous and for GDB to
7949 not realize it. For example, if there's initially one thread, the target
7950 spawns a second thread, and then sends a stop reply without an id that
7951 concerns the first thread. GDB will assume the stop reply is about the
7952 first thread - the only thread it knows about - without printing a warning.
7953 Anyway, if the remote meant for the stop reply to be about the second thread,
7954 then it would be really broken, because GDB doesn't know about that thread
7955 yet. */
7957 ptid_t
7958 remote_target::select_thread_for_ambiguous_stop_reply
7959 (const target_waitstatus &status)
7961 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7963 /* Some stop events apply to all threads in an inferior, while others
7964 only apply to a single thread. */
7965 bool process_wide_stop
7966 = (status.kind () == TARGET_WAITKIND_EXITED
7967 || status.kind () == TARGET_WAITKIND_SIGNALLED);
7969 remote_debug_printf ("process_wide_stop = %d", process_wide_stop);
7971 thread_info *first_resumed_thread = nullptr;
7972 bool ambiguous = false;
7974 /* Consider all non-exited threads of the target, find the first resumed
7975 one. */
7976 for (thread_info *thr : all_non_exited_threads (this))
7978 remote_thread_info *remote_thr = get_remote_thread_info (thr);
7980 if (remote_thr->get_resume_state () != resume_state::RESUMED)
7981 continue;
7983 if (first_resumed_thread == nullptr)
7984 first_resumed_thread = thr;
7985 else if (!process_wide_stop
7986 || first_resumed_thread->ptid.pid () != thr->ptid.pid ())
7987 ambiguous = true;
7990 gdb_assert (first_resumed_thread != nullptr);
7992 remote_debug_printf ("first resumed thread is %s",
7993 pid_to_str (first_resumed_thread->ptid).c_str ());
7994 remote_debug_printf ("is this guess ambiguous? = %d", ambiguous);
7996 /* Warn if the remote target is sending ambiguous stop replies. */
7997 if (ambiguous)
7999 static bool warned = false;
8001 if (!warned)
8003 /* If you are seeing this warning then the remote target has
8004 stopped without specifying a thread-id, but the target
8005 does have multiple threads (or inferiors), and so GDB is
8006 having to guess which thread stopped.
8008 Examples of what might cause this are the target sending
8009 and 'S' stop packet, or a 'T' stop packet and not
8010 including a thread-id.
8012 Additionally, the target might send a 'W' or 'X packet
8013 without including a process-id, when the target has
8014 multiple running inferiors. */
8015 if (process_wide_stop)
8016 warning (_("multi-inferior target stopped without "
8017 "sending a process-id, using first "
8018 "non-exited inferior"));
8019 else
8020 warning (_("multi-threaded target stopped without "
8021 "sending a thread-id, using first "
8022 "non-exited thread"));
8023 warned = true;
8027 /* If this is a stop for all threads then don't use a particular threads
8028 ptid, instead create a new ptid where only the pid field is set. */
8029 if (process_wide_stop)
8030 return ptid_t (first_resumed_thread->ptid.pid ());
8031 else
8032 return first_resumed_thread->ptid;
8035 /* Called when it is decided that STOP_REPLY holds the info of the
8036 event that is to be returned to the core. This function always
8037 destroys STOP_REPLY. */
8039 ptid_t
8040 remote_target::process_stop_reply (struct stop_reply *stop_reply,
8041 struct target_waitstatus *status)
8043 *status = stop_reply->ws;
8044 ptid_t ptid = stop_reply->ptid;
8046 /* If no thread/process was reported by the stub then select a suitable
8047 thread/process. */
8048 if (ptid == null_ptid)
8049 ptid = select_thread_for_ambiguous_stop_reply (*status);
8050 gdb_assert (ptid != null_ptid);
8052 if (status->kind () != TARGET_WAITKIND_EXITED
8053 && status->kind () != TARGET_WAITKIND_SIGNALLED
8054 && status->kind () != TARGET_WAITKIND_NO_RESUMED)
8056 /* Expedited registers. */
8057 if (!stop_reply->regcache.empty ())
8059 struct regcache *regcache
8060 = get_thread_arch_regcache (this, ptid, stop_reply->arch);
8062 for (cached_reg_t &reg : stop_reply->regcache)
8064 regcache->raw_supply (reg.num, reg.data);
8065 xfree (reg.data);
8068 stop_reply->regcache.clear ();
8071 remote_notice_new_inferior (ptid, false);
8072 remote_thread_info *remote_thr = get_remote_thread_info (this, ptid);
8073 remote_thr->core = stop_reply->core;
8074 remote_thr->stop_reason = stop_reply->stop_reason;
8075 remote_thr->watch_data_address = stop_reply->watch_data_address;
8077 if (target_is_non_stop_p ())
8079 /* If the target works in non-stop mode, a stop-reply indicates that
8080 only this thread stopped. */
8081 remote_thr->set_not_resumed ();
8083 else
8085 /* If the target works in all-stop mode, a stop-reply indicates that
8086 all the target's threads stopped. */
8087 for (thread_info *tp : all_non_exited_threads (this))
8088 get_remote_thread_info (tp)->set_not_resumed ();
8092 delete stop_reply;
8093 return ptid;
8096 /* The non-stop mode version of target_wait. */
8098 ptid_t
8099 remote_target::wait_ns (ptid_t ptid, struct target_waitstatus *status,
8100 target_wait_flags options)
8102 struct remote_state *rs = get_remote_state ();
8103 struct stop_reply *stop_reply;
8104 int ret;
8105 int is_notif = 0;
8107 /* If in non-stop mode, get out of getpkt even if a
8108 notification is received. */
8110 ret = getpkt_or_notif_sane (&rs->buf, 0 /* forever */, &is_notif);
8111 while (1)
8113 if (ret != -1 && !is_notif)
8114 switch (rs->buf[0])
8116 case 'E': /* Error of some sort. */
8117 /* We're out of sync with the target now. Did it continue
8118 or not? We can't tell which thread it was in non-stop,
8119 so just ignore this. */
8120 warning (_("Remote failure reply: %s"), rs->buf.data ());
8121 break;
8122 case 'O': /* Console output. */
8123 remote_console_output (&rs->buf[1]);
8124 break;
8125 default:
8126 warning (_("Invalid remote reply: %s"), rs->buf.data ());
8127 break;
8130 /* Acknowledge a pending stop reply that may have arrived in the
8131 mean time. */
8132 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
8133 remote_notif_get_pending_events (&notif_client_stop);
8135 /* If indeed we noticed a stop reply, we're done. */
8136 stop_reply = queued_stop_reply (ptid);
8137 if (stop_reply != NULL)
8138 return process_stop_reply (stop_reply, status);
8140 /* Still no event. If we're just polling for an event, then
8141 return to the event loop. */
8142 if (options & TARGET_WNOHANG)
8144 status->set_ignore ();
8145 return minus_one_ptid;
8148 /* Otherwise do a blocking wait. */
8149 ret = getpkt_or_notif_sane (&rs->buf, 1 /* forever */, &is_notif);
8153 /* Return the first resumed thread. */
8155 static ptid_t
8156 first_remote_resumed_thread (remote_target *target)
8158 for (thread_info *tp : all_non_exited_threads (target, minus_one_ptid))
8159 if (tp->resumed ())
8160 return tp->ptid;
8161 return null_ptid;
8164 /* Wait until the remote machine stops, then return, storing status in
8165 STATUS just as `wait' would. */
8167 ptid_t
8168 remote_target::wait_as (ptid_t ptid, target_waitstatus *status,
8169 target_wait_flags options)
8171 struct remote_state *rs = get_remote_state ();
8172 ptid_t event_ptid = null_ptid;
8173 char *buf;
8174 struct stop_reply *stop_reply;
8176 again:
8178 status->set_ignore ();
8180 stop_reply = queued_stop_reply (ptid);
8181 if (stop_reply != NULL)
8183 /* None of the paths that push a stop reply onto the queue should
8184 have set the waiting_for_stop_reply flag. */
8185 gdb_assert (!rs->waiting_for_stop_reply);
8186 event_ptid = process_stop_reply (stop_reply, status);
8188 else
8190 int forever = ((options & TARGET_WNOHANG) == 0
8191 && rs->wait_forever_enabled_p);
8193 if (!rs->waiting_for_stop_reply)
8195 status->set_no_resumed ();
8196 return minus_one_ptid;
8199 /* FIXME: cagney/1999-09-27: If we're in async mode we should
8200 _never_ wait for ever -> test on target_is_async_p().
8201 However, before we do that we need to ensure that the caller
8202 knows how to take the target into/out of async mode. */
8203 int is_notif;
8204 int ret = getpkt_or_notif_sane (&rs->buf, forever, &is_notif);
8206 /* GDB gets a notification. Return to core as this event is
8207 not interesting. */
8208 if (ret != -1 && is_notif)
8209 return minus_one_ptid;
8211 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
8212 return minus_one_ptid;
8214 buf = rs->buf.data ();
8216 /* Assume that the target has acknowledged Ctrl-C unless we receive
8217 an 'F' or 'O' packet. */
8218 if (buf[0] != 'F' && buf[0] != 'O')
8219 rs->ctrlc_pending_p = 0;
8221 switch (buf[0])
8223 case 'E': /* Error of some sort. */
8224 /* We're out of sync with the target now. Did it continue or
8225 not? Not is more likely, so report a stop. */
8226 rs->waiting_for_stop_reply = 0;
8228 warning (_("Remote failure reply: %s"), buf);
8229 status->set_stopped (GDB_SIGNAL_0);
8230 break;
8231 case 'F': /* File-I/O request. */
8232 /* GDB may access the inferior memory while handling the File-I/O
8233 request, but we don't want GDB accessing memory while waiting
8234 for a stop reply. See the comments in putpkt_binary. Set
8235 waiting_for_stop_reply to 0 temporarily. */
8236 rs->waiting_for_stop_reply = 0;
8237 remote_fileio_request (this, buf, rs->ctrlc_pending_p);
8238 rs->ctrlc_pending_p = 0;
8239 /* GDB handled the File-I/O request, and the target is running
8240 again. Keep waiting for events. */
8241 rs->waiting_for_stop_reply = 1;
8242 break;
8243 case 'N': case 'T': case 'S': case 'X': case 'W':
8245 /* There is a stop reply to handle. */
8246 rs->waiting_for_stop_reply = 0;
8248 stop_reply
8249 = (struct stop_reply *) remote_notif_parse (this,
8250 &notif_client_stop,
8251 rs->buf.data ());
8253 event_ptid = process_stop_reply (stop_reply, status);
8254 break;
8256 case 'O': /* Console output. */
8257 remote_console_output (buf + 1);
8258 break;
8259 case '\0':
8260 if (rs->last_sent_signal != GDB_SIGNAL_0)
8262 /* Zero length reply means that we tried 'S' or 'C' and the
8263 remote system doesn't support it. */
8264 target_terminal::ours_for_output ();
8265 gdb_printf
8266 ("Can't send signals to this remote system. %s not sent.\n",
8267 gdb_signal_to_name (rs->last_sent_signal));
8268 rs->last_sent_signal = GDB_SIGNAL_0;
8269 target_terminal::inferior ();
8271 strcpy (buf, rs->last_sent_step ? "s" : "c");
8272 putpkt (buf);
8273 break;
8275 /* fallthrough */
8276 default:
8277 warning (_("Invalid remote reply: %s"), buf);
8278 break;
8282 if (status->kind () == TARGET_WAITKIND_NO_RESUMED)
8283 return minus_one_ptid;
8284 else if (status->kind () == TARGET_WAITKIND_IGNORE)
8286 /* Nothing interesting happened. If we're doing a non-blocking
8287 poll, we're done. Otherwise, go back to waiting. */
8288 if (options & TARGET_WNOHANG)
8289 return minus_one_ptid;
8290 else
8291 goto again;
8293 else if (status->kind () != TARGET_WAITKIND_EXITED
8294 && status->kind () != TARGET_WAITKIND_SIGNALLED)
8296 if (event_ptid != null_ptid)
8297 record_currthread (rs, event_ptid);
8298 else
8299 event_ptid = first_remote_resumed_thread (this);
8301 else
8303 /* A process exit. Invalidate our notion of current thread. */
8304 record_currthread (rs, minus_one_ptid);
8305 /* It's possible that the packet did not include a pid. */
8306 if (event_ptid == null_ptid)
8307 event_ptid = first_remote_resumed_thread (this);
8308 /* EVENT_PTID could still be NULL_PTID. Double-check. */
8309 if (event_ptid == null_ptid)
8310 event_ptid = magic_null_ptid;
8313 return event_ptid;
8316 /* Wait until the remote machine stops, then return, storing status in
8317 STATUS just as `wait' would. */
8319 ptid_t
8320 remote_target::wait (ptid_t ptid, struct target_waitstatus *status,
8321 target_wait_flags options)
8323 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
8325 remote_state *rs = get_remote_state ();
8327 /* Start by clearing the flag that asks for our wait method to be called,
8328 we'll mark it again at the end if needed. If the target is not in
8329 async mode then the async token should not be marked. */
8330 if (target_is_async_p ())
8331 clear_async_event_handler (rs->remote_async_inferior_event_token);
8332 else
8333 gdb_assert (!async_event_handler_marked
8334 (rs->remote_async_inferior_event_token));
8336 ptid_t event_ptid;
8338 if (target_is_non_stop_p ())
8339 event_ptid = wait_ns (ptid, status, options);
8340 else
8341 event_ptid = wait_as (ptid, status, options);
8343 if (target_is_async_p ())
8345 /* If there are events left in the queue, or unacknowledged
8346 notifications, then tell the event loop to call us again. */
8347 if (!rs->stop_reply_queue.empty ()
8348 || rs->notif_state->pending_event[notif_client_stop.id] != nullptr)
8349 mark_async_event_handler (rs->remote_async_inferior_event_token);
8352 return event_ptid;
8355 /* Fetch a single register using a 'p' packet. */
8358 remote_target::fetch_register_using_p (struct regcache *regcache,
8359 packet_reg *reg)
8361 struct gdbarch *gdbarch = regcache->arch ();
8362 struct remote_state *rs = get_remote_state ();
8363 char *buf, *p;
8364 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
8365 int i;
8367 if (packet_support (PACKET_p) == PACKET_DISABLE)
8368 return 0;
8370 if (reg->pnum == -1)
8371 return 0;
8373 p = rs->buf.data ();
8374 *p++ = 'p';
8375 p += hexnumstr (p, reg->pnum);
8376 *p++ = '\0';
8377 putpkt (rs->buf);
8378 getpkt (&rs->buf, 0);
8380 buf = rs->buf.data ();
8382 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_p]))
8384 case PACKET_OK:
8385 break;
8386 case PACKET_UNKNOWN:
8387 return 0;
8388 case PACKET_ERROR:
8389 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
8390 gdbarch_register_name (regcache->arch (),
8391 reg->regnum),
8392 buf);
8395 /* If this register is unfetchable, tell the regcache. */
8396 if (buf[0] == 'x')
8398 regcache->raw_supply (reg->regnum, NULL);
8399 return 1;
8402 /* Otherwise, parse and supply the value. */
8403 p = buf;
8404 i = 0;
8405 while (p[0] != 0)
8407 if (p[1] == 0)
8408 error (_("fetch_register_using_p: early buf termination"));
8410 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
8411 p += 2;
8413 regcache->raw_supply (reg->regnum, regp);
8414 return 1;
8417 /* Fetch the registers included in the target's 'g' packet. */
8420 remote_target::send_g_packet ()
8422 struct remote_state *rs = get_remote_state ();
8423 int buf_len;
8425 xsnprintf (rs->buf.data (), get_remote_packet_size (), "g");
8426 putpkt (rs->buf);
8427 getpkt (&rs->buf, 0);
8428 if (packet_check_result (rs->buf) == PACKET_ERROR)
8429 error (_("Could not read registers; remote failure reply '%s'"),
8430 rs->buf.data ());
8432 /* We can get out of synch in various cases. If the first character
8433 in the buffer is not a hex character, assume that has happened
8434 and try to fetch another packet to read. */
8435 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
8436 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
8437 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
8438 && rs->buf[0] != 'x') /* New: unavailable register value. */
8440 remote_debug_printf ("Bad register packet; fetching a new packet");
8441 getpkt (&rs->buf, 0);
8444 buf_len = strlen (rs->buf.data ());
8446 /* Sanity check the received packet. */
8447 if (buf_len % 2 != 0)
8448 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf.data ());
8450 return buf_len / 2;
8453 void
8454 remote_target::process_g_packet (struct regcache *regcache)
8456 struct gdbarch *gdbarch = regcache->arch ();
8457 struct remote_state *rs = get_remote_state ();
8458 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8459 int i, buf_len;
8460 char *p;
8461 char *regs;
8463 buf_len = strlen (rs->buf.data ());
8465 /* Further sanity checks, with knowledge of the architecture. */
8466 if (buf_len > 2 * rsa->sizeof_g_packet)
8467 error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
8468 "bytes): %s"),
8469 rsa->sizeof_g_packet, buf_len / 2,
8470 rs->buf.data ());
8472 /* Save the size of the packet sent to us by the target. It is used
8473 as a heuristic when determining the max size of packets that the
8474 target can safely receive. */
8475 if (rsa->actual_register_packet_size == 0)
8476 rsa->actual_register_packet_size = buf_len;
8478 /* If this is smaller than we guessed the 'g' packet would be,
8479 update our records. A 'g' reply that doesn't include a register's
8480 value implies either that the register is not available, or that
8481 the 'p' packet must be used. */
8482 if (buf_len < 2 * rsa->sizeof_g_packet)
8484 long sizeof_g_packet = buf_len / 2;
8486 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8488 long offset = rsa->regs[i].offset;
8489 long reg_size = register_size (gdbarch, i);
8491 if (rsa->regs[i].pnum == -1)
8492 continue;
8494 if (offset >= sizeof_g_packet)
8495 rsa->regs[i].in_g_packet = 0;
8496 else if (offset + reg_size > sizeof_g_packet)
8497 error (_("Truncated register %d in remote 'g' packet"), i);
8498 else
8499 rsa->regs[i].in_g_packet = 1;
8502 /* Looks valid enough, we can assume this is the correct length
8503 for a 'g' packet. It's important not to adjust
8504 rsa->sizeof_g_packet if we have truncated registers otherwise
8505 this "if" won't be run the next time the method is called
8506 with a packet of the same size and one of the internal errors
8507 below will trigger instead. */
8508 rsa->sizeof_g_packet = sizeof_g_packet;
8511 regs = (char *) alloca (rsa->sizeof_g_packet);
8513 /* Unimplemented registers read as all bits zero. */
8514 memset (regs, 0, rsa->sizeof_g_packet);
8516 /* Reply describes registers byte by byte, each byte encoded as two
8517 hex characters. Suck them all up, then supply them to the
8518 register cacheing/storage mechanism. */
8520 p = rs->buf.data ();
8521 for (i = 0; i < rsa->sizeof_g_packet; i++)
8523 if (p[0] == 0 || p[1] == 0)
8524 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
8525 internal_error (__FILE__, __LINE__,
8526 _("unexpected end of 'g' packet reply"));
8528 if (p[0] == 'x' && p[1] == 'x')
8529 regs[i] = 0; /* 'x' */
8530 else
8531 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
8532 p += 2;
8535 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8537 struct packet_reg *r = &rsa->regs[i];
8538 long reg_size = register_size (gdbarch, i);
8540 if (r->in_g_packet)
8542 if ((r->offset + reg_size) * 2 > strlen (rs->buf.data ()))
8543 /* This shouldn't happen - we adjusted in_g_packet above. */
8544 internal_error (__FILE__, __LINE__,
8545 _("unexpected end of 'g' packet reply"));
8546 else if (rs->buf[r->offset * 2] == 'x')
8548 gdb_assert (r->offset * 2 < strlen (rs->buf.data ()));
8549 /* The register isn't available, mark it as such (at
8550 the same time setting the value to zero). */
8551 regcache->raw_supply (r->regnum, NULL);
8553 else
8554 regcache->raw_supply (r->regnum, regs + r->offset);
8559 void
8560 remote_target::fetch_registers_using_g (struct regcache *regcache)
8562 send_g_packet ();
8563 process_g_packet (regcache);
8566 /* Make the remote selected traceframe match GDB's selected
8567 traceframe. */
8569 void
8570 remote_target::set_remote_traceframe ()
8572 int newnum;
8573 struct remote_state *rs = get_remote_state ();
8575 if (rs->remote_traceframe_number == get_traceframe_number ())
8576 return;
8578 /* Avoid recursion, remote_trace_find calls us again. */
8579 rs->remote_traceframe_number = get_traceframe_number ();
8581 newnum = target_trace_find (tfind_number,
8582 get_traceframe_number (), 0, 0, NULL);
8584 /* Should not happen. If it does, all bets are off. */
8585 if (newnum != get_traceframe_number ())
8586 warning (_("could not set remote traceframe"));
8589 void
8590 remote_target::fetch_registers (struct regcache *regcache, int regnum)
8592 struct gdbarch *gdbarch = regcache->arch ();
8593 struct remote_state *rs = get_remote_state ();
8594 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8595 int i;
8597 set_remote_traceframe ();
8598 set_general_thread (regcache->ptid ());
8600 if (regnum >= 0)
8602 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8604 gdb_assert (reg != NULL);
8606 /* If this register might be in the 'g' packet, try that first -
8607 we are likely to read more than one register. If this is the
8608 first 'g' packet, we might be overly optimistic about its
8609 contents, so fall back to 'p'. */
8610 if (reg->in_g_packet)
8612 fetch_registers_using_g (regcache);
8613 if (reg->in_g_packet)
8614 return;
8617 if (fetch_register_using_p (regcache, reg))
8618 return;
8620 /* This register is not available. */
8621 regcache->raw_supply (reg->regnum, NULL);
8623 return;
8626 fetch_registers_using_g (regcache);
8628 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8629 if (!rsa->regs[i].in_g_packet)
8630 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
8632 /* This register is not available. */
8633 regcache->raw_supply (i, NULL);
8637 /* Prepare to store registers. Since we may send them all (using a
8638 'G' request), we have to read out the ones we don't want to change
8639 first. */
8641 void
8642 remote_target::prepare_to_store (struct regcache *regcache)
8644 struct remote_state *rs = get_remote_state ();
8645 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
8646 int i;
8648 /* Make sure the entire registers array is valid. */
8649 switch (packet_support (PACKET_P))
8651 case PACKET_DISABLE:
8652 case PACKET_SUPPORT_UNKNOWN:
8653 /* Make sure all the necessary registers are cached. */
8654 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8655 if (rsa->regs[i].in_g_packet)
8656 regcache->raw_update (rsa->regs[i].regnum);
8657 break;
8658 case PACKET_ENABLE:
8659 break;
8663 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
8664 packet was not recognized. */
8667 remote_target::store_register_using_P (const struct regcache *regcache,
8668 packet_reg *reg)
8670 struct gdbarch *gdbarch = regcache->arch ();
8671 struct remote_state *rs = get_remote_state ();
8672 /* Try storing a single register. */
8673 char *buf = rs->buf.data ();
8674 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
8675 char *p;
8677 if (packet_support (PACKET_P) == PACKET_DISABLE)
8678 return 0;
8680 if (reg->pnum == -1)
8681 return 0;
8683 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
8684 p = buf + strlen (buf);
8685 regcache->raw_collect (reg->regnum, regp);
8686 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
8687 putpkt (rs->buf);
8688 getpkt (&rs->buf, 0);
8690 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
8692 case PACKET_OK:
8693 return 1;
8694 case PACKET_ERROR:
8695 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
8696 gdbarch_register_name (gdbarch, reg->regnum), rs->buf.data ());
8697 case PACKET_UNKNOWN:
8698 return 0;
8699 default:
8700 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8704 /* Store register REGNUM, or all registers if REGNUM == -1, from the
8705 contents of the register cache buffer. FIXME: ignores errors. */
8707 void
8708 remote_target::store_registers_using_G (const struct regcache *regcache)
8710 struct remote_state *rs = get_remote_state ();
8711 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
8712 gdb_byte *regs;
8713 char *p;
8715 /* Extract all the registers in the regcache copying them into a
8716 local buffer. */
8718 int i;
8720 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
8721 memset (regs, 0, rsa->sizeof_g_packet);
8722 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8724 struct packet_reg *r = &rsa->regs[i];
8726 if (r->in_g_packet)
8727 regcache->raw_collect (r->regnum, regs + r->offset);
8731 /* Command describes registers byte by byte,
8732 each byte encoded as two hex characters. */
8733 p = rs->buf.data ();
8734 *p++ = 'G';
8735 bin2hex (regs, p, rsa->sizeof_g_packet);
8736 putpkt (rs->buf);
8737 getpkt (&rs->buf, 0);
8738 if (packet_check_result (rs->buf) == PACKET_ERROR)
8739 error (_("Could not write registers; remote failure reply '%s'"),
8740 rs->buf.data ());
8743 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
8744 of the register cache buffer. FIXME: ignores errors. */
8746 void
8747 remote_target::store_registers (struct regcache *regcache, int regnum)
8749 struct gdbarch *gdbarch = regcache->arch ();
8750 struct remote_state *rs = get_remote_state ();
8751 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8752 int i;
8754 set_remote_traceframe ();
8755 set_general_thread (regcache->ptid ());
8757 if (regnum >= 0)
8759 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8761 gdb_assert (reg != NULL);
8763 /* Always prefer to store registers using the 'P' packet if
8764 possible; we often change only a small number of registers.
8765 Sometimes we change a larger number; we'd need help from a
8766 higher layer to know to use 'G'. */
8767 if (store_register_using_P (regcache, reg))
8768 return;
8770 /* For now, don't complain if we have no way to write the
8771 register. GDB loses track of unavailable registers too
8772 easily. Some day, this may be an error. We don't have
8773 any way to read the register, either... */
8774 if (!reg->in_g_packet)
8775 return;
8777 store_registers_using_G (regcache);
8778 return;
8781 store_registers_using_G (regcache);
8783 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8784 if (!rsa->regs[i].in_g_packet)
8785 if (!store_register_using_P (regcache, &rsa->regs[i]))
8786 /* See above for why we do not issue an error here. */
8787 continue;
8791 /* Return the number of hex digits in num. */
8793 static int
8794 hexnumlen (ULONGEST num)
8796 int i;
8798 for (i = 0; num != 0; i++)
8799 num >>= 4;
8801 return std::max (i, 1);
8804 /* Set BUF to the minimum number of hex digits representing NUM. */
8806 static int
8807 hexnumstr (char *buf, ULONGEST num)
8809 int len = hexnumlen (num);
8811 return hexnumnstr (buf, num, len);
8815 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
8817 static int
8818 hexnumnstr (char *buf, ULONGEST num, int width)
8820 int i;
8822 buf[width] = '\0';
8824 for (i = width - 1; i >= 0; i--)
8826 buf[i] = "0123456789abcdef"[(num & 0xf)];
8827 num >>= 4;
8830 return width;
8833 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
8835 static CORE_ADDR
8836 remote_address_masked (CORE_ADDR addr)
8838 unsigned int address_size = remote_address_size;
8840 /* If "remoteaddresssize" was not set, default to target address size. */
8841 if (!address_size)
8842 address_size = gdbarch_addr_bit (target_gdbarch ());
8844 if (address_size > 0
8845 && address_size < (sizeof (ULONGEST) * 8))
8847 /* Only create a mask when that mask can safely be constructed
8848 in a ULONGEST variable. */
8849 ULONGEST mask = 1;
8851 mask = (mask << address_size) - 1;
8852 addr &= mask;
8854 return addr;
8857 /* Determine whether the remote target supports binary downloading.
8858 This is accomplished by sending a no-op memory write of zero length
8859 to the target at the specified address. It does not suffice to send
8860 the whole packet, since many stubs strip the eighth bit and
8861 subsequently compute a wrong checksum, which causes real havoc with
8862 remote_write_bytes.
8864 NOTE: This can still lose if the serial line is not eight-bit
8865 clean. In cases like this, the user should clear "remote
8866 X-packet". */
8868 void
8869 remote_target::check_binary_download (CORE_ADDR addr)
8871 struct remote_state *rs = get_remote_state ();
8873 switch (packet_support (PACKET_X))
8875 case PACKET_DISABLE:
8876 break;
8877 case PACKET_ENABLE:
8878 break;
8879 case PACKET_SUPPORT_UNKNOWN:
8881 char *p;
8883 p = rs->buf.data ();
8884 *p++ = 'X';
8885 p += hexnumstr (p, (ULONGEST) addr);
8886 *p++ = ',';
8887 p += hexnumstr (p, (ULONGEST) 0);
8888 *p++ = ':';
8889 *p = '\0';
8891 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
8892 getpkt (&rs->buf, 0);
8894 if (rs->buf[0] == '\0')
8896 remote_debug_printf ("binary downloading NOT supported by target");
8897 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
8899 else
8901 remote_debug_printf ("binary downloading supported by target");
8902 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
8904 break;
8909 /* Helper function to resize the payload in order to try to get a good
8910 alignment. We try to write an amount of data such that the next write will
8911 start on an address aligned on REMOTE_ALIGN_WRITES. */
8913 static int
8914 align_for_efficient_write (int todo, CORE_ADDR memaddr)
8916 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
8919 /* Write memory data directly to the remote machine.
8920 This does not inform the data cache; the data cache uses this.
8921 HEADER is the starting part of the packet.
8922 MEMADDR is the address in the remote memory space.
8923 MYADDR is the address of the buffer in our space.
8924 LEN_UNITS is the number of addressable units to write.
8925 UNIT_SIZE is the length in bytes of an addressable unit.
8926 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
8927 should send data as binary ('X'), or hex-encoded ('M').
8929 The function creates packet of the form
8930 <HEADER><ADDRESS>,<LENGTH>:<DATA>
8932 where encoding of <DATA> is terminated by PACKET_FORMAT.
8934 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
8935 are omitted.
8937 Return the transferred status, error or OK (an
8938 'enum target_xfer_status' value). Save the number of addressable units
8939 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
8941 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
8942 exchange between gdb and the stub could look like (?? in place of the
8943 checksum):
8945 -> $m1000,4#??
8946 <- aaaabbbbccccdddd
8948 -> $M1000,3:eeeeffffeeee#??
8949 <- OK
8951 -> $m1000,4#??
8952 <- eeeeffffeeeedddd */
8954 target_xfer_status
8955 remote_target::remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
8956 const gdb_byte *myaddr,
8957 ULONGEST len_units,
8958 int unit_size,
8959 ULONGEST *xfered_len_units,
8960 char packet_format, int use_length)
8962 struct remote_state *rs = get_remote_state ();
8963 char *p;
8964 char *plen = NULL;
8965 int plenlen = 0;
8966 int todo_units;
8967 int units_written;
8968 int payload_capacity_bytes;
8969 int payload_length_bytes;
8971 if (packet_format != 'X' && packet_format != 'M')
8972 internal_error (__FILE__, __LINE__,
8973 _("remote_write_bytes_aux: bad packet format"));
8975 if (len_units == 0)
8976 return TARGET_XFER_EOF;
8978 payload_capacity_bytes = get_memory_write_packet_size ();
8980 /* The packet buffer will be large enough for the payload;
8981 get_memory_packet_size ensures this. */
8982 rs->buf[0] = '\0';
8984 /* Compute the size of the actual payload by subtracting out the
8985 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
8987 payload_capacity_bytes -= strlen ("$,:#NN");
8988 if (!use_length)
8989 /* The comma won't be used. */
8990 payload_capacity_bytes += 1;
8991 payload_capacity_bytes -= strlen (header);
8992 payload_capacity_bytes -= hexnumlen (memaddr);
8994 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
8996 strcat (rs->buf.data (), header);
8997 p = rs->buf.data () + strlen (header);
8999 /* Compute a best guess of the number of bytes actually transfered. */
9000 if (packet_format == 'X')
9002 /* Best guess at number of bytes that will fit. */
9003 todo_units = std::min (len_units,
9004 (ULONGEST) payload_capacity_bytes / unit_size);
9005 if (use_length)
9006 payload_capacity_bytes -= hexnumlen (todo_units);
9007 todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
9009 else
9011 /* Number of bytes that will fit. */
9012 todo_units
9013 = std::min (len_units,
9014 (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
9015 if (use_length)
9016 payload_capacity_bytes -= hexnumlen (todo_units);
9017 todo_units = std::min (todo_units,
9018 (payload_capacity_bytes / unit_size) / 2);
9021 if (todo_units <= 0)
9022 internal_error (__FILE__, __LINE__,
9023 _("minimum packet size too small to write data"));
9025 /* If we already need another packet, then try to align the end
9026 of this packet to a useful boundary. */
9027 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
9028 todo_units = align_for_efficient_write (todo_units, memaddr);
9030 /* Append "<memaddr>". */
9031 memaddr = remote_address_masked (memaddr);
9032 p += hexnumstr (p, (ULONGEST) memaddr);
9034 if (use_length)
9036 /* Append ",". */
9037 *p++ = ',';
9039 /* Append the length and retain its location and size. It may need to be
9040 adjusted once the packet body has been created. */
9041 plen = p;
9042 plenlen = hexnumstr (p, (ULONGEST) todo_units);
9043 p += plenlen;
9046 /* Append ":". */
9047 *p++ = ':';
9048 *p = '\0';
9050 /* Append the packet body. */
9051 if (packet_format == 'X')
9053 /* Binary mode. Send target system values byte by byte, in
9054 increasing byte addresses. Only escape certain critical
9055 characters. */
9056 payload_length_bytes =
9057 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
9058 &units_written, payload_capacity_bytes);
9060 /* If not all TODO units fit, then we'll need another packet. Make
9061 a second try to keep the end of the packet aligned. Don't do
9062 this if the packet is tiny. */
9063 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
9065 int new_todo_units;
9067 new_todo_units = align_for_efficient_write (units_written, memaddr);
9069 if (new_todo_units != units_written)
9070 payload_length_bytes =
9071 remote_escape_output (myaddr, new_todo_units, unit_size,
9072 (gdb_byte *) p, &units_written,
9073 payload_capacity_bytes);
9076 p += payload_length_bytes;
9077 if (use_length && units_written < todo_units)
9079 /* Escape chars have filled up the buffer prematurely,
9080 and we have actually sent fewer units than planned.
9081 Fix-up the length field of the packet. Use the same
9082 number of characters as before. */
9083 plen += hexnumnstr (plen, (ULONGEST) units_written,
9084 plenlen);
9085 *plen = ':'; /* overwrite \0 from hexnumnstr() */
9088 else
9090 /* Normal mode: Send target system values byte by byte, in
9091 increasing byte addresses. Each byte is encoded as a two hex
9092 value. */
9093 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
9094 units_written = todo_units;
9097 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
9098 getpkt (&rs->buf, 0);
9100 if (rs->buf[0] == 'E')
9101 return TARGET_XFER_E_IO;
9103 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
9104 send fewer units than we'd planned. */
9105 *xfered_len_units = (ULONGEST) units_written;
9106 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9109 /* Write memory data directly to the remote machine.
9110 This does not inform the data cache; the data cache uses this.
9111 MEMADDR is the address in the remote memory space.
9112 MYADDR is the address of the buffer in our space.
9113 LEN is the number of bytes.
9115 Return the transferred status, error or OK (an
9116 'enum target_xfer_status' value). Save the number of bytes
9117 transferred in *XFERED_LEN. Only transfer a single packet. */
9119 target_xfer_status
9120 remote_target::remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr,
9121 ULONGEST len, int unit_size,
9122 ULONGEST *xfered_len)
9124 const char *packet_format = NULL;
9126 /* Check whether the target supports binary download. */
9127 check_binary_download (memaddr);
9129 switch (packet_support (PACKET_X))
9131 case PACKET_ENABLE:
9132 packet_format = "X";
9133 break;
9134 case PACKET_DISABLE:
9135 packet_format = "M";
9136 break;
9137 case PACKET_SUPPORT_UNKNOWN:
9138 internal_error (__FILE__, __LINE__,
9139 _("remote_write_bytes: bad internal state"));
9140 default:
9141 internal_error (__FILE__, __LINE__, _("bad switch"));
9144 return remote_write_bytes_aux (packet_format,
9145 memaddr, myaddr, len, unit_size, xfered_len,
9146 packet_format[0], 1);
9149 /* Read memory data directly from the remote machine.
9150 This does not use the data cache; the data cache uses this.
9151 MEMADDR is the address in the remote memory space.
9152 MYADDR is the address of the buffer in our space.
9153 LEN_UNITS is the number of addressable memory units to read..
9154 UNIT_SIZE is the length in bytes of an addressable unit.
9156 Return the transferred status, error or OK (an
9157 'enum target_xfer_status' value). Save the number of bytes
9158 transferred in *XFERED_LEN_UNITS.
9160 See the comment of remote_write_bytes_aux for an example of
9161 memory read/write exchange between gdb and the stub. */
9163 target_xfer_status
9164 remote_target::remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
9165 ULONGEST len_units,
9166 int unit_size, ULONGEST *xfered_len_units)
9168 struct remote_state *rs = get_remote_state ();
9169 int buf_size_bytes; /* Max size of packet output buffer. */
9170 char *p;
9171 int todo_units;
9172 int decoded_bytes;
9174 buf_size_bytes = get_memory_read_packet_size ();
9175 /* The packet buffer will be large enough for the payload;
9176 get_memory_packet_size ensures this. */
9178 /* Number of units that will fit. */
9179 todo_units = std::min (len_units,
9180 (ULONGEST) (buf_size_bytes / unit_size) / 2);
9182 /* Construct "m"<memaddr>","<len>". */
9183 memaddr = remote_address_masked (memaddr);
9184 p = rs->buf.data ();
9185 *p++ = 'm';
9186 p += hexnumstr (p, (ULONGEST) memaddr);
9187 *p++ = ',';
9188 p += hexnumstr (p, (ULONGEST) todo_units);
9189 *p = '\0';
9190 putpkt (rs->buf);
9191 getpkt (&rs->buf, 0);
9192 if (rs->buf[0] == 'E'
9193 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
9194 && rs->buf[3] == '\0')
9195 return TARGET_XFER_E_IO;
9196 /* Reply describes memory byte by byte, each byte encoded as two hex
9197 characters. */
9198 p = rs->buf.data ();
9199 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
9200 /* Return what we have. Let higher layers handle partial reads. */
9201 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
9202 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9205 /* Using the set of read-only target sections of remote, read live
9206 read-only memory.
9208 For interface/parameters/return description see target.h,
9209 to_xfer_partial. */
9211 target_xfer_status
9212 remote_target::remote_xfer_live_readonly_partial (gdb_byte *readbuf,
9213 ULONGEST memaddr,
9214 ULONGEST len,
9215 int unit_size,
9216 ULONGEST *xfered_len)
9218 const struct target_section *secp;
9220 secp = target_section_by_addr (this, memaddr);
9221 if (secp != NULL
9222 && (bfd_section_flags (secp->the_bfd_section) & SEC_READONLY))
9224 ULONGEST memend = memaddr + len;
9226 const target_section_table *table = target_get_section_table (this);
9227 for (const target_section &p : *table)
9229 if (memaddr >= p.addr)
9231 if (memend <= p.endaddr)
9233 /* Entire transfer is within this section. */
9234 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
9235 xfered_len);
9237 else if (memaddr >= p.endaddr)
9239 /* This section ends before the transfer starts. */
9240 continue;
9242 else
9244 /* This section overlaps the transfer. Just do half. */
9245 len = p.endaddr - memaddr;
9246 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
9247 xfered_len);
9253 return TARGET_XFER_EOF;
9256 /* Similar to remote_read_bytes_1, but it reads from the remote stub
9257 first if the requested memory is unavailable in traceframe.
9258 Otherwise, fall back to remote_read_bytes_1. */
9260 target_xfer_status
9261 remote_target::remote_read_bytes (CORE_ADDR memaddr,
9262 gdb_byte *myaddr, ULONGEST len, int unit_size,
9263 ULONGEST *xfered_len)
9265 if (len == 0)
9266 return TARGET_XFER_EOF;
9268 if (get_traceframe_number () != -1)
9270 std::vector<mem_range> available;
9272 /* If we fail to get the set of available memory, then the
9273 target does not support querying traceframe info, and so we
9274 attempt reading from the traceframe anyway (assuming the
9275 target implements the old QTro packet then). */
9276 if (traceframe_available_memory (&available, memaddr, len))
9278 if (available.empty () || available[0].start != memaddr)
9280 enum target_xfer_status res;
9282 /* Don't read into the traceframe's available
9283 memory. */
9284 if (!available.empty ())
9286 LONGEST oldlen = len;
9288 len = available[0].start - memaddr;
9289 gdb_assert (len <= oldlen);
9292 /* This goes through the topmost target again. */
9293 res = remote_xfer_live_readonly_partial (myaddr, memaddr,
9294 len, unit_size, xfered_len);
9295 if (res == TARGET_XFER_OK)
9296 return TARGET_XFER_OK;
9297 else
9299 /* No use trying further, we know some memory starting
9300 at MEMADDR isn't available. */
9301 *xfered_len = len;
9302 return (*xfered_len != 0) ?
9303 TARGET_XFER_UNAVAILABLE : TARGET_XFER_EOF;
9307 /* Don't try to read more than how much is available, in
9308 case the target implements the deprecated QTro packet to
9309 cater for older GDBs (the target's knowledge of read-only
9310 sections may be outdated by now). */
9311 len = available[0].length;
9315 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
9320 /* Sends a packet with content determined by the printf format string
9321 FORMAT and the remaining arguments, then gets the reply. Returns
9322 whether the packet was a success, a failure, or unknown. */
9324 packet_result
9325 remote_target::remote_send_printf (const char *format, ...)
9327 struct remote_state *rs = get_remote_state ();
9328 int max_size = get_remote_packet_size ();
9329 va_list ap;
9331 va_start (ap, format);
9333 rs->buf[0] = '\0';
9334 int size = vsnprintf (rs->buf.data (), max_size, format, ap);
9336 va_end (ap);
9338 if (size >= max_size)
9339 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
9341 if (putpkt (rs->buf) < 0)
9342 error (_("Communication problem with target."));
9344 rs->buf[0] = '\0';
9345 getpkt (&rs->buf, 0);
9347 return packet_check_result (rs->buf);
9350 /* Flash writing can take quite some time. We'll set
9351 effectively infinite timeout for flash operations.
9352 In future, we'll need to decide on a better approach. */
9353 static const int remote_flash_timeout = 1000;
9355 void
9356 remote_target::flash_erase (ULONGEST address, LONGEST length)
9358 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
9359 enum packet_result ret;
9360 scoped_restore restore_timeout
9361 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9363 ret = remote_send_printf ("vFlashErase:%s,%s",
9364 phex (address, addr_size),
9365 phex (length, 4));
9366 switch (ret)
9368 case PACKET_UNKNOWN:
9369 error (_("Remote target does not support flash erase"));
9370 case PACKET_ERROR:
9371 error (_("Error erasing flash with vFlashErase packet"));
9372 default:
9373 break;
9377 target_xfer_status
9378 remote_target::remote_flash_write (ULONGEST address,
9379 ULONGEST length, ULONGEST *xfered_len,
9380 const gdb_byte *data)
9382 scoped_restore restore_timeout
9383 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9384 return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
9385 xfered_len,'X', 0);
9388 void
9389 remote_target::flash_done ()
9391 int ret;
9393 scoped_restore restore_timeout
9394 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9396 ret = remote_send_printf ("vFlashDone");
9398 switch (ret)
9400 case PACKET_UNKNOWN:
9401 error (_("Remote target does not support vFlashDone"));
9402 case PACKET_ERROR:
9403 error (_("Error finishing flash operation"));
9404 default:
9405 break;
9410 /* Stuff for dealing with the packets which are part of this protocol.
9411 See comment at top of file for details. */
9413 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
9414 error to higher layers. Called when a serial error is detected.
9415 The exception message is STRING, followed by a colon and a blank,
9416 the system error message for errno at function entry and final dot
9417 for output compatibility with throw_perror_with_name. */
9419 static void
9420 unpush_and_perror (remote_target *target, const char *string)
9422 int saved_errno = errno;
9424 remote_unpush_target (target);
9425 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
9426 safe_strerror (saved_errno));
9429 /* Read a single character from the remote end. The current quit
9430 handler is overridden to avoid quitting in the middle of packet
9431 sequence, as that would break communication with the remote server.
9432 See remote_serial_quit_handler for more detail. */
9435 remote_target::readchar (int timeout)
9437 int ch;
9438 struct remote_state *rs = get_remote_state ();
9441 scoped_restore restore_quit_target
9442 = make_scoped_restore (&curr_quit_handler_target, this);
9443 scoped_restore restore_quit
9444 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9446 rs->got_ctrlc_during_io = 0;
9448 ch = serial_readchar (rs->remote_desc, timeout);
9450 if (rs->got_ctrlc_during_io)
9451 set_quit_flag ();
9454 if (ch >= 0)
9455 return ch;
9457 switch ((enum serial_rc) ch)
9459 case SERIAL_EOF:
9460 remote_unpush_target (this);
9461 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
9462 /* no return */
9463 case SERIAL_ERROR:
9464 unpush_and_perror (this, _("Remote communication error. "
9465 "Target disconnected."));
9466 /* no return */
9467 case SERIAL_TIMEOUT:
9468 break;
9470 return ch;
9473 /* Wrapper for serial_write that closes the target and throws if
9474 writing fails. The current quit handler is overridden to avoid
9475 quitting in the middle of packet sequence, as that would break
9476 communication with the remote server. See
9477 remote_serial_quit_handler for more detail. */
9479 void
9480 remote_target::remote_serial_write (const char *str, int len)
9482 struct remote_state *rs = get_remote_state ();
9484 scoped_restore restore_quit_target
9485 = make_scoped_restore (&curr_quit_handler_target, this);
9486 scoped_restore restore_quit
9487 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9489 rs->got_ctrlc_during_io = 0;
9491 if (serial_write (rs->remote_desc, str, len))
9493 unpush_and_perror (this, _("Remote communication error. "
9494 "Target disconnected."));
9497 if (rs->got_ctrlc_during_io)
9498 set_quit_flag ();
9501 /* Return a string representing an escaped version of BUF, of len N.
9502 E.g. \n is converted to \\n, \t to \\t, etc. */
9504 static std::string
9505 escape_buffer (const char *buf, int n)
9507 string_file stb;
9509 stb.putstrn (buf, n, '\\');
9510 return stb.release ();
9514 remote_target::putpkt (const char *buf)
9516 return putpkt_binary (buf, strlen (buf));
9519 /* Wrapper around remote_target::putpkt to avoid exporting
9520 remote_target. */
9523 putpkt (remote_target *remote, const char *buf)
9525 return remote->putpkt (buf);
9528 /* Send a packet to the remote machine, with error checking. The data
9529 of the packet is in BUF. The string in BUF can be at most
9530 get_remote_packet_size () - 5 to account for the $, # and checksum,
9531 and for a possible /0 if we are debugging (remote_debug) and want
9532 to print the sent packet as a string. */
9535 remote_target::putpkt_binary (const char *buf, int cnt)
9537 struct remote_state *rs = get_remote_state ();
9538 int i;
9539 unsigned char csum = 0;
9540 gdb::def_vector<char> data (cnt + 6);
9541 char *buf2 = data.data ();
9543 int ch;
9544 int tcount = 0;
9545 char *p;
9547 /* Catch cases like trying to read memory or listing threads while
9548 we're waiting for a stop reply. The remote server wouldn't be
9549 ready to handle this request, so we'd hang and timeout. We don't
9550 have to worry about this in synchronous mode, because in that
9551 case it's not possible to issue a command while the target is
9552 running. This is not a problem in non-stop mode, because in that
9553 case, the stub is always ready to process serial input. */
9554 if (!target_is_non_stop_p ()
9555 && target_is_async_p ()
9556 && rs->waiting_for_stop_reply)
9558 error (_("Cannot execute this command while the target is running.\n"
9559 "Use the \"interrupt\" command to stop the target\n"
9560 "and then try again."));
9563 /* Copy the packet into buffer BUF2, encapsulating it
9564 and giving it a checksum. */
9566 p = buf2;
9567 *p++ = '$';
9569 for (i = 0; i < cnt; i++)
9571 csum += buf[i];
9572 *p++ = buf[i];
9574 *p++ = '#';
9575 *p++ = tohex ((csum >> 4) & 0xf);
9576 *p++ = tohex (csum & 0xf);
9578 /* Send it over and over until we get a positive ack. */
9580 while (1)
9582 if (remote_debug)
9584 *p = '\0';
9586 int len = (int) (p - buf2);
9587 int max_chars;
9589 if (remote_packet_max_chars < 0)
9590 max_chars = len;
9591 else
9592 max_chars = remote_packet_max_chars;
9594 std::string str
9595 = escape_buffer (buf2, std::min (len, max_chars));
9597 if (len > max_chars)
9598 remote_debug_printf_nofunc
9599 ("Sending packet: %s [%d bytes omitted]", str.c_str (),
9600 len - max_chars);
9601 else
9602 remote_debug_printf_nofunc ("Sending packet: %s", str.c_str ());
9604 remote_serial_write (buf2, p - buf2);
9606 /* If this is a no acks version of the remote protocol, send the
9607 packet and move on. */
9608 if (rs->noack_mode)
9609 break;
9611 /* Read until either a timeout occurs (-2) or '+' is read.
9612 Handle any notification that arrives in the mean time. */
9613 while (1)
9615 ch = readchar (remote_timeout);
9617 switch (ch)
9619 case '+':
9620 remote_debug_printf_nofunc ("Received Ack");
9621 return 1;
9622 case '-':
9623 remote_debug_printf_nofunc ("Received Nak");
9624 /* FALLTHROUGH */
9625 case SERIAL_TIMEOUT:
9626 tcount++;
9627 if (tcount > 3)
9628 return 0;
9629 break; /* Retransmit buffer. */
9630 case '$':
9632 remote_debug_printf ("Packet instead of Ack, ignoring it");
9633 /* It's probably an old response sent because an ACK
9634 was lost. Gobble up the packet and ack it so it
9635 doesn't get retransmitted when we resend this
9636 packet. */
9637 skip_frame ();
9638 remote_serial_write ("+", 1);
9639 continue; /* Now, go look for +. */
9642 case '%':
9644 int val;
9646 /* If we got a notification, handle it, and go back to looking
9647 for an ack. */
9648 /* We've found the start of a notification. Now
9649 collect the data. */
9650 val = read_frame (&rs->buf);
9651 if (val >= 0)
9653 remote_debug_printf_nofunc
9654 (" Notification received: %s",
9655 escape_buffer (rs->buf.data (), val).c_str ());
9657 handle_notification (rs->notif_state, rs->buf.data ());
9658 /* We're in sync now, rewait for the ack. */
9659 tcount = 0;
9661 else
9662 remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
9663 rs->buf.data ());
9664 continue;
9666 /* fall-through */
9667 default:
9668 remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
9669 rs->buf.data ());
9670 continue;
9672 break; /* Here to retransmit. */
9675 #if 0
9676 /* This is wrong. If doing a long backtrace, the user should be
9677 able to get out next time we call QUIT, without anything as
9678 violent as interrupt_query. If we want to provide a way out of
9679 here without getting to the next QUIT, it should be based on
9680 hitting ^C twice as in remote_wait. */
9681 if (quit_flag)
9683 quit_flag = 0;
9684 interrupt_query ();
9686 #endif
9689 return 0;
9692 /* Come here after finding the start of a frame when we expected an
9693 ack. Do our best to discard the rest of this packet. */
9695 void
9696 remote_target::skip_frame ()
9698 int c;
9700 while (1)
9702 c = readchar (remote_timeout);
9703 switch (c)
9705 case SERIAL_TIMEOUT:
9706 /* Nothing we can do. */
9707 return;
9708 case '#':
9709 /* Discard the two bytes of checksum and stop. */
9710 c = readchar (remote_timeout);
9711 if (c >= 0)
9712 c = readchar (remote_timeout);
9714 return;
9715 case '*': /* Run length encoding. */
9716 /* Discard the repeat count. */
9717 c = readchar (remote_timeout);
9718 if (c < 0)
9719 return;
9720 break;
9721 default:
9722 /* A regular character. */
9723 break;
9728 /* Come here after finding the start of the frame. Collect the rest
9729 into *BUF, verifying the checksum, length, and handling run-length
9730 compression. NUL terminate the buffer. If there is not enough room,
9731 expand *BUF.
9733 Returns -1 on error, number of characters in buffer (ignoring the
9734 trailing NULL) on success. (could be extended to return one of the
9735 SERIAL status indications). */
9737 long
9738 remote_target::read_frame (gdb::char_vector *buf_p)
9740 unsigned char csum;
9741 long bc;
9742 int c;
9743 char *buf = buf_p->data ();
9744 struct remote_state *rs = get_remote_state ();
9746 csum = 0;
9747 bc = 0;
9749 while (1)
9751 c = readchar (remote_timeout);
9752 switch (c)
9754 case SERIAL_TIMEOUT:
9755 remote_debug_printf ("Timeout in mid-packet, retrying");
9756 return -1;
9758 case '$':
9759 remote_debug_printf ("Saw new packet start in middle of old one");
9760 return -1; /* Start a new packet, count retries. */
9762 case '#':
9764 unsigned char pktcsum;
9765 int check_0 = 0;
9766 int check_1 = 0;
9768 buf[bc] = '\0';
9770 check_0 = readchar (remote_timeout);
9771 if (check_0 >= 0)
9772 check_1 = readchar (remote_timeout);
9774 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
9776 remote_debug_printf ("Timeout in checksum, retrying");
9777 return -1;
9779 else if (check_0 < 0 || check_1 < 0)
9781 remote_debug_printf ("Communication error in checksum");
9782 return -1;
9785 /* Don't recompute the checksum; with no ack packets we
9786 don't have any way to indicate a packet retransmission
9787 is necessary. */
9788 if (rs->noack_mode)
9789 return bc;
9791 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
9792 if (csum == pktcsum)
9793 return bc;
9795 remote_debug_printf
9796 ("Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s",
9797 pktcsum, csum, escape_buffer (buf, bc).c_str ());
9799 /* Number of characters in buffer ignoring trailing
9800 NULL. */
9801 return -1;
9803 case '*': /* Run length encoding. */
9805 int repeat;
9807 csum += c;
9808 c = readchar (remote_timeout);
9809 csum += c;
9810 repeat = c - ' ' + 3; /* Compute repeat count. */
9812 /* The character before ``*'' is repeated. */
9814 if (repeat > 0 && repeat <= 255 && bc > 0)
9816 if (bc + repeat - 1 >= buf_p->size () - 1)
9818 /* Make some more room in the buffer. */
9819 buf_p->resize (buf_p->size () + repeat);
9820 buf = buf_p->data ();
9823 memset (&buf[bc], buf[bc - 1], repeat);
9824 bc += repeat;
9825 continue;
9828 buf[bc] = '\0';
9829 gdb_printf (_("Invalid run length encoding: %s\n"), buf);
9830 return -1;
9832 default:
9833 if (bc >= buf_p->size () - 1)
9835 /* Make some more room in the buffer. */
9836 buf_p->resize (buf_p->size () * 2);
9837 buf = buf_p->data ();
9840 buf[bc++] = c;
9841 csum += c;
9842 continue;
9847 /* Set this to the maximum number of seconds to wait instead of waiting forever
9848 in target_wait(). If this timer times out, then it generates an error and
9849 the command is aborted. This replaces most of the need for timeouts in the
9850 GDB test suite, and makes it possible to distinguish between a hung target
9851 and one with slow communications. */
9853 static int watchdog = 0;
9854 static void
9855 show_watchdog (struct ui_file *file, int from_tty,
9856 struct cmd_list_element *c, const char *value)
9858 gdb_printf (file, _("Watchdog timer is %s.\n"), value);
9861 /* Read a packet from the remote machine, with error checking, and
9862 store it in *BUF. Resize *BUF if necessary to hold the result. If
9863 FOREVER, wait forever rather than timing out; this is used (in
9864 synchronous mode) to wait for a target that is is executing user
9865 code to stop. */
9866 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
9867 don't have to change all the calls to getpkt to deal with the
9868 return value, because at the moment I don't know what the right
9869 thing to do it for those. */
9871 void
9872 remote_target::getpkt (gdb::char_vector *buf, int forever)
9874 getpkt_sane (buf, forever);
9878 /* Read a packet from the remote machine, with error checking, and
9879 store it in *BUF. Resize *BUF if necessary to hold the result. If
9880 FOREVER, wait forever rather than timing out; this is used (in
9881 synchronous mode) to wait for a target that is is executing user
9882 code to stop. If FOREVER == 0, this function is allowed to time
9883 out gracefully and return an indication of this to the caller.
9884 Otherwise return the number of bytes read. If EXPECTING_NOTIF,
9885 consider receiving a notification enough reason to return to the
9886 caller. *IS_NOTIF is an output boolean that indicates whether *BUF
9887 holds a notification or not (a regular packet). */
9890 remote_target::getpkt_or_notif_sane_1 (gdb::char_vector *buf,
9891 int forever, int expecting_notif,
9892 int *is_notif)
9894 struct remote_state *rs = get_remote_state ();
9895 int c;
9896 int tries;
9897 int timeout;
9898 int val = -1;
9900 strcpy (buf->data (), "timeout");
9902 if (forever)
9903 timeout = watchdog > 0 ? watchdog : -1;
9904 else if (expecting_notif)
9905 timeout = 0; /* There should already be a char in the buffer. If
9906 not, bail out. */
9907 else
9908 timeout = remote_timeout;
9910 #define MAX_TRIES 3
9912 /* Process any number of notifications, and then return when
9913 we get a packet. */
9914 for (;;)
9916 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
9917 times. */
9918 for (tries = 1; tries <= MAX_TRIES; tries++)
9920 /* This can loop forever if the remote side sends us
9921 characters continuously, but if it pauses, we'll get
9922 SERIAL_TIMEOUT from readchar because of timeout. Then
9923 we'll count that as a retry.
9925 Note that even when forever is set, we will only wait
9926 forever prior to the start of a packet. After that, we
9927 expect characters to arrive at a brisk pace. They should
9928 show up within remote_timeout intervals. */
9930 c = readchar (timeout);
9931 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
9933 if (c == SERIAL_TIMEOUT)
9935 if (expecting_notif)
9936 return -1; /* Don't complain, it's normal to not get
9937 anything in this case. */
9939 if (forever) /* Watchdog went off? Kill the target. */
9941 remote_unpush_target (this);
9942 throw_error (TARGET_CLOSE_ERROR,
9943 _("Watchdog timeout has expired. "
9944 "Target detached."));
9947 remote_debug_printf ("Timed out.");
9949 else
9951 /* We've found the start of a packet or notification.
9952 Now collect the data. */
9953 val = read_frame (buf);
9954 if (val >= 0)
9955 break;
9958 remote_serial_write ("-", 1);
9961 if (tries > MAX_TRIES)
9963 /* We have tried hard enough, and just can't receive the
9964 packet/notification. Give up. */
9965 gdb_printf (_("Ignoring packet error, continuing...\n"));
9967 /* Skip the ack char if we're in no-ack mode. */
9968 if (!rs->noack_mode)
9969 remote_serial_write ("+", 1);
9970 return -1;
9973 /* If we got an ordinary packet, return that to our caller. */
9974 if (c == '$')
9976 if (remote_debug)
9978 int max_chars;
9980 if (remote_packet_max_chars < 0)
9981 max_chars = val;
9982 else
9983 max_chars = remote_packet_max_chars;
9985 std::string str
9986 = escape_buffer (buf->data (),
9987 std::min (val, max_chars));
9989 if (val > max_chars)
9990 remote_debug_printf_nofunc
9991 ("Packet received: %s [%d bytes omitted]", str.c_str (),
9992 val - max_chars);
9993 else
9994 remote_debug_printf_nofunc ("Packet received: %s",
9995 str.c_str ());
9998 /* Skip the ack char if we're in no-ack mode. */
9999 if (!rs->noack_mode)
10000 remote_serial_write ("+", 1);
10001 if (is_notif != NULL)
10002 *is_notif = 0;
10003 return val;
10006 /* If we got a notification, handle it, and go back to looking
10007 for a packet. */
10008 else
10010 gdb_assert (c == '%');
10012 remote_debug_printf_nofunc
10013 (" Notification received: %s",
10014 escape_buffer (buf->data (), val).c_str ());
10016 if (is_notif != NULL)
10017 *is_notif = 1;
10019 handle_notification (rs->notif_state, buf->data ());
10021 /* Notifications require no acknowledgement. */
10023 if (expecting_notif)
10024 return val;
10030 remote_target::getpkt_sane (gdb::char_vector *buf, int forever)
10032 return getpkt_or_notif_sane_1 (buf, forever, 0, NULL);
10036 remote_target::getpkt_or_notif_sane (gdb::char_vector *buf, int forever,
10037 int *is_notif)
10039 return getpkt_or_notif_sane_1 (buf, forever, 1, is_notif);
10042 /* Kill any new fork children of inferior INF that haven't been
10043 processed by follow_fork. */
10045 void
10046 remote_target::kill_new_fork_children (inferior *inf)
10048 remote_state *rs = get_remote_state ();
10049 struct notif_client *notif = &notif_client_stop;
10051 /* Kill the fork child threads of any threads in inferior INF that are stopped
10052 at a fork event. */
10053 for (thread_info *thread : inf->non_exited_threads ())
10055 const target_waitstatus *ws = thread_pending_fork_status (thread);
10057 if (ws == nullptr)
10058 continue;
10060 int child_pid = ws->child_ptid ().pid ();
10061 int res = remote_vkill (child_pid);
10063 if (res != 0)
10064 error (_("Can't kill fork child process %d"), child_pid);
10067 /* Check for any pending fork events (not reported or processed yet)
10068 in inferior INF and kill those fork child threads as well. */
10069 remote_notif_get_pending_events (notif);
10070 for (auto &event : rs->stop_reply_queue)
10072 if (event->ptid.pid () != inf->pid)
10073 continue;
10075 if (!is_fork_status (event->ws.kind ()))
10076 continue;
10078 int child_pid = event->ws.child_ptid ().pid ();
10079 int res = remote_vkill (child_pid);
10081 if (res != 0)
10082 error (_("Can't kill fork child process %d"), child_pid);
10087 /* Target hook to kill the current inferior. */
10089 void
10090 remote_target::kill ()
10092 int res = -1;
10093 inferior *inf = find_inferior_pid (this, inferior_ptid.pid ());
10094 struct remote_state *rs = get_remote_state ();
10096 gdb_assert (inf != nullptr);
10098 if (packet_support (PACKET_vKill) != PACKET_DISABLE)
10100 /* If we're stopped while forking and we haven't followed yet,
10101 kill the child task. We need to do this before killing the
10102 parent task because if this is a vfork then the parent will
10103 be sleeping. */
10104 kill_new_fork_children (inf);
10106 res = remote_vkill (inf->pid);
10107 if (res == 0)
10109 target_mourn_inferior (inferior_ptid);
10110 return;
10114 /* If we are in 'target remote' mode and we are killing the only
10115 inferior, then we will tell gdbserver to exit and unpush the
10116 target. */
10117 if (res == -1 && !remote_multi_process_p (rs)
10118 && number_of_live_inferiors (this) == 1)
10120 remote_kill_k ();
10122 /* We've killed the remote end, we get to mourn it. If we are
10123 not in extended mode, mourning the inferior also unpushes
10124 remote_ops from the target stack, which closes the remote
10125 connection. */
10126 target_mourn_inferior (inferior_ptid);
10128 return;
10131 error (_("Can't kill process"));
10134 /* Send a kill request to the target using the 'vKill' packet. */
10137 remote_target::remote_vkill (int pid)
10139 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
10140 return -1;
10142 remote_state *rs = get_remote_state ();
10144 /* Tell the remote target to detach. */
10145 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vKill;%x", pid);
10146 putpkt (rs->buf);
10147 getpkt (&rs->buf, 0);
10149 switch (packet_ok (rs->buf,
10150 &remote_protocol_packets[PACKET_vKill]))
10152 case PACKET_OK:
10153 return 0;
10154 case PACKET_ERROR:
10155 return 1;
10156 case PACKET_UNKNOWN:
10157 return -1;
10158 default:
10159 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
10163 /* Send a kill request to the target using the 'k' packet. */
10165 void
10166 remote_target::remote_kill_k ()
10168 /* Catch errors so the user can quit from gdb even when we
10169 aren't on speaking terms with the remote system. */
10172 putpkt ("k");
10174 catch (const gdb_exception_error &ex)
10176 if (ex.error == TARGET_CLOSE_ERROR)
10178 /* If we got an (EOF) error that caused the target
10179 to go away, then we're done, that's what we wanted.
10180 "k" is susceptible to cause a premature EOF, given
10181 that the remote server isn't actually required to
10182 reply to "k", and it can happen that it doesn't
10183 even get to reply ACK to the "k". */
10184 return;
10187 /* Otherwise, something went wrong. We didn't actually kill
10188 the target. Just propagate the exception, and let the
10189 user or higher layers decide what to do. */
10190 throw;
10194 void
10195 remote_target::mourn_inferior ()
10197 struct remote_state *rs = get_remote_state ();
10199 /* We're no longer interested in notification events of an inferior
10200 that exited or was killed/detached. */
10201 discard_pending_stop_replies (current_inferior ());
10203 /* In 'target remote' mode with one inferior, we close the connection. */
10204 if (!rs->extended && number_of_live_inferiors (this) <= 1)
10206 remote_unpush_target (this);
10207 return;
10210 /* In case we got here due to an error, but we're going to stay
10211 connected. */
10212 rs->waiting_for_stop_reply = 0;
10214 /* If the current general thread belonged to the process we just
10215 detached from or has exited, the remote side current general
10216 thread becomes undefined. Considering a case like this:
10218 - We just got here due to a detach.
10219 - The process that we're detaching from happens to immediately
10220 report a global breakpoint being hit in non-stop mode, in the
10221 same thread we had selected before.
10222 - GDB attaches to this process again.
10223 - This event happens to be the next event we handle.
10225 GDB would consider that the current general thread didn't need to
10226 be set on the stub side (with Hg), since for all it knew,
10227 GENERAL_THREAD hadn't changed.
10229 Notice that although in all-stop mode, the remote server always
10230 sets the current thread to the thread reporting the stop event,
10231 that doesn't happen in non-stop mode; in non-stop, the stub *must
10232 not* change the current thread when reporting a breakpoint hit,
10233 due to the decoupling of event reporting and event handling.
10235 To keep things simple, we always invalidate our notion of the
10236 current thread. */
10237 record_currthread (rs, minus_one_ptid);
10239 /* Call common code to mark the inferior as not running. */
10240 generic_mourn_inferior ();
10243 bool
10244 extended_remote_target::supports_disable_randomization ()
10246 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
10249 void
10250 remote_target::extended_remote_disable_randomization (int val)
10252 struct remote_state *rs = get_remote_state ();
10253 char *reply;
10255 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10256 "QDisableRandomization:%x", val);
10257 putpkt (rs->buf);
10258 reply = remote_get_noisy_reply ();
10259 if (*reply == '\0')
10260 error (_("Target does not support QDisableRandomization."));
10261 if (strcmp (reply, "OK") != 0)
10262 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
10266 remote_target::extended_remote_run (const std::string &args)
10268 struct remote_state *rs = get_remote_state ();
10269 int len;
10270 const char *remote_exec_file = get_remote_exec_file ();
10272 /* If the user has disabled vRun support, or we have detected that
10273 support is not available, do not try it. */
10274 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
10275 return -1;
10277 strcpy (rs->buf.data (), "vRun;");
10278 len = strlen (rs->buf.data ());
10280 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
10281 error (_("Remote file name too long for run packet"));
10282 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf.data () + len,
10283 strlen (remote_exec_file));
10285 if (!args.empty ())
10287 int i;
10289 gdb_argv argv (args.c_str ());
10290 for (i = 0; argv[i] != NULL; i++)
10292 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
10293 error (_("Argument list too long for run packet"));
10294 rs->buf[len++] = ';';
10295 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf.data () + len,
10296 strlen (argv[i]));
10300 rs->buf[len++] = '\0';
10302 putpkt (rs->buf);
10303 getpkt (&rs->buf, 0);
10305 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
10307 case PACKET_OK:
10308 /* We have a wait response. All is well. */
10309 return 0;
10310 case PACKET_UNKNOWN:
10311 return -1;
10312 case PACKET_ERROR:
10313 if (remote_exec_file[0] == '\0')
10314 error (_("Running the default executable on the remote target failed; "
10315 "try \"set remote exec-file\"?"));
10316 else
10317 error (_("Running \"%s\" on the remote target failed"),
10318 remote_exec_file);
10319 default:
10320 gdb_assert_not_reached ("bad switch");
10324 /* Helper function to send set/unset environment packets. ACTION is
10325 either "set" or "unset". PACKET is either "QEnvironmentHexEncoded"
10326 or "QEnvironmentUnsetVariable". VALUE is the variable to be
10327 sent. */
10329 void
10330 remote_target::send_environment_packet (const char *action,
10331 const char *packet,
10332 const char *value)
10334 remote_state *rs = get_remote_state ();
10336 /* Convert the environment variable to an hex string, which
10337 is the best format to be transmitted over the wire. */
10338 std::string encoded_value = bin2hex ((const gdb_byte *) value,
10339 strlen (value));
10341 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10342 "%s:%s", packet, encoded_value.c_str ());
10344 putpkt (rs->buf);
10345 getpkt (&rs->buf, 0);
10346 if (strcmp (rs->buf.data (), "OK") != 0)
10347 warning (_("Unable to %s environment variable '%s' on remote."),
10348 action, value);
10351 /* Helper function to handle the QEnvironment* packets. */
10353 void
10354 remote_target::extended_remote_environment_support ()
10356 remote_state *rs = get_remote_state ();
10358 if (packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
10360 putpkt ("QEnvironmentReset");
10361 getpkt (&rs->buf, 0);
10362 if (strcmp (rs->buf.data (), "OK") != 0)
10363 warning (_("Unable to reset environment on remote."));
10366 gdb_environ *e = &current_inferior ()->environment;
10368 if (packet_support (PACKET_QEnvironmentHexEncoded) != PACKET_DISABLE)
10369 for (const std::string &el : e->user_set_env ())
10370 send_environment_packet ("set", "QEnvironmentHexEncoded",
10371 el.c_str ());
10373 if (packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
10374 for (const std::string &el : e->user_unset_env ())
10375 send_environment_packet ("unset", "QEnvironmentUnset", el.c_str ());
10378 /* Helper function to set the current working directory for the
10379 inferior in the remote target. */
10381 void
10382 remote_target::extended_remote_set_inferior_cwd ()
10384 if (packet_support (PACKET_QSetWorkingDir) != PACKET_DISABLE)
10386 const std::string &inferior_cwd = current_inferior ()->cwd ();
10387 remote_state *rs = get_remote_state ();
10389 if (!inferior_cwd.empty ())
10391 std::string hexpath
10392 = bin2hex ((const gdb_byte *) inferior_cwd.data (),
10393 inferior_cwd.size ());
10395 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10396 "QSetWorkingDir:%s", hexpath.c_str ());
10398 else
10400 /* An empty inferior_cwd means that the user wants us to
10401 reset the remote server's inferior's cwd. */
10402 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10403 "QSetWorkingDir:");
10406 putpkt (rs->buf);
10407 getpkt (&rs->buf, 0);
10408 if (packet_ok (rs->buf,
10409 &remote_protocol_packets[PACKET_QSetWorkingDir])
10410 != PACKET_OK)
10411 error (_("\
10412 Remote replied unexpectedly while setting the inferior's working\n\
10413 directory: %s"),
10414 rs->buf.data ());
10419 /* In the extended protocol we want to be able to do things like
10420 "run" and have them basically work as expected. So we need
10421 a special create_inferior function. We support changing the
10422 executable file and the command line arguments, but not the
10423 environment. */
10425 void
10426 extended_remote_target::create_inferior (const char *exec_file,
10427 const std::string &args,
10428 char **env, int from_tty)
10430 int run_worked;
10431 char *stop_reply;
10432 struct remote_state *rs = get_remote_state ();
10433 const char *remote_exec_file = get_remote_exec_file ();
10435 /* If running asynchronously, register the target file descriptor
10436 with the event loop. */
10437 if (target_can_async_p ())
10438 target_async (1);
10440 /* Disable address space randomization if requested (and supported). */
10441 if (supports_disable_randomization ())
10442 extended_remote_disable_randomization (disable_randomization);
10444 /* If startup-with-shell is on, we inform gdbserver to start the
10445 remote inferior using a shell. */
10446 if (packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
10448 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10449 "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
10450 putpkt (rs->buf);
10451 getpkt (&rs->buf, 0);
10452 if (strcmp (rs->buf.data (), "OK") != 0)
10453 error (_("\
10454 Remote replied unexpectedly while setting startup-with-shell: %s"),
10455 rs->buf.data ());
10458 extended_remote_environment_support ();
10460 extended_remote_set_inferior_cwd ();
10462 /* Now restart the remote server. */
10463 run_worked = extended_remote_run (args) != -1;
10464 if (!run_worked)
10466 /* vRun was not supported. Fail if we need it to do what the
10467 user requested. */
10468 if (remote_exec_file[0])
10469 error (_("Remote target does not support \"set remote exec-file\""));
10470 if (!args.empty ())
10471 error (_("Remote target does not support \"set args\" or run ARGS"));
10473 /* Fall back to "R". */
10474 extended_remote_restart ();
10477 /* vRun's success return is a stop reply. */
10478 stop_reply = run_worked ? rs->buf.data () : NULL;
10479 add_current_inferior_and_thread (stop_reply);
10481 /* Get updated offsets, if the stub uses qOffsets. */
10482 get_offsets ();
10486 /* Given a location's target info BP_TGT and the packet buffer BUF, output
10487 the list of conditions (in agent expression bytecode format), if any, the
10488 target needs to evaluate. The output is placed into the packet buffer
10489 started from BUF and ended at BUF_END. */
10491 static int
10492 remote_add_target_side_condition (struct gdbarch *gdbarch,
10493 struct bp_target_info *bp_tgt, char *buf,
10494 char *buf_end)
10496 if (bp_tgt->conditions.empty ())
10497 return 0;
10499 buf += strlen (buf);
10500 xsnprintf (buf, buf_end - buf, "%s", ";");
10501 buf++;
10503 /* Send conditions to the target. */
10504 for (agent_expr *aexpr : bp_tgt->conditions)
10506 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
10507 buf += strlen (buf);
10508 for (int i = 0; i < aexpr->len; ++i)
10509 buf = pack_hex_byte (buf, aexpr->buf[i]);
10510 *buf = '\0';
10512 return 0;
10515 static void
10516 remote_add_target_side_commands (struct gdbarch *gdbarch,
10517 struct bp_target_info *bp_tgt, char *buf)
10519 if (bp_tgt->tcommands.empty ())
10520 return;
10522 buf += strlen (buf);
10524 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
10525 buf += strlen (buf);
10527 /* Concatenate all the agent expressions that are commands into the
10528 cmds parameter. */
10529 for (agent_expr *aexpr : bp_tgt->tcommands)
10531 sprintf (buf, "X%x,", aexpr->len);
10532 buf += strlen (buf);
10533 for (int i = 0; i < aexpr->len; ++i)
10534 buf = pack_hex_byte (buf, aexpr->buf[i]);
10535 *buf = '\0';
10539 /* Insert a breakpoint. On targets that have software breakpoint
10540 support, we ask the remote target to do the work; on targets
10541 which don't, we insert a traditional memory breakpoint. */
10544 remote_target::insert_breakpoint (struct gdbarch *gdbarch,
10545 struct bp_target_info *bp_tgt)
10547 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
10548 If it succeeds, then set the support to PACKET_ENABLE. If it
10549 fails, and the user has explicitly requested the Z support then
10550 report an error, otherwise, mark it disabled and go on. */
10552 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
10554 CORE_ADDR addr = bp_tgt->reqstd_address;
10555 struct remote_state *rs;
10556 char *p, *endbuf;
10558 /* Make sure the remote is pointing at the right process, if
10559 necessary. */
10560 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10561 set_general_process ();
10563 rs = get_remote_state ();
10564 p = rs->buf.data ();
10565 endbuf = p + get_remote_packet_size ();
10567 *(p++) = 'Z';
10568 *(p++) = '0';
10569 *(p++) = ',';
10570 addr = (ULONGEST) remote_address_masked (addr);
10571 p += hexnumstr (p, addr);
10572 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10574 if (supports_evaluation_of_breakpoint_conditions ())
10575 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10577 if (can_run_breakpoint_commands ())
10578 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10580 putpkt (rs->buf);
10581 getpkt (&rs->buf, 0);
10583 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
10585 case PACKET_ERROR:
10586 return -1;
10587 case PACKET_OK:
10588 return 0;
10589 case PACKET_UNKNOWN:
10590 break;
10594 /* If this breakpoint has target-side commands but this stub doesn't
10595 support Z0 packets, throw error. */
10596 if (!bp_tgt->tcommands.empty ())
10597 throw_error (NOT_SUPPORTED_ERROR, _("\
10598 Target doesn't support breakpoints that have target side commands."));
10600 return memory_insert_breakpoint (this, gdbarch, bp_tgt);
10604 remote_target::remove_breakpoint (struct gdbarch *gdbarch,
10605 struct bp_target_info *bp_tgt,
10606 enum remove_bp_reason reason)
10608 CORE_ADDR addr = bp_tgt->placed_address;
10609 struct remote_state *rs = get_remote_state ();
10611 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
10613 char *p = rs->buf.data ();
10614 char *endbuf = p + get_remote_packet_size ();
10616 /* Make sure the remote is pointing at the right process, if
10617 necessary. */
10618 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10619 set_general_process ();
10621 *(p++) = 'z';
10622 *(p++) = '0';
10623 *(p++) = ',';
10625 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
10626 p += hexnumstr (p, addr);
10627 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10629 putpkt (rs->buf);
10630 getpkt (&rs->buf, 0);
10632 return (rs->buf[0] == 'E');
10635 return memory_remove_breakpoint (this, gdbarch, bp_tgt, reason);
10638 static enum Z_packet_type
10639 watchpoint_to_Z_packet (int type)
10641 switch (type)
10643 case hw_write:
10644 return Z_PACKET_WRITE_WP;
10645 break;
10646 case hw_read:
10647 return Z_PACKET_READ_WP;
10648 break;
10649 case hw_access:
10650 return Z_PACKET_ACCESS_WP;
10651 break;
10652 default:
10653 internal_error (__FILE__, __LINE__,
10654 _("hw_bp_to_z: bad watchpoint type %d"), type);
10659 remote_target::insert_watchpoint (CORE_ADDR addr, int len,
10660 enum target_hw_bp_type type, struct expression *cond)
10662 struct remote_state *rs = get_remote_state ();
10663 char *endbuf = rs->buf.data () + get_remote_packet_size ();
10664 char *p;
10665 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10667 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
10668 return 1;
10670 /* Make sure the remote is pointing at the right process, if
10671 necessary. */
10672 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10673 set_general_process ();
10675 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "Z%x,", packet);
10676 p = strchr (rs->buf.data (), '\0');
10677 addr = remote_address_masked (addr);
10678 p += hexnumstr (p, (ULONGEST) addr);
10679 xsnprintf (p, endbuf - p, ",%x", len);
10681 putpkt (rs->buf);
10682 getpkt (&rs->buf, 0);
10684 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
10686 case PACKET_ERROR:
10687 return -1;
10688 case PACKET_UNKNOWN:
10689 return 1;
10690 case PACKET_OK:
10691 return 0;
10693 internal_error (__FILE__, __LINE__,
10694 _("remote_insert_watchpoint: reached end of function"));
10697 bool
10698 remote_target::watchpoint_addr_within_range (CORE_ADDR addr,
10699 CORE_ADDR start, int length)
10701 CORE_ADDR diff = remote_address_masked (addr - start);
10703 return diff < length;
10708 remote_target::remove_watchpoint (CORE_ADDR addr, int len,
10709 enum target_hw_bp_type type, struct expression *cond)
10711 struct remote_state *rs = get_remote_state ();
10712 char *endbuf = rs->buf.data () + get_remote_packet_size ();
10713 char *p;
10714 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10716 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
10717 return -1;
10719 /* Make sure the remote is pointing at the right process, if
10720 necessary. */
10721 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10722 set_general_process ();
10724 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "z%x,", packet);
10725 p = strchr (rs->buf.data (), '\0');
10726 addr = remote_address_masked (addr);
10727 p += hexnumstr (p, (ULONGEST) addr);
10728 xsnprintf (p, endbuf - p, ",%x", len);
10729 putpkt (rs->buf);
10730 getpkt (&rs->buf, 0);
10732 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
10734 case PACKET_ERROR:
10735 case PACKET_UNKNOWN:
10736 return -1;
10737 case PACKET_OK:
10738 return 0;
10740 internal_error (__FILE__, __LINE__,
10741 _("remote_remove_watchpoint: reached end of function"));
10745 static int remote_hw_watchpoint_limit = -1;
10746 static int remote_hw_watchpoint_length_limit = -1;
10747 static int remote_hw_breakpoint_limit = -1;
10750 remote_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
10752 if (remote_hw_watchpoint_length_limit == 0)
10753 return 0;
10754 else if (remote_hw_watchpoint_length_limit < 0)
10755 return 1;
10756 else if (len <= remote_hw_watchpoint_length_limit)
10757 return 1;
10758 else
10759 return 0;
10763 remote_target::can_use_hw_breakpoint (enum bptype type, int cnt, int ot)
10765 if (type == bp_hardware_breakpoint)
10767 if (remote_hw_breakpoint_limit == 0)
10768 return 0;
10769 else if (remote_hw_breakpoint_limit < 0)
10770 return 1;
10771 else if (cnt <= remote_hw_breakpoint_limit)
10772 return 1;
10774 else
10776 if (remote_hw_watchpoint_limit == 0)
10777 return 0;
10778 else if (remote_hw_watchpoint_limit < 0)
10779 return 1;
10780 else if (ot)
10781 return -1;
10782 else if (cnt <= remote_hw_watchpoint_limit)
10783 return 1;
10785 return -1;
10788 /* The to_stopped_by_sw_breakpoint method of target remote. */
10790 bool
10791 remote_target::stopped_by_sw_breakpoint ()
10793 struct thread_info *thread = inferior_thread ();
10795 return (thread->priv != NULL
10796 && (get_remote_thread_info (thread)->stop_reason
10797 == TARGET_STOPPED_BY_SW_BREAKPOINT));
10800 /* The to_supports_stopped_by_sw_breakpoint method of target
10801 remote. */
10803 bool
10804 remote_target::supports_stopped_by_sw_breakpoint ()
10806 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
10809 /* The to_stopped_by_hw_breakpoint method of target remote. */
10811 bool
10812 remote_target::stopped_by_hw_breakpoint ()
10814 struct thread_info *thread = inferior_thread ();
10816 return (thread->priv != NULL
10817 && (get_remote_thread_info (thread)->stop_reason
10818 == TARGET_STOPPED_BY_HW_BREAKPOINT));
10821 /* The to_supports_stopped_by_hw_breakpoint method of target
10822 remote. */
10824 bool
10825 remote_target::supports_stopped_by_hw_breakpoint ()
10827 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
10830 bool
10831 remote_target::stopped_by_watchpoint ()
10833 struct thread_info *thread = inferior_thread ();
10835 return (thread->priv != NULL
10836 && (get_remote_thread_info (thread)->stop_reason
10837 == TARGET_STOPPED_BY_WATCHPOINT));
10840 bool
10841 remote_target::stopped_data_address (CORE_ADDR *addr_p)
10843 struct thread_info *thread = inferior_thread ();
10845 if (thread->priv != NULL
10846 && (get_remote_thread_info (thread)->stop_reason
10847 == TARGET_STOPPED_BY_WATCHPOINT))
10849 *addr_p = get_remote_thread_info (thread)->watch_data_address;
10850 return true;
10853 return false;
10858 remote_target::insert_hw_breakpoint (struct gdbarch *gdbarch,
10859 struct bp_target_info *bp_tgt)
10861 CORE_ADDR addr = bp_tgt->reqstd_address;
10862 struct remote_state *rs;
10863 char *p, *endbuf;
10864 char *message;
10866 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10867 return -1;
10869 /* Make sure the remote is pointing at the right process, if
10870 necessary. */
10871 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10872 set_general_process ();
10874 rs = get_remote_state ();
10875 p = rs->buf.data ();
10876 endbuf = p + get_remote_packet_size ();
10878 *(p++) = 'Z';
10879 *(p++) = '1';
10880 *(p++) = ',';
10882 addr = remote_address_masked (addr);
10883 p += hexnumstr (p, (ULONGEST) addr);
10884 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
10886 if (supports_evaluation_of_breakpoint_conditions ())
10887 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10889 if (can_run_breakpoint_commands ())
10890 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10892 putpkt (rs->buf);
10893 getpkt (&rs->buf, 0);
10895 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10897 case PACKET_ERROR:
10898 if (rs->buf[1] == '.')
10900 message = strchr (&rs->buf[2], '.');
10901 if (message)
10902 error (_("Remote failure reply: %s"), message + 1);
10904 return -1;
10905 case PACKET_UNKNOWN:
10906 return -1;
10907 case PACKET_OK:
10908 return 0;
10910 internal_error (__FILE__, __LINE__,
10911 _("remote_insert_hw_breakpoint: reached end of function"));
10916 remote_target::remove_hw_breakpoint (struct gdbarch *gdbarch,
10917 struct bp_target_info *bp_tgt)
10919 CORE_ADDR addr;
10920 struct remote_state *rs = get_remote_state ();
10921 char *p = rs->buf.data ();
10922 char *endbuf = p + get_remote_packet_size ();
10924 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10925 return -1;
10927 /* Make sure the remote is pointing at the right process, if
10928 necessary. */
10929 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10930 set_general_process ();
10932 *(p++) = 'z';
10933 *(p++) = '1';
10934 *(p++) = ',';
10936 addr = remote_address_masked (bp_tgt->placed_address);
10937 p += hexnumstr (p, (ULONGEST) addr);
10938 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
10940 putpkt (rs->buf);
10941 getpkt (&rs->buf, 0);
10943 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10945 case PACKET_ERROR:
10946 case PACKET_UNKNOWN:
10947 return -1;
10948 case PACKET_OK:
10949 return 0;
10951 internal_error (__FILE__, __LINE__,
10952 _("remote_remove_hw_breakpoint: reached end of function"));
10955 /* Verify memory using the "qCRC:" request. */
10958 remote_target::verify_memory (const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
10960 struct remote_state *rs = get_remote_state ();
10961 unsigned long host_crc, target_crc;
10962 char *tmp;
10964 /* It doesn't make sense to use qCRC if the remote target is
10965 connected but not running. */
10966 if (target_has_execution ()
10967 && packet_support (PACKET_qCRC) != PACKET_DISABLE)
10969 enum packet_result result;
10971 /* Make sure the remote is pointing at the right process. */
10972 set_general_process ();
10974 /* FIXME: assumes lma can fit into long. */
10975 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qCRC:%lx,%lx",
10976 (long) lma, (long) size);
10977 putpkt (rs->buf);
10979 /* Be clever; compute the host_crc before waiting for target
10980 reply. */
10981 host_crc = xcrc32 (data, size, 0xffffffff);
10983 getpkt (&rs->buf, 0);
10985 result = packet_ok (rs->buf,
10986 &remote_protocol_packets[PACKET_qCRC]);
10987 if (result == PACKET_ERROR)
10988 return -1;
10989 else if (result == PACKET_OK)
10991 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
10992 target_crc = target_crc * 16 + fromhex (*tmp);
10994 return (host_crc == target_crc);
10998 return simple_verify_memory (this, data, lma, size);
11001 /* compare-sections command
11003 With no arguments, compares each loadable section in the exec bfd
11004 with the same memory range on the target, and reports mismatches.
11005 Useful for verifying the image on the target against the exec file. */
11007 static void
11008 compare_sections_command (const char *args, int from_tty)
11010 asection *s;
11011 const char *sectname;
11012 bfd_size_type size;
11013 bfd_vma lma;
11014 int matched = 0;
11015 int mismatched = 0;
11016 int res;
11017 int read_only = 0;
11019 if (!current_program_space->exec_bfd ())
11020 error (_("command cannot be used without an exec file"));
11022 if (args != NULL && strcmp (args, "-r") == 0)
11024 read_only = 1;
11025 args = NULL;
11028 for (s = current_program_space->exec_bfd ()->sections; s; s = s->next)
11030 if (!(s->flags & SEC_LOAD))
11031 continue; /* Skip non-loadable section. */
11033 if (read_only && (s->flags & SEC_READONLY) == 0)
11034 continue; /* Skip writeable sections */
11036 size = bfd_section_size (s);
11037 if (size == 0)
11038 continue; /* Skip zero-length section. */
11040 sectname = bfd_section_name (s);
11041 if (args && strcmp (args, sectname) != 0)
11042 continue; /* Not the section selected by user. */
11044 matched = 1; /* Do this section. */
11045 lma = s->lma;
11047 gdb::byte_vector sectdata (size);
11048 bfd_get_section_contents (current_program_space->exec_bfd (), s,
11049 sectdata.data (), 0, size);
11051 res = target_verify_memory (sectdata.data (), lma, size);
11053 if (res == -1)
11054 error (_("target memory fault, section %s, range %s -- %s"), sectname,
11055 paddress (target_gdbarch (), lma),
11056 paddress (target_gdbarch (), lma + size));
11058 gdb_printf ("Section %s, range %s -- %s: ", sectname,
11059 paddress (target_gdbarch (), lma),
11060 paddress (target_gdbarch (), lma + size));
11061 if (res)
11062 gdb_printf ("matched.\n");
11063 else
11065 gdb_printf ("MIS-MATCHED!\n");
11066 mismatched++;
11069 if (mismatched > 0)
11070 warning (_("One or more sections of the target image does not match\n\
11071 the loaded file\n"));
11072 if (args && !matched)
11073 gdb_printf (_("No loaded section named '%s'.\n"), args);
11076 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
11077 into remote target. The number of bytes written to the remote
11078 target is returned, or -1 for error. */
11080 target_xfer_status
11081 remote_target::remote_write_qxfer (const char *object_name,
11082 const char *annex, const gdb_byte *writebuf,
11083 ULONGEST offset, LONGEST len,
11084 ULONGEST *xfered_len,
11085 struct packet_config *packet)
11087 int i, buf_len;
11088 ULONGEST n;
11089 struct remote_state *rs = get_remote_state ();
11090 int max_size = get_memory_write_packet_size ();
11092 if (packet_config_support (packet) == PACKET_DISABLE)
11093 return TARGET_XFER_E_IO;
11095 /* Insert header. */
11096 i = snprintf (rs->buf.data (), max_size,
11097 "qXfer:%s:write:%s:%s:",
11098 object_name, annex ? annex : "",
11099 phex_nz (offset, sizeof offset));
11100 max_size -= (i + 1);
11102 /* Escape as much data as fits into rs->buf. */
11103 buf_len = remote_escape_output
11104 (writebuf, len, 1, (gdb_byte *) rs->buf.data () + i, &max_size, max_size);
11106 if (putpkt_binary (rs->buf.data (), i + buf_len) < 0
11107 || getpkt_sane (&rs->buf, 0) < 0
11108 || packet_ok (rs->buf, packet) != PACKET_OK)
11109 return TARGET_XFER_E_IO;
11111 unpack_varlen_hex (rs->buf.data (), &n);
11113 *xfered_len = n;
11114 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
11117 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
11118 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
11119 number of bytes read is returned, or 0 for EOF, or -1 for error.
11120 The number of bytes read may be less than LEN without indicating an
11121 EOF. PACKET is checked and updated to indicate whether the remote
11122 target supports this object. */
11124 target_xfer_status
11125 remote_target::remote_read_qxfer (const char *object_name,
11126 const char *annex,
11127 gdb_byte *readbuf, ULONGEST offset,
11128 LONGEST len,
11129 ULONGEST *xfered_len,
11130 struct packet_config *packet)
11132 struct remote_state *rs = get_remote_state ();
11133 LONGEST i, n, packet_len;
11135 if (packet_config_support (packet) == PACKET_DISABLE)
11136 return TARGET_XFER_E_IO;
11138 /* Check whether we've cached an end-of-object packet that matches
11139 this request. */
11140 if (rs->finished_object)
11142 if (strcmp (object_name, rs->finished_object) == 0
11143 && strcmp (annex ? annex : "", rs->finished_annex) == 0
11144 && offset == rs->finished_offset)
11145 return TARGET_XFER_EOF;
11148 /* Otherwise, we're now reading something different. Discard
11149 the cache. */
11150 xfree (rs->finished_object);
11151 xfree (rs->finished_annex);
11152 rs->finished_object = NULL;
11153 rs->finished_annex = NULL;
11156 /* Request only enough to fit in a single packet. The actual data
11157 may not, since we don't know how much of it will need to be escaped;
11158 the target is free to respond with slightly less data. We subtract
11159 five to account for the response type and the protocol frame. */
11160 n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
11161 snprintf (rs->buf.data (), get_remote_packet_size () - 4,
11162 "qXfer:%s:read:%s:%s,%s",
11163 object_name, annex ? annex : "",
11164 phex_nz (offset, sizeof offset),
11165 phex_nz (n, sizeof n));
11166 i = putpkt (rs->buf);
11167 if (i < 0)
11168 return TARGET_XFER_E_IO;
11170 rs->buf[0] = '\0';
11171 packet_len = getpkt_sane (&rs->buf, 0);
11172 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
11173 return TARGET_XFER_E_IO;
11175 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
11176 error (_("Unknown remote qXfer reply: %s"), rs->buf.data ());
11178 /* 'm' means there is (or at least might be) more data after this
11179 batch. That does not make sense unless there's at least one byte
11180 of data in this reply. */
11181 if (rs->buf[0] == 'm' && packet_len == 1)
11182 error (_("Remote qXfer reply contained no data."));
11184 /* Got some data. */
11185 i = remote_unescape_input ((gdb_byte *) rs->buf.data () + 1,
11186 packet_len - 1, readbuf, n);
11188 /* 'l' is an EOF marker, possibly including a final block of data,
11189 or possibly empty. If we have the final block of a non-empty
11190 object, record this fact to bypass a subsequent partial read. */
11191 if (rs->buf[0] == 'l' && offset + i > 0)
11193 rs->finished_object = xstrdup (object_name);
11194 rs->finished_annex = xstrdup (annex ? annex : "");
11195 rs->finished_offset = offset + i;
11198 if (i == 0)
11199 return TARGET_XFER_EOF;
11200 else
11202 *xfered_len = i;
11203 return TARGET_XFER_OK;
11207 enum target_xfer_status
11208 remote_target::xfer_partial (enum target_object object,
11209 const char *annex, gdb_byte *readbuf,
11210 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
11211 ULONGEST *xfered_len)
11213 struct remote_state *rs;
11214 int i;
11215 char *p2;
11216 char query_type;
11217 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
11219 set_remote_traceframe ();
11220 set_general_thread (inferior_ptid);
11222 rs = get_remote_state ();
11224 /* Handle memory using the standard memory routines. */
11225 if (object == TARGET_OBJECT_MEMORY)
11227 /* If the remote target is connected but not running, we should
11228 pass this request down to a lower stratum (e.g. the executable
11229 file). */
11230 if (!target_has_execution ())
11231 return TARGET_XFER_EOF;
11233 if (writebuf != NULL)
11234 return remote_write_bytes (offset, writebuf, len, unit_size,
11235 xfered_len);
11236 else
11237 return remote_read_bytes (offset, readbuf, len, unit_size,
11238 xfered_len);
11241 /* Handle extra signal info using qxfer packets. */
11242 if (object == TARGET_OBJECT_SIGNAL_INFO)
11244 if (readbuf)
11245 return remote_read_qxfer ("siginfo", annex, readbuf, offset, len,
11246 xfered_len, &remote_protocol_packets
11247 [PACKET_qXfer_siginfo_read]);
11248 else
11249 return remote_write_qxfer ("siginfo", annex,
11250 writebuf, offset, len, xfered_len,
11251 &remote_protocol_packets
11252 [PACKET_qXfer_siginfo_write]);
11255 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
11257 if (readbuf)
11258 return remote_read_qxfer ("statictrace", annex,
11259 readbuf, offset, len, xfered_len,
11260 &remote_protocol_packets
11261 [PACKET_qXfer_statictrace_read]);
11262 else
11263 return TARGET_XFER_E_IO;
11266 /* Only handle flash writes. */
11267 if (writebuf != NULL)
11269 switch (object)
11271 case TARGET_OBJECT_FLASH:
11272 return remote_flash_write (offset, len, xfered_len,
11273 writebuf);
11275 default:
11276 return TARGET_XFER_E_IO;
11280 /* Map pre-existing objects onto letters. DO NOT do this for new
11281 objects!!! Instead specify new query packets. */
11282 switch (object)
11284 case TARGET_OBJECT_AVR:
11285 query_type = 'R';
11286 break;
11288 case TARGET_OBJECT_AUXV:
11289 gdb_assert (annex == NULL);
11290 return remote_read_qxfer ("auxv", annex, readbuf, offset, len,
11291 xfered_len,
11292 &remote_protocol_packets[PACKET_qXfer_auxv]);
11294 case TARGET_OBJECT_AVAILABLE_FEATURES:
11295 return remote_read_qxfer
11296 ("features", annex, readbuf, offset, len, xfered_len,
11297 &remote_protocol_packets[PACKET_qXfer_features]);
11299 case TARGET_OBJECT_LIBRARIES:
11300 return remote_read_qxfer
11301 ("libraries", annex, readbuf, offset, len, xfered_len,
11302 &remote_protocol_packets[PACKET_qXfer_libraries]);
11304 case TARGET_OBJECT_LIBRARIES_SVR4:
11305 return remote_read_qxfer
11306 ("libraries-svr4", annex, readbuf, offset, len, xfered_len,
11307 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
11309 case TARGET_OBJECT_MEMORY_MAP:
11310 gdb_assert (annex == NULL);
11311 return remote_read_qxfer ("memory-map", annex, readbuf, offset, len,
11312 xfered_len,
11313 &remote_protocol_packets[PACKET_qXfer_memory_map]);
11315 case TARGET_OBJECT_OSDATA:
11316 /* Should only get here if we're connected. */
11317 gdb_assert (rs->remote_desc);
11318 return remote_read_qxfer
11319 ("osdata", annex, readbuf, offset, len, xfered_len,
11320 &remote_protocol_packets[PACKET_qXfer_osdata]);
11322 case TARGET_OBJECT_THREADS:
11323 gdb_assert (annex == NULL);
11324 return remote_read_qxfer ("threads", annex, readbuf, offset, len,
11325 xfered_len,
11326 &remote_protocol_packets[PACKET_qXfer_threads]);
11328 case TARGET_OBJECT_TRACEFRAME_INFO:
11329 gdb_assert (annex == NULL);
11330 return remote_read_qxfer
11331 ("traceframe-info", annex, readbuf, offset, len, xfered_len,
11332 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
11334 case TARGET_OBJECT_FDPIC:
11335 return remote_read_qxfer ("fdpic", annex, readbuf, offset, len,
11336 xfered_len,
11337 &remote_protocol_packets[PACKET_qXfer_fdpic]);
11339 case TARGET_OBJECT_OPENVMS_UIB:
11340 return remote_read_qxfer ("uib", annex, readbuf, offset, len,
11341 xfered_len,
11342 &remote_protocol_packets[PACKET_qXfer_uib]);
11344 case TARGET_OBJECT_BTRACE:
11345 return remote_read_qxfer ("btrace", annex, readbuf, offset, len,
11346 xfered_len,
11347 &remote_protocol_packets[PACKET_qXfer_btrace]);
11349 case TARGET_OBJECT_BTRACE_CONF:
11350 return remote_read_qxfer ("btrace-conf", annex, readbuf, offset,
11351 len, xfered_len,
11352 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
11354 case TARGET_OBJECT_EXEC_FILE:
11355 return remote_read_qxfer ("exec-file", annex, readbuf, offset,
11356 len, xfered_len,
11357 &remote_protocol_packets[PACKET_qXfer_exec_file]);
11359 default:
11360 return TARGET_XFER_E_IO;
11363 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
11364 large enough let the caller deal with it. */
11365 if (len < get_remote_packet_size ())
11366 return TARGET_XFER_E_IO;
11367 len = get_remote_packet_size ();
11369 /* Except for querying the minimum buffer size, target must be open. */
11370 if (!rs->remote_desc)
11371 error (_("remote query is only available after target open"));
11373 gdb_assert (annex != NULL);
11374 gdb_assert (readbuf != NULL);
11376 p2 = rs->buf.data ();
11377 *p2++ = 'q';
11378 *p2++ = query_type;
11380 /* We used one buffer char for the remote protocol q command and
11381 another for the query type. As the remote protocol encapsulation
11382 uses 4 chars plus one extra in case we are debugging
11383 (remote_debug), we have PBUFZIZ - 7 left to pack the query
11384 string. */
11385 i = 0;
11386 while (annex[i] && (i < (get_remote_packet_size () - 8)))
11388 /* Bad caller may have sent forbidden characters. */
11389 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
11390 *p2++ = annex[i];
11391 i++;
11393 *p2 = '\0';
11394 gdb_assert (annex[i] == '\0');
11396 i = putpkt (rs->buf);
11397 if (i < 0)
11398 return TARGET_XFER_E_IO;
11400 getpkt (&rs->buf, 0);
11401 strcpy ((char *) readbuf, rs->buf.data ());
11403 *xfered_len = strlen ((char *) readbuf);
11404 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
11407 /* Implementation of to_get_memory_xfer_limit. */
11409 ULONGEST
11410 remote_target::get_memory_xfer_limit ()
11412 return get_memory_write_packet_size ();
11416 remote_target::search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
11417 const gdb_byte *pattern, ULONGEST pattern_len,
11418 CORE_ADDR *found_addrp)
11420 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
11421 struct remote_state *rs = get_remote_state ();
11422 int max_size = get_memory_write_packet_size ();
11423 struct packet_config *packet =
11424 &remote_protocol_packets[PACKET_qSearch_memory];
11425 /* Number of packet bytes used to encode the pattern;
11426 this could be more than PATTERN_LEN due to escape characters. */
11427 int escaped_pattern_len;
11428 /* Amount of pattern that was encodable in the packet. */
11429 int used_pattern_len;
11430 int i;
11431 int found;
11432 ULONGEST found_addr;
11434 auto read_memory = [=] (CORE_ADDR addr, gdb_byte *result, size_t len)
11436 return (target_read (this, TARGET_OBJECT_MEMORY, NULL, result, addr, len)
11437 == len);
11440 /* Don't go to the target if we don't have to. This is done before
11441 checking packet_config_support to avoid the possibility that a
11442 success for this edge case means the facility works in
11443 general. */
11444 if (pattern_len > search_space_len)
11445 return 0;
11446 if (pattern_len == 0)
11448 *found_addrp = start_addr;
11449 return 1;
11452 /* If we already know the packet isn't supported, fall back to the simple
11453 way of searching memory. */
11455 if (packet_config_support (packet) == PACKET_DISABLE)
11457 /* Target doesn't provided special support, fall back and use the
11458 standard support (copy memory and do the search here). */
11459 return simple_search_memory (read_memory, start_addr, search_space_len,
11460 pattern, pattern_len, found_addrp);
11463 /* Make sure the remote is pointing at the right process. */
11464 set_general_process ();
11466 /* Insert header. */
11467 i = snprintf (rs->buf.data (), max_size,
11468 "qSearch:memory:%s;%s;",
11469 phex_nz (start_addr, addr_size),
11470 phex_nz (search_space_len, sizeof (search_space_len)));
11471 max_size -= (i + 1);
11473 /* Escape as much data as fits into rs->buf. */
11474 escaped_pattern_len =
11475 remote_escape_output (pattern, pattern_len, 1,
11476 (gdb_byte *) rs->buf.data () + i,
11477 &used_pattern_len, max_size);
11479 /* Bail if the pattern is too large. */
11480 if (used_pattern_len != pattern_len)
11481 error (_("Pattern is too large to transmit to remote target."));
11483 if (putpkt_binary (rs->buf.data (), i + escaped_pattern_len) < 0
11484 || getpkt_sane (&rs->buf, 0) < 0
11485 || packet_ok (rs->buf, packet) != PACKET_OK)
11487 /* The request may not have worked because the command is not
11488 supported. If so, fall back to the simple way. */
11489 if (packet_config_support (packet) == PACKET_DISABLE)
11491 return simple_search_memory (read_memory, start_addr, search_space_len,
11492 pattern, pattern_len, found_addrp);
11494 return -1;
11497 if (rs->buf[0] == '0')
11498 found = 0;
11499 else if (rs->buf[0] == '1')
11501 found = 1;
11502 if (rs->buf[1] != ',')
11503 error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
11504 unpack_varlen_hex (&rs->buf[2], &found_addr);
11505 *found_addrp = found_addr;
11507 else
11508 error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
11510 return found;
11513 void
11514 remote_target::rcmd (const char *command, struct ui_file *outbuf)
11516 struct remote_state *rs = get_remote_state ();
11517 char *p = rs->buf.data ();
11519 if (!rs->remote_desc)
11520 error (_("remote rcmd is only available after target open"));
11522 /* Send a NULL command across as an empty command. */
11523 if (command == NULL)
11524 command = "";
11526 /* The query prefix. */
11527 strcpy (rs->buf.data (), "qRcmd,");
11528 p = strchr (rs->buf.data (), '\0');
11530 if ((strlen (rs->buf.data ()) + strlen (command) * 2 + 8/*misc*/)
11531 > get_remote_packet_size ())
11532 error (_("\"monitor\" command ``%s'' is too long."), command);
11534 /* Encode the actual command. */
11535 bin2hex ((const gdb_byte *) command, p, strlen (command));
11537 if (putpkt (rs->buf) < 0)
11538 error (_("Communication problem with target."));
11540 /* get/display the response */
11541 while (1)
11543 char *buf;
11545 /* XXX - see also remote_get_noisy_reply(). */
11546 QUIT; /* Allow user to bail out with ^C. */
11547 rs->buf[0] = '\0';
11548 if (getpkt_sane (&rs->buf, 0) == -1)
11550 /* Timeout. Continue to (try to) read responses.
11551 This is better than stopping with an error, assuming the stub
11552 is still executing the (long) monitor command.
11553 If needed, the user can interrupt gdb using C-c, obtaining
11554 an effect similar to stop on timeout. */
11555 continue;
11557 buf = rs->buf.data ();
11558 if (buf[0] == '\0')
11559 error (_("Target does not support this command."));
11560 if (buf[0] == 'O' && buf[1] != 'K')
11562 remote_console_output (buf + 1); /* 'O' message from stub. */
11563 continue;
11565 if (strcmp (buf, "OK") == 0)
11566 break;
11567 if (strlen (buf) == 3 && buf[0] == 'E'
11568 && isxdigit (buf[1]) && isxdigit (buf[2]))
11570 error (_("Protocol error with Rcmd"));
11572 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
11574 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
11576 gdb_putc (c, outbuf);
11578 break;
11582 std::vector<mem_region>
11583 remote_target::memory_map ()
11585 std::vector<mem_region> result;
11586 gdb::optional<gdb::char_vector> text
11587 = target_read_stralloc (current_inferior ()->top_target (),
11588 TARGET_OBJECT_MEMORY_MAP, NULL);
11590 if (text)
11591 result = parse_memory_map (text->data ());
11593 return result;
11596 /* Set of callbacks used to implement the 'maint packet' command. */
11598 struct cli_packet_command_callbacks : public send_remote_packet_callbacks
11600 /* Called before the packet is sent. BUF is the packet content before
11601 the protocol specific prefix, suffix, and escaping is added. */
11603 void sending (gdb::array_view<const char> &buf) override
11605 gdb_puts ("sending: ");
11606 print_packet (buf);
11607 gdb_puts ("\n");
11610 /* Called with BUF, the reply from the remote target. */
11612 void received (gdb::array_view<const char> &buf) override
11614 gdb_puts ("received: \"");
11615 print_packet (buf);
11616 gdb_puts ("\"\n");
11619 private:
11621 /* Print BUF o gdb_stdout. Any non-printable bytes in BUF are printed as
11622 '\x??' with '??' replaced by the hexadecimal value of the byte. */
11624 static void
11625 print_packet (gdb::array_view<const char> &buf)
11627 string_file stb;
11629 for (int i = 0; i < buf.size (); ++i)
11631 gdb_byte c = buf[i];
11632 if (isprint (c))
11633 gdb_putc (c, &stb);
11634 else
11635 gdb_printf (&stb, "\\x%02x", (unsigned char) c);
11638 gdb_puts (stb.string ().c_str ());
11642 /* See remote.h. */
11644 void
11645 send_remote_packet (gdb::array_view<const char> &buf,
11646 send_remote_packet_callbacks *callbacks)
11648 if (buf.size () == 0 || buf.data ()[0] == '\0')
11649 error (_("a remote packet must not be empty"));
11651 remote_target *remote = get_current_remote_target ();
11652 if (remote == nullptr)
11653 error (_("packets can only be sent to a remote target"));
11655 callbacks->sending (buf);
11657 remote->putpkt_binary (buf.data (), buf.size ());
11658 remote_state *rs = remote->get_remote_state ();
11659 int bytes = remote->getpkt_sane (&rs->buf, 0);
11661 if (bytes < 0)
11662 error (_("error while fetching packet from remote target"));
11664 gdb::array_view<const char> view (&rs->buf[0], bytes);
11665 callbacks->received (view);
11668 /* Entry point for the 'maint packet' command. */
11670 static void
11671 cli_packet_command (const char *args, int from_tty)
11673 cli_packet_command_callbacks cb;
11674 gdb::array_view<const char> view
11675 = gdb::make_array_view (args, args == nullptr ? 0 : strlen (args));
11676 send_remote_packet (view, &cb);
11679 #if 0
11680 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
11682 static void display_thread_info (struct gdb_ext_thread_info *info);
11684 static void threadset_test_cmd (char *cmd, int tty);
11686 static void threadalive_test (char *cmd, int tty);
11688 static void threadlist_test_cmd (char *cmd, int tty);
11690 int get_and_display_threadinfo (threadref *ref);
11692 static void threadinfo_test_cmd (char *cmd, int tty);
11694 static int thread_display_step (threadref *ref, void *context);
11696 static void threadlist_update_test_cmd (char *cmd, int tty);
11698 static void init_remote_threadtests (void);
11700 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
11702 static void
11703 threadset_test_cmd (const char *cmd, int tty)
11705 int sample_thread = SAMPLE_THREAD;
11707 gdb_printf (_("Remote threadset test\n"));
11708 set_general_thread (sample_thread);
11712 static void
11713 threadalive_test (const char *cmd, int tty)
11715 int sample_thread = SAMPLE_THREAD;
11716 int pid = inferior_ptid.pid ();
11717 ptid_t ptid = ptid_t (pid, sample_thread, 0);
11719 if (remote_thread_alive (ptid))
11720 gdb_printf ("PASS: Thread alive test\n");
11721 else
11722 gdb_printf ("FAIL: Thread alive test\n");
11725 void output_threadid (char *title, threadref *ref);
11727 void
11728 output_threadid (char *title, threadref *ref)
11730 char hexid[20];
11732 pack_threadid (&hexid[0], ref); /* Convert thread id into hex. */
11733 hexid[16] = 0;
11734 gdb_printf ("%s %s\n", title, (&hexid[0]));
11737 static void
11738 threadlist_test_cmd (const char *cmd, int tty)
11740 int startflag = 1;
11741 threadref nextthread;
11742 int done, result_count;
11743 threadref threadlist[3];
11745 gdb_printf ("Remote Threadlist test\n");
11746 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
11747 &result_count, &threadlist[0]))
11748 gdb_printf ("FAIL: threadlist test\n");
11749 else
11751 threadref *scan = threadlist;
11752 threadref *limit = scan + result_count;
11754 while (scan < limit)
11755 output_threadid (" thread ", scan++);
11759 void
11760 display_thread_info (struct gdb_ext_thread_info *info)
11762 output_threadid ("Threadid: ", &info->threadid);
11763 gdb_printf ("Name: %s\n ", info->shortname);
11764 gdb_printf ("State: %s\n", info->display);
11765 gdb_printf ("other: %s\n\n", info->more_display);
11769 get_and_display_threadinfo (threadref *ref)
11771 int result;
11772 int set;
11773 struct gdb_ext_thread_info threadinfo;
11775 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
11776 | TAG_MOREDISPLAY | TAG_DISPLAY;
11777 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
11778 display_thread_info (&threadinfo);
11779 return result;
11782 static void
11783 threadinfo_test_cmd (const char *cmd, int tty)
11785 int athread = SAMPLE_THREAD;
11786 threadref thread;
11787 int set;
11789 int_to_threadref (&thread, athread);
11790 gdb_printf ("Remote Threadinfo test\n");
11791 if (!get_and_display_threadinfo (&thread))
11792 gdb_printf ("FAIL cannot get thread info\n");
11795 static int
11796 thread_display_step (threadref *ref, void *context)
11798 /* output_threadid(" threadstep ",ref); *//* simple test */
11799 return get_and_display_threadinfo (ref);
11802 static void
11803 threadlist_update_test_cmd (const char *cmd, int tty)
11805 gdb_printf ("Remote Threadlist update test\n");
11806 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
11809 static void
11810 init_remote_threadtests (void)
11812 add_com ("tlist", class_obscure, threadlist_test_cmd,
11813 _("Fetch and print the remote list of "
11814 "thread identifiers, one pkt only."));
11815 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
11816 _("Fetch and display info about one thread."));
11817 add_com ("tset", class_obscure, threadset_test_cmd,
11818 _("Test setting to a different thread."));
11819 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
11820 _("Iterate through updating all remote thread info."));
11821 add_com ("talive", class_obscure, threadalive_test,
11822 _("Remote thread alive test."));
11825 #endif /* 0 */
11827 /* Convert a thread ID to a string. */
11829 std::string
11830 remote_target::pid_to_str (ptid_t ptid)
11832 struct remote_state *rs = get_remote_state ();
11834 if (ptid == null_ptid)
11835 return normal_pid_to_str (ptid);
11836 else if (ptid.is_pid ())
11838 /* Printing an inferior target id. */
11840 /* When multi-process extensions are off, there's no way in the
11841 remote protocol to know the remote process id, if there's any
11842 at all. There's one exception --- when we're connected with
11843 target extended-remote, and we manually attached to a process
11844 with "attach PID". We don't record anywhere a flag that
11845 allows us to distinguish that case from the case of
11846 connecting with extended-remote and the stub already being
11847 attached to a process, and reporting yes to qAttached, hence
11848 no smart special casing here. */
11849 if (!remote_multi_process_p (rs))
11850 return "Remote target";
11852 return normal_pid_to_str (ptid);
11854 else
11856 if (magic_null_ptid == ptid)
11857 return "Thread <main>";
11858 else if (remote_multi_process_p (rs))
11859 if (ptid.lwp () == 0)
11860 return normal_pid_to_str (ptid);
11861 else
11862 return string_printf ("Thread %d.%ld",
11863 ptid.pid (), ptid.lwp ());
11864 else
11865 return string_printf ("Thread %ld", ptid.lwp ());
11869 /* Get the address of the thread local variable in OBJFILE which is
11870 stored at OFFSET within the thread local storage for thread PTID. */
11872 CORE_ADDR
11873 remote_target::get_thread_local_address (ptid_t ptid, CORE_ADDR lm,
11874 CORE_ADDR offset)
11876 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
11878 struct remote_state *rs = get_remote_state ();
11879 char *p = rs->buf.data ();
11880 char *endp = p + get_remote_packet_size ();
11881 enum packet_result result;
11883 strcpy (p, "qGetTLSAddr:");
11884 p += strlen (p);
11885 p = write_ptid (p, endp, ptid);
11886 *p++ = ',';
11887 p += hexnumstr (p, offset);
11888 *p++ = ',';
11889 p += hexnumstr (p, lm);
11890 *p++ = '\0';
11892 putpkt (rs->buf);
11893 getpkt (&rs->buf, 0);
11894 result = packet_ok (rs->buf,
11895 &remote_protocol_packets[PACKET_qGetTLSAddr]);
11896 if (result == PACKET_OK)
11898 ULONGEST addr;
11900 unpack_varlen_hex (rs->buf.data (), &addr);
11901 return addr;
11903 else if (result == PACKET_UNKNOWN)
11904 throw_error (TLS_GENERIC_ERROR,
11905 _("Remote target doesn't support qGetTLSAddr packet"));
11906 else
11907 throw_error (TLS_GENERIC_ERROR,
11908 _("Remote target failed to process qGetTLSAddr request"));
11910 else
11911 throw_error (TLS_GENERIC_ERROR,
11912 _("TLS not supported or disabled on this target"));
11913 /* Not reached. */
11914 return 0;
11917 /* Provide thread local base, i.e. Thread Information Block address.
11918 Returns 1 if ptid is found and thread_local_base is non zero. */
11920 bool
11921 remote_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
11923 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
11925 struct remote_state *rs = get_remote_state ();
11926 char *p = rs->buf.data ();
11927 char *endp = p + get_remote_packet_size ();
11928 enum packet_result result;
11930 strcpy (p, "qGetTIBAddr:");
11931 p += strlen (p);
11932 p = write_ptid (p, endp, ptid);
11933 *p++ = '\0';
11935 putpkt (rs->buf);
11936 getpkt (&rs->buf, 0);
11937 result = packet_ok (rs->buf,
11938 &remote_protocol_packets[PACKET_qGetTIBAddr]);
11939 if (result == PACKET_OK)
11941 ULONGEST val;
11942 unpack_varlen_hex (rs->buf.data (), &val);
11943 if (addr)
11944 *addr = (CORE_ADDR) val;
11945 return true;
11947 else if (result == PACKET_UNKNOWN)
11948 error (_("Remote target doesn't support qGetTIBAddr packet"));
11949 else
11950 error (_("Remote target failed to process qGetTIBAddr request"));
11952 else
11953 error (_("qGetTIBAddr not supported or disabled on this target"));
11954 /* Not reached. */
11955 return false;
11958 /* Support for inferring a target description based on the current
11959 architecture and the size of a 'g' packet. While the 'g' packet
11960 can have any size (since optional registers can be left off the
11961 end), some sizes are easily recognizable given knowledge of the
11962 approximate architecture. */
11964 struct remote_g_packet_guess
11966 remote_g_packet_guess (int bytes_, const struct target_desc *tdesc_)
11967 : bytes (bytes_),
11968 tdesc (tdesc_)
11972 int bytes;
11973 const struct target_desc *tdesc;
11976 struct remote_g_packet_data : public allocate_on_obstack
11978 std::vector<remote_g_packet_guess> guesses;
11981 static struct gdbarch_data *remote_g_packet_data_handle;
11983 static void *
11984 remote_g_packet_data_init (struct obstack *obstack)
11986 return new (obstack) remote_g_packet_data;
11989 void
11990 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
11991 const struct target_desc *tdesc)
11993 struct remote_g_packet_data *data
11994 = ((struct remote_g_packet_data *)
11995 gdbarch_data (gdbarch, remote_g_packet_data_handle));
11997 gdb_assert (tdesc != NULL);
11999 for (const remote_g_packet_guess &guess : data->guesses)
12000 if (guess.bytes == bytes)
12001 internal_error (__FILE__, __LINE__,
12002 _("Duplicate g packet description added for size %d"),
12003 bytes);
12005 data->guesses.emplace_back (bytes, tdesc);
12008 /* Return true if remote_read_description would do anything on this target
12009 and architecture, false otherwise. */
12011 static bool
12012 remote_read_description_p (struct target_ops *target)
12014 struct remote_g_packet_data *data
12015 = ((struct remote_g_packet_data *)
12016 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
12018 return !data->guesses.empty ();
12021 const struct target_desc *
12022 remote_target::read_description ()
12024 struct remote_g_packet_data *data
12025 = ((struct remote_g_packet_data *)
12026 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
12028 /* Do not try this during initial connection, when we do not know
12029 whether there is a running but stopped thread. */
12030 if (!target_has_execution () || inferior_ptid == null_ptid)
12031 return beneath ()->read_description ();
12033 if (!data->guesses.empty ())
12035 int bytes = send_g_packet ();
12037 for (const remote_g_packet_guess &guess : data->guesses)
12038 if (guess.bytes == bytes)
12039 return guess.tdesc;
12041 /* We discard the g packet. A minor optimization would be to
12042 hold on to it, and fill the register cache once we have selected
12043 an architecture, but it's too tricky to do safely. */
12046 return beneath ()->read_description ();
12049 /* Remote file transfer support. This is host-initiated I/O, not
12050 target-initiated; for target-initiated, see remote-fileio.c. */
12052 /* If *LEFT is at least the length of STRING, copy STRING to
12053 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12054 decrease *LEFT. Otherwise raise an error. */
12056 static void
12057 remote_buffer_add_string (char **buffer, int *left, const char *string)
12059 int len = strlen (string);
12061 if (len > *left)
12062 error (_("Packet too long for target."));
12064 memcpy (*buffer, string, len);
12065 *buffer += len;
12066 *left -= len;
12068 /* NUL-terminate the buffer as a convenience, if there is
12069 room. */
12070 if (*left)
12071 **buffer = '\0';
12074 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
12075 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12076 decrease *LEFT. Otherwise raise an error. */
12078 static void
12079 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
12080 int len)
12082 if (2 * len > *left)
12083 error (_("Packet too long for target."));
12085 bin2hex (bytes, *buffer, len);
12086 *buffer += 2 * len;
12087 *left -= 2 * len;
12089 /* NUL-terminate the buffer as a convenience, if there is
12090 room. */
12091 if (*left)
12092 **buffer = '\0';
12095 /* If *LEFT is large enough, convert VALUE to hex and add it to
12096 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12097 decrease *LEFT. Otherwise raise an error. */
12099 static void
12100 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
12102 int len = hexnumlen (value);
12104 if (len > *left)
12105 error (_("Packet too long for target."));
12107 hexnumstr (*buffer, value);
12108 *buffer += len;
12109 *left -= len;
12111 /* NUL-terminate the buffer as a convenience, if there is
12112 room. */
12113 if (*left)
12114 **buffer = '\0';
12117 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
12118 value, *REMOTE_ERRNO to the remote error number or zero if none
12119 was included, and *ATTACHMENT to point to the start of the annex
12120 if any. The length of the packet isn't needed here; there may
12121 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
12123 Return 0 if the packet could be parsed, -1 if it could not. If
12124 -1 is returned, the other variables may not be initialized. */
12126 static int
12127 remote_hostio_parse_result (const char *buffer, int *retcode,
12128 int *remote_errno, const char **attachment)
12130 char *p, *p2;
12132 *remote_errno = 0;
12133 *attachment = NULL;
12135 if (buffer[0] != 'F')
12136 return -1;
12138 errno = 0;
12139 *retcode = strtol (&buffer[1], &p, 16);
12140 if (errno != 0 || p == &buffer[1])
12141 return -1;
12143 /* Check for ",errno". */
12144 if (*p == ',')
12146 errno = 0;
12147 *remote_errno = strtol (p + 1, &p2, 16);
12148 if (errno != 0 || p + 1 == p2)
12149 return -1;
12150 p = p2;
12153 /* Check for ";attachment". If there is no attachment, the
12154 packet should end here. */
12155 if (*p == ';')
12157 *attachment = p + 1;
12158 return 0;
12160 else if (*p == '\0')
12161 return 0;
12162 else
12163 return -1;
12166 /* Send a prepared I/O packet to the target and read its response.
12167 The prepared packet is in the global RS->BUF before this function
12168 is called, and the answer is there when we return.
12170 COMMAND_BYTES is the length of the request to send, which may include
12171 binary data. WHICH_PACKET is the packet configuration to check
12172 before attempting a packet. If an error occurs, *REMOTE_ERRNO
12173 is set to the error number and -1 is returned. Otherwise the value
12174 returned by the function is returned.
12176 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
12177 attachment is expected; an error will be reported if there's a
12178 mismatch. If one is found, *ATTACHMENT will be set to point into
12179 the packet buffer and *ATTACHMENT_LEN will be set to the
12180 attachment's length. */
12183 remote_target::remote_hostio_send_command (int command_bytes, int which_packet,
12184 int *remote_errno, const char **attachment,
12185 int *attachment_len)
12187 struct remote_state *rs = get_remote_state ();
12188 int ret, bytes_read;
12189 const char *attachment_tmp;
12191 if (packet_support (which_packet) == PACKET_DISABLE)
12193 *remote_errno = FILEIO_ENOSYS;
12194 return -1;
12197 putpkt_binary (rs->buf.data (), command_bytes);
12198 bytes_read = getpkt_sane (&rs->buf, 0);
12200 /* If it timed out, something is wrong. Don't try to parse the
12201 buffer. */
12202 if (bytes_read < 0)
12204 *remote_errno = FILEIO_EINVAL;
12205 return -1;
12208 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
12210 case PACKET_ERROR:
12211 *remote_errno = FILEIO_EINVAL;
12212 return -1;
12213 case PACKET_UNKNOWN:
12214 *remote_errno = FILEIO_ENOSYS;
12215 return -1;
12216 case PACKET_OK:
12217 break;
12220 if (remote_hostio_parse_result (rs->buf.data (), &ret, remote_errno,
12221 &attachment_tmp))
12223 *remote_errno = FILEIO_EINVAL;
12224 return -1;
12227 /* Make sure we saw an attachment if and only if we expected one. */
12228 if ((attachment_tmp == NULL && attachment != NULL)
12229 || (attachment_tmp != NULL && attachment == NULL))
12231 *remote_errno = FILEIO_EINVAL;
12232 return -1;
12235 /* If an attachment was found, it must point into the packet buffer;
12236 work out how many bytes there were. */
12237 if (attachment_tmp != NULL)
12239 *attachment = attachment_tmp;
12240 *attachment_len = bytes_read - (*attachment - rs->buf.data ());
12243 return ret;
12246 /* See declaration.h. */
12248 void
12249 readahead_cache::invalidate ()
12251 this->fd = -1;
12254 /* See declaration.h. */
12256 void
12257 readahead_cache::invalidate_fd (int fd)
12259 if (this->fd == fd)
12260 this->fd = -1;
12263 /* Set the filesystem remote_hostio functions that take FILENAME
12264 arguments will use. Return 0 on success, or -1 if an error
12265 occurs (and set *REMOTE_ERRNO). */
12268 remote_target::remote_hostio_set_filesystem (struct inferior *inf,
12269 int *remote_errno)
12271 struct remote_state *rs = get_remote_state ();
12272 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
12273 char *p = rs->buf.data ();
12274 int left = get_remote_packet_size () - 1;
12275 char arg[9];
12276 int ret;
12278 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
12279 return 0;
12281 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
12282 return 0;
12284 remote_buffer_add_string (&p, &left, "vFile:setfs:");
12286 xsnprintf (arg, sizeof (arg), "%x", required_pid);
12287 remote_buffer_add_string (&p, &left, arg);
12289 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_setfs,
12290 remote_errno, NULL, NULL);
12292 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
12293 return 0;
12295 if (ret == 0)
12296 rs->fs_pid = required_pid;
12298 return ret;
12301 /* Implementation of to_fileio_open. */
12304 remote_target::remote_hostio_open (inferior *inf, const char *filename,
12305 int flags, int mode, int warn_if_slow,
12306 int *remote_errno)
12308 struct remote_state *rs = get_remote_state ();
12309 char *p = rs->buf.data ();
12310 int left = get_remote_packet_size () - 1;
12312 if (warn_if_slow)
12314 static int warning_issued = 0;
12316 gdb_printf (_("Reading %s from remote target...\n"),
12317 filename);
12319 if (!warning_issued)
12321 warning (_("File transfers from remote targets can be slow."
12322 " Use \"set sysroot\" to access files locally"
12323 " instead."));
12324 warning_issued = 1;
12328 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12329 return -1;
12331 remote_buffer_add_string (&p, &left, "vFile:open:");
12333 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12334 strlen (filename));
12335 remote_buffer_add_string (&p, &left, ",");
12337 remote_buffer_add_int (&p, &left, flags);
12338 remote_buffer_add_string (&p, &left, ",");
12340 remote_buffer_add_int (&p, &left, mode);
12342 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_open,
12343 remote_errno, NULL, NULL);
12347 remote_target::fileio_open (struct inferior *inf, const char *filename,
12348 int flags, int mode, int warn_if_slow,
12349 int *remote_errno)
12351 return remote_hostio_open (inf, filename, flags, mode, warn_if_slow,
12352 remote_errno);
12355 /* Implementation of to_fileio_pwrite. */
12358 remote_target::remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
12359 ULONGEST offset, int *remote_errno)
12361 struct remote_state *rs = get_remote_state ();
12362 char *p = rs->buf.data ();
12363 int left = get_remote_packet_size ();
12364 int out_len;
12366 rs->readahead_cache.invalidate_fd (fd);
12368 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
12370 remote_buffer_add_int (&p, &left, fd);
12371 remote_buffer_add_string (&p, &left, ",");
12373 remote_buffer_add_int (&p, &left, offset);
12374 remote_buffer_add_string (&p, &left, ",");
12376 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
12377 (get_remote_packet_size ()
12378 - (p - rs->buf.data ())));
12380 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pwrite,
12381 remote_errno, NULL, NULL);
12385 remote_target::fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
12386 ULONGEST offset, int *remote_errno)
12388 return remote_hostio_pwrite (fd, write_buf, len, offset, remote_errno);
12391 /* Helper for the implementation of to_fileio_pread. Read the file
12392 from the remote side with vFile:pread. */
12395 remote_target::remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
12396 ULONGEST offset, int *remote_errno)
12398 struct remote_state *rs = get_remote_state ();
12399 char *p = rs->buf.data ();
12400 const char *attachment;
12401 int left = get_remote_packet_size ();
12402 int ret, attachment_len;
12403 int read_len;
12405 remote_buffer_add_string (&p, &left, "vFile:pread:");
12407 remote_buffer_add_int (&p, &left, fd);
12408 remote_buffer_add_string (&p, &left, ",");
12410 remote_buffer_add_int (&p, &left, len);
12411 remote_buffer_add_string (&p, &left, ",");
12413 remote_buffer_add_int (&p, &left, offset);
12415 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pread,
12416 remote_errno, &attachment,
12417 &attachment_len);
12419 if (ret < 0)
12420 return ret;
12422 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12423 read_buf, len);
12424 if (read_len != ret)
12425 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
12427 return ret;
12430 /* See declaration.h. */
12433 readahead_cache::pread (int fd, gdb_byte *read_buf, size_t len,
12434 ULONGEST offset)
12436 if (this->fd == fd
12437 && this->offset <= offset
12438 && offset < this->offset + this->bufsize)
12440 ULONGEST max = this->offset + this->bufsize;
12442 if (offset + len > max)
12443 len = max - offset;
12445 memcpy (read_buf, this->buf + offset - this->offset, len);
12446 return len;
12449 return 0;
12452 /* Implementation of to_fileio_pread. */
12455 remote_target::remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
12456 ULONGEST offset, int *remote_errno)
12458 int ret;
12459 struct remote_state *rs = get_remote_state ();
12460 readahead_cache *cache = &rs->readahead_cache;
12462 ret = cache->pread (fd, read_buf, len, offset);
12463 if (ret > 0)
12465 cache->hit_count++;
12467 remote_debug_printf ("readahead cache hit %s",
12468 pulongest (cache->hit_count));
12469 return ret;
12472 cache->miss_count++;
12474 remote_debug_printf ("readahead cache miss %s",
12475 pulongest (cache->miss_count));
12477 cache->fd = fd;
12478 cache->offset = offset;
12479 cache->bufsize = get_remote_packet_size ();
12480 cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
12482 ret = remote_hostio_pread_vFile (cache->fd, cache->buf, cache->bufsize,
12483 cache->offset, remote_errno);
12484 if (ret <= 0)
12486 cache->invalidate_fd (fd);
12487 return ret;
12490 cache->bufsize = ret;
12491 return cache->pread (fd, read_buf, len, offset);
12495 remote_target::fileio_pread (int fd, gdb_byte *read_buf, int len,
12496 ULONGEST offset, int *remote_errno)
12498 return remote_hostio_pread (fd, read_buf, len, offset, remote_errno);
12501 /* Implementation of to_fileio_close. */
12504 remote_target::remote_hostio_close (int fd, int *remote_errno)
12506 struct remote_state *rs = get_remote_state ();
12507 char *p = rs->buf.data ();
12508 int left = get_remote_packet_size () - 1;
12510 rs->readahead_cache.invalidate_fd (fd);
12512 remote_buffer_add_string (&p, &left, "vFile:close:");
12514 remote_buffer_add_int (&p, &left, fd);
12516 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_close,
12517 remote_errno, NULL, NULL);
12521 remote_target::fileio_close (int fd, int *remote_errno)
12523 return remote_hostio_close (fd, remote_errno);
12526 /* Implementation of to_fileio_unlink. */
12529 remote_target::remote_hostio_unlink (inferior *inf, const char *filename,
12530 int *remote_errno)
12532 struct remote_state *rs = get_remote_state ();
12533 char *p = rs->buf.data ();
12534 int left = get_remote_packet_size () - 1;
12536 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12537 return -1;
12539 remote_buffer_add_string (&p, &left, "vFile:unlink:");
12541 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12542 strlen (filename));
12544 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_unlink,
12545 remote_errno, NULL, NULL);
12549 remote_target::fileio_unlink (struct inferior *inf, const char *filename,
12550 int *remote_errno)
12552 return remote_hostio_unlink (inf, filename, remote_errno);
12555 /* Implementation of to_fileio_readlink. */
12557 gdb::optional<std::string>
12558 remote_target::fileio_readlink (struct inferior *inf, const char *filename,
12559 int *remote_errno)
12561 struct remote_state *rs = get_remote_state ();
12562 char *p = rs->buf.data ();
12563 const char *attachment;
12564 int left = get_remote_packet_size ();
12565 int len, attachment_len;
12566 int read_len;
12568 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12569 return {};
12571 remote_buffer_add_string (&p, &left, "vFile:readlink:");
12573 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12574 strlen (filename));
12576 len = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_readlink,
12577 remote_errno, &attachment,
12578 &attachment_len);
12580 if (len < 0)
12581 return {};
12583 std::string ret (len, '\0');
12585 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12586 (gdb_byte *) &ret[0], len);
12587 if (read_len != len)
12588 error (_("Readlink returned %d, but %d bytes."), len, read_len);
12590 return ret;
12593 /* Implementation of to_fileio_fstat. */
12596 remote_target::fileio_fstat (int fd, struct stat *st, int *remote_errno)
12598 struct remote_state *rs = get_remote_state ();
12599 char *p = rs->buf.data ();
12600 int left = get_remote_packet_size ();
12601 int attachment_len, ret;
12602 const char *attachment;
12603 struct fio_stat fst;
12604 int read_len;
12606 remote_buffer_add_string (&p, &left, "vFile:fstat:");
12608 remote_buffer_add_int (&p, &left, fd);
12610 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_fstat,
12611 remote_errno, &attachment,
12612 &attachment_len);
12613 if (ret < 0)
12615 if (*remote_errno != FILEIO_ENOSYS)
12616 return ret;
12618 /* Strictly we should return -1, ENOSYS here, but when
12619 "set sysroot remote:" was implemented in August 2008
12620 BFD's need for a stat function was sidestepped with
12621 this hack. This was not remedied until March 2015
12622 so we retain the previous behavior to avoid breaking
12623 compatibility.
12625 Note that the memset is a March 2015 addition; older
12626 GDBs set st_size *and nothing else* so the structure
12627 would have garbage in all other fields. This might
12628 break something but retaining the previous behavior
12629 here would be just too wrong. */
12631 memset (st, 0, sizeof (struct stat));
12632 st->st_size = INT_MAX;
12633 return 0;
12636 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12637 (gdb_byte *) &fst, sizeof (fst));
12639 if (read_len != ret)
12640 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
12642 if (read_len != sizeof (fst))
12643 error (_("vFile:fstat returned %d bytes, but expecting %d."),
12644 read_len, (int) sizeof (fst));
12646 remote_fileio_to_host_stat (&fst, st);
12648 return 0;
12651 /* Implementation of to_filesystem_is_local. */
12653 bool
12654 remote_target::filesystem_is_local ()
12656 /* Valgrind GDB presents itself as a remote target but works
12657 on the local filesystem: it does not implement remote get
12658 and users are not expected to set a sysroot. To handle
12659 this case we treat the remote filesystem as local if the
12660 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
12661 does not support vFile:open. */
12662 if (gdb_sysroot == TARGET_SYSROOT_PREFIX)
12664 enum packet_support ps = packet_support (PACKET_vFile_open);
12666 if (ps == PACKET_SUPPORT_UNKNOWN)
12668 int fd, remote_errno;
12670 /* Try opening a file to probe support. The supplied
12671 filename is irrelevant, we only care about whether
12672 the stub recognizes the packet or not. */
12673 fd = remote_hostio_open (NULL, "just probing",
12674 FILEIO_O_RDONLY, 0700, 0,
12675 &remote_errno);
12677 if (fd >= 0)
12678 remote_hostio_close (fd, &remote_errno);
12680 ps = packet_support (PACKET_vFile_open);
12683 if (ps == PACKET_DISABLE)
12685 static int warning_issued = 0;
12687 if (!warning_issued)
12689 warning (_("remote target does not support file"
12690 " transfer, attempting to access files"
12691 " from local filesystem."));
12692 warning_issued = 1;
12695 return true;
12699 return false;
12702 static int
12703 remote_fileio_errno_to_host (int errnum)
12705 switch (errnum)
12707 case FILEIO_EPERM:
12708 return EPERM;
12709 case FILEIO_ENOENT:
12710 return ENOENT;
12711 case FILEIO_EINTR:
12712 return EINTR;
12713 case FILEIO_EIO:
12714 return EIO;
12715 case FILEIO_EBADF:
12716 return EBADF;
12717 case FILEIO_EACCES:
12718 return EACCES;
12719 case FILEIO_EFAULT:
12720 return EFAULT;
12721 case FILEIO_EBUSY:
12722 return EBUSY;
12723 case FILEIO_EEXIST:
12724 return EEXIST;
12725 case FILEIO_ENODEV:
12726 return ENODEV;
12727 case FILEIO_ENOTDIR:
12728 return ENOTDIR;
12729 case FILEIO_EISDIR:
12730 return EISDIR;
12731 case FILEIO_EINVAL:
12732 return EINVAL;
12733 case FILEIO_ENFILE:
12734 return ENFILE;
12735 case FILEIO_EMFILE:
12736 return EMFILE;
12737 case FILEIO_EFBIG:
12738 return EFBIG;
12739 case FILEIO_ENOSPC:
12740 return ENOSPC;
12741 case FILEIO_ESPIPE:
12742 return ESPIPE;
12743 case FILEIO_EROFS:
12744 return EROFS;
12745 case FILEIO_ENOSYS:
12746 return ENOSYS;
12747 case FILEIO_ENAMETOOLONG:
12748 return ENAMETOOLONG;
12750 return -1;
12753 static char *
12754 remote_hostio_error (int errnum)
12756 int host_error = remote_fileio_errno_to_host (errnum);
12758 if (host_error == -1)
12759 error (_("Unknown remote I/O error %d"), errnum);
12760 else
12761 error (_("Remote I/O error: %s"), safe_strerror (host_error));
12764 /* A RAII wrapper around a remote file descriptor. */
12766 class scoped_remote_fd
12768 public:
12769 scoped_remote_fd (remote_target *remote, int fd)
12770 : m_remote (remote), m_fd (fd)
12774 ~scoped_remote_fd ()
12776 if (m_fd != -1)
12780 int remote_errno;
12781 m_remote->remote_hostio_close (m_fd, &remote_errno);
12783 catch (...)
12785 /* Swallow exception before it escapes the dtor. If
12786 something goes wrong, likely the connection is gone,
12787 and there's nothing else that can be done. */
12792 DISABLE_COPY_AND_ASSIGN (scoped_remote_fd);
12794 /* Release ownership of the file descriptor, and return it. */
12795 ATTRIBUTE_UNUSED_RESULT int release () noexcept
12797 int fd = m_fd;
12798 m_fd = -1;
12799 return fd;
12802 /* Return the owned file descriptor. */
12803 int get () const noexcept
12805 return m_fd;
12808 private:
12809 /* The remote target. */
12810 remote_target *m_remote;
12812 /* The owned remote I/O file descriptor. */
12813 int m_fd;
12816 void
12817 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
12819 remote_target *remote = get_current_remote_target ();
12821 if (remote == nullptr)
12822 error (_("command can only be used with remote target"));
12824 remote->remote_file_put (local_file, remote_file, from_tty);
12827 void
12828 remote_target::remote_file_put (const char *local_file, const char *remote_file,
12829 int from_tty)
12831 int retcode, remote_errno, bytes, io_size;
12832 int bytes_in_buffer;
12833 int saw_eof;
12834 ULONGEST offset;
12836 gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
12837 if (file == NULL)
12838 perror_with_name (local_file);
12840 scoped_remote_fd fd
12841 (this, remote_hostio_open (NULL,
12842 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
12843 | FILEIO_O_TRUNC),
12844 0700, 0, &remote_errno));
12845 if (fd.get () == -1)
12846 remote_hostio_error (remote_errno);
12848 /* Send up to this many bytes at once. They won't all fit in the
12849 remote packet limit, so we'll transfer slightly fewer. */
12850 io_size = get_remote_packet_size ();
12851 gdb::byte_vector buffer (io_size);
12853 bytes_in_buffer = 0;
12854 saw_eof = 0;
12855 offset = 0;
12856 while (bytes_in_buffer || !saw_eof)
12858 if (!saw_eof)
12860 bytes = fread (buffer.data () + bytes_in_buffer, 1,
12861 io_size - bytes_in_buffer,
12862 file.get ());
12863 if (bytes == 0)
12865 if (ferror (file.get ()))
12866 error (_("Error reading %s."), local_file);
12867 else
12869 /* EOF. Unless there is something still in the
12870 buffer from the last iteration, we are done. */
12871 saw_eof = 1;
12872 if (bytes_in_buffer == 0)
12873 break;
12877 else
12878 bytes = 0;
12880 bytes += bytes_in_buffer;
12881 bytes_in_buffer = 0;
12883 retcode = remote_hostio_pwrite (fd.get (), buffer.data (), bytes,
12884 offset, &remote_errno);
12886 if (retcode < 0)
12887 remote_hostio_error (remote_errno);
12888 else if (retcode == 0)
12889 error (_("Remote write of %d bytes returned 0!"), bytes);
12890 else if (retcode < bytes)
12892 /* Short write. Save the rest of the read data for the next
12893 write. */
12894 bytes_in_buffer = bytes - retcode;
12895 memmove (buffer.data (), buffer.data () + retcode, bytes_in_buffer);
12898 offset += retcode;
12901 if (remote_hostio_close (fd.release (), &remote_errno))
12902 remote_hostio_error (remote_errno);
12904 if (from_tty)
12905 gdb_printf (_("Successfully sent file \"%s\".\n"), local_file);
12908 void
12909 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
12911 remote_target *remote = get_current_remote_target ();
12913 if (remote == nullptr)
12914 error (_("command can only be used with remote target"));
12916 remote->remote_file_get (remote_file, local_file, from_tty);
12919 void
12920 remote_target::remote_file_get (const char *remote_file, const char *local_file,
12921 int from_tty)
12923 int remote_errno, bytes, io_size;
12924 ULONGEST offset;
12926 scoped_remote_fd fd
12927 (this, remote_hostio_open (NULL,
12928 remote_file, FILEIO_O_RDONLY, 0, 0,
12929 &remote_errno));
12930 if (fd.get () == -1)
12931 remote_hostio_error (remote_errno);
12933 gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
12934 if (file == NULL)
12935 perror_with_name (local_file);
12937 /* Send up to this many bytes at once. They won't all fit in the
12938 remote packet limit, so we'll transfer slightly fewer. */
12939 io_size = get_remote_packet_size ();
12940 gdb::byte_vector buffer (io_size);
12942 offset = 0;
12943 while (1)
12945 bytes = remote_hostio_pread (fd.get (), buffer.data (), io_size, offset,
12946 &remote_errno);
12947 if (bytes == 0)
12948 /* Success, but no bytes, means end-of-file. */
12949 break;
12950 if (bytes == -1)
12951 remote_hostio_error (remote_errno);
12953 offset += bytes;
12955 bytes = fwrite (buffer.data (), 1, bytes, file.get ());
12956 if (bytes == 0)
12957 perror_with_name (local_file);
12960 if (remote_hostio_close (fd.release (), &remote_errno))
12961 remote_hostio_error (remote_errno);
12963 if (from_tty)
12964 gdb_printf (_("Successfully fetched file \"%s\".\n"), remote_file);
12967 void
12968 remote_file_delete (const char *remote_file, int from_tty)
12970 remote_target *remote = get_current_remote_target ();
12972 if (remote == nullptr)
12973 error (_("command can only be used with remote target"));
12975 remote->remote_file_delete (remote_file, from_tty);
12978 void
12979 remote_target::remote_file_delete (const char *remote_file, int from_tty)
12981 int retcode, remote_errno;
12983 retcode = remote_hostio_unlink (NULL, remote_file, &remote_errno);
12984 if (retcode == -1)
12985 remote_hostio_error (remote_errno);
12987 if (from_tty)
12988 gdb_printf (_("Successfully deleted file \"%s\".\n"), remote_file);
12991 static void
12992 remote_put_command (const char *args, int from_tty)
12994 if (args == NULL)
12995 error_no_arg (_("file to put"));
12997 gdb_argv argv (args);
12998 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12999 error (_("Invalid parameters to remote put"));
13001 remote_file_put (argv[0], argv[1], from_tty);
13004 static void
13005 remote_get_command (const char *args, int from_tty)
13007 if (args == NULL)
13008 error_no_arg (_("file to get"));
13010 gdb_argv argv (args);
13011 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
13012 error (_("Invalid parameters to remote get"));
13014 remote_file_get (argv[0], argv[1], from_tty);
13017 static void
13018 remote_delete_command (const char *args, int from_tty)
13020 if (args == NULL)
13021 error_no_arg (_("file to delete"));
13023 gdb_argv argv (args);
13024 if (argv[0] == NULL || argv[1] != NULL)
13025 error (_("Invalid parameters to remote delete"));
13027 remote_file_delete (argv[0], from_tty);
13030 bool
13031 remote_target::can_execute_reverse ()
13033 if (packet_support (PACKET_bs) == PACKET_ENABLE
13034 || packet_support (PACKET_bc) == PACKET_ENABLE)
13035 return true;
13036 else
13037 return false;
13040 bool
13041 remote_target::supports_non_stop ()
13043 return true;
13046 bool
13047 remote_target::supports_disable_randomization ()
13049 /* Only supported in extended mode. */
13050 return false;
13053 bool
13054 remote_target::supports_multi_process ()
13056 struct remote_state *rs = get_remote_state ();
13058 return remote_multi_process_p (rs);
13061 static int
13062 remote_supports_cond_tracepoints ()
13064 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
13067 bool
13068 remote_target::supports_evaluation_of_breakpoint_conditions ()
13070 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
13073 static int
13074 remote_supports_fast_tracepoints ()
13076 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
13079 static int
13080 remote_supports_static_tracepoints ()
13082 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
13085 static int
13086 remote_supports_install_in_trace ()
13088 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
13091 bool
13092 remote_target::supports_enable_disable_tracepoint ()
13094 return (packet_support (PACKET_EnableDisableTracepoints_feature)
13095 == PACKET_ENABLE);
13098 bool
13099 remote_target::supports_string_tracing ()
13101 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
13104 bool
13105 remote_target::can_run_breakpoint_commands ()
13107 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
13110 void
13111 remote_target::trace_init ()
13113 struct remote_state *rs = get_remote_state ();
13115 putpkt ("QTinit");
13116 remote_get_noisy_reply ();
13117 if (strcmp (rs->buf.data (), "OK") != 0)
13118 error (_("Target does not support this command."));
13121 /* Recursive routine to walk through command list including loops, and
13122 download packets for each command. */
13124 void
13125 remote_target::remote_download_command_source (int num, ULONGEST addr,
13126 struct command_line *cmds)
13128 struct remote_state *rs = get_remote_state ();
13129 struct command_line *cmd;
13131 for (cmd = cmds; cmd; cmd = cmd->next)
13133 QUIT; /* Allow user to bail out with ^C. */
13134 strcpy (rs->buf.data (), "QTDPsrc:");
13135 encode_source_string (num, addr, "cmd", cmd->line,
13136 rs->buf.data () + strlen (rs->buf.data ()),
13137 rs->buf.size () - strlen (rs->buf.data ()));
13138 putpkt (rs->buf);
13139 remote_get_noisy_reply ();
13140 if (strcmp (rs->buf.data (), "OK"))
13141 warning (_("Target does not support source download."));
13143 if (cmd->control_type == while_control
13144 || cmd->control_type == while_stepping_control)
13146 remote_download_command_source (num, addr, cmd->body_list_0.get ());
13148 QUIT; /* Allow user to bail out with ^C. */
13149 strcpy (rs->buf.data (), "QTDPsrc:");
13150 encode_source_string (num, addr, "cmd", "end",
13151 rs->buf.data () + strlen (rs->buf.data ()),
13152 rs->buf.size () - strlen (rs->buf.data ()));
13153 putpkt (rs->buf);
13154 remote_get_noisy_reply ();
13155 if (strcmp (rs->buf.data (), "OK"))
13156 warning (_("Target does not support source download."));
13161 void
13162 remote_target::download_tracepoint (struct bp_location *loc)
13164 CORE_ADDR tpaddr;
13165 char addrbuf[40];
13166 std::vector<std::string> tdp_actions;
13167 std::vector<std::string> stepping_actions;
13168 char *pkt;
13169 struct breakpoint *b = loc->owner;
13170 struct tracepoint *t = (struct tracepoint *) b;
13171 struct remote_state *rs = get_remote_state ();
13172 int ret;
13173 const char *err_msg = _("Tracepoint packet too large for target.");
13174 size_t size_left;
13176 /* We use a buffer other than rs->buf because we'll build strings
13177 across multiple statements, and other statements in between could
13178 modify rs->buf. */
13179 gdb::char_vector buf (get_remote_packet_size ());
13181 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
13183 tpaddr = loc->address;
13184 strcpy (addrbuf, phex (tpaddr, sizeof (CORE_ADDR)));
13185 ret = snprintf (buf.data (), buf.size (), "QTDP:%x:%s:%c:%lx:%x",
13186 b->number, addrbuf, /* address */
13187 (b->enable_state == bp_enabled ? 'E' : 'D'),
13188 t->step_count, t->pass_count);
13190 if (ret < 0 || ret >= buf.size ())
13191 error ("%s", err_msg);
13193 /* Fast tracepoints are mostly handled by the target, but we can
13194 tell the target how big of an instruction block should be moved
13195 around. */
13196 if (b->type == bp_fast_tracepoint)
13198 /* Only test for support at download time; we may not know
13199 target capabilities at definition time. */
13200 if (remote_supports_fast_tracepoints ())
13202 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
13203 NULL))
13205 size_left = buf.size () - strlen (buf.data ());
13206 ret = snprintf (buf.data () + strlen (buf.data ()),
13207 size_left, ":F%x",
13208 gdb_insn_length (loc->gdbarch, tpaddr));
13210 if (ret < 0 || ret >= size_left)
13211 error ("%s", err_msg);
13213 else
13214 /* If it passed validation at definition but fails now,
13215 something is very wrong. */
13216 internal_error (__FILE__, __LINE__,
13217 _("Fast tracepoint not "
13218 "valid during download"));
13220 else
13221 /* Fast tracepoints are functionally identical to regular
13222 tracepoints, so don't take lack of support as a reason to
13223 give up on the trace run. */
13224 warning (_("Target does not support fast tracepoints, "
13225 "downloading %d as regular tracepoint"), b->number);
13227 else if (b->type == bp_static_tracepoint)
13229 /* Only test for support at download time; we may not know
13230 target capabilities at definition time. */
13231 if (remote_supports_static_tracepoints ())
13233 struct static_tracepoint_marker marker;
13235 if (target_static_tracepoint_marker_at (tpaddr, &marker))
13237 size_left = buf.size () - strlen (buf.data ());
13238 ret = snprintf (buf.data () + strlen (buf.data ()),
13239 size_left, ":S");
13241 if (ret < 0 || ret >= size_left)
13242 error ("%s", err_msg);
13244 else
13245 error (_("Static tracepoint not valid during download"));
13247 else
13248 /* Fast tracepoints are functionally identical to regular
13249 tracepoints, so don't take lack of support as a reason
13250 to give up on the trace run. */
13251 error (_("Target does not support static tracepoints"));
13253 /* If the tracepoint has a conditional, make it into an agent
13254 expression and append to the definition. */
13255 if (loc->cond)
13257 /* Only test support at download time, we may not know target
13258 capabilities at definition time. */
13259 if (remote_supports_cond_tracepoints ())
13261 agent_expr_up aexpr = gen_eval_for_expr (tpaddr,
13262 loc->cond.get ());
13264 size_left = buf.size () - strlen (buf.data ());
13266 ret = snprintf (buf.data () + strlen (buf.data ()),
13267 size_left, ":X%x,", aexpr->len);
13269 if (ret < 0 || ret >= size_left)
13270 error ("%s", err_msg);
13272 size_left = buf.size () - strlen (buf.data ());
13274 /* Two bytes to encode each aexpr byte, plus the terminating
13275 null byte. */
13276 if (aexpr->len * 2 + 1 > size_left)
13277 error ("%s", err_msg);
13279 pkt = buf.data () + strlen (buf.data ());
13281 for (int ndx = 0; ndx < aexpr->len; ++ndx)
13282 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
13283 *pkt = '\0';
13285 else
13286 warning (_("Target does not support conditional tracepoints, "
13287 "ignoring tp %d cond"), b->number);
13290 if (b->commands || !default_collect.empty ())
13292 size_left = buf.size () - strlen (buf.data ());
13294 ret = snprintf (buf.data () + strlen (buf.data ()),
13295 size_left, "-");
13297 if (ret < 0 || ret >= size_left)
13298 error ("%s", err_msg);
13301 putpkt (buf.data ());
13302 remote_get_noisy_reply ();
13303 if (strcmp (rs->buf.data (), "OK"))
13304 error (_("Target does not support tracepoints."));
13306 /* do_single_steps (t); */
13307 for (auto action_it = tdp_actions.begin ();
13308 action_it != tdp_actions.end (); action_it++)
13310 QUIT; /* Allow user to bail out with ^C. */
13312 bool has_more = ((action_it + 1) != tdp_actions.end ()
13313 || !stepping_actions.empty ());
13315 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%c",
13316 b->number, addrbuf, /* address */
13317 action_it->c_str (),
13318 has_more ? '-' : 0);
13320 if (ret < 0 || ret >= buf.size ())
13321 error ("%s", err_msg);
13323 putpkt (buf.data ());
13324 remote_get_noisy_reply ();
13325 if (strcmp (rs->buf.data (), "OK"))
13326 error (_("Error on target while setting tracepoints."));
13329 for (auto action_it = stepping_actions.begin ();
13330 action_it != stepping_actions.end (); action_it++)
13332 QUIT; /* Allow user to bail out with ^C. */
13334 bool is_first = action_it == stepping_actions.begin ();
13335 bool has_more = (action_it + 1) != stepping_actions.end ();
13337 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%s%s",
13338 b->number, addrbuf, /* address */
13339 is_first ? "S" : "",
13340 action_it->c_str (),
13341 has_more ? "-" : "");
13343 if (ret < 0 || ret >= buf.size ())
13344 error ("%s", err_msg);
13346 putpkt (buf.data ());
13347 remote_get_noisy_reply ();
13348 if (strcmp (rs->buf.data (), "OK"))
13349 error (_("Error on target while setting tracepoints."));
13352 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
13354 if (b->location != NULL)
13356 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13358 if (ret < 0 || ret >= buf.size ())
13359 error ("%s", err_msg);
13361 encode_source_string (b->number, loc->address, "at",
13362 event_location_to_string (b->location.get ()),
13363 buf.data () + strlen (buf.data ()),
13364 buf.size () - strlen (buf.data ()));
13365 putpkt (buf.data ());
13366 remote_get_noisy_reply ();
13367 if (strcmp (rs->buf.data (), "OK"))
13368 warning (_("Target does not support source download."));
13370 if (b->cond_string)
13372 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13374 if (ret < 0 || ret >= buf.size ())
13375 error ("%s", err_msg);
13377 encode_source_string (b->number, loc->address,
13378 "cond", b->cond_string.get (),
13379 buf.data () + strlen (buf.data ()),
13380 buf.size () - strlen (buf.data ()));
13381 putpkt (buf.data ());
13382 remote_get_noisy_reply ();
13383 if (strcmp (rs->buf.data (), "OK"))
13384 warning (_("Target does not support source download."));
13386 remote_download_command_source (b->number, loc->address,
13387 breakpoint_commands (b));
13391 bool
13392 remote_target::can_download_tracepoint ()
13394 struct remote_state *rs = get_remote_state ();
13395 struct trace_status *ts;
13396 int status;
13398 /* Don't try to install tracepoints until we've relocated our
13399 symbols, and fetched and merged the target's tracepoint list with
13400 ours. */
13401 if (rs->starting_up)
13402 return false;
13404 ts = current_trace_status ();
13405 status = get_trace_status (ts);
13407 if (status == -1 || !ts->running_known || !ts->running)
13408 return false;
13410 /* If we are in a tracing experiment, but remote stub doesn't support
13411 installing tracepoint in trace, we have to return. */
13412 if (!remote_supports_install_in_trace ())
13413 return false;
13415 return true;
13419 void
13420 remote_target::download_trace_state_variable (const trace_state_variable &tsv)
13422 struct remote_state *rs = get_remote_state ();
13423 char *p;
13425 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDV:%x:%s:%x:",
13426 tsv.number, phex ((ULONGEST) tsv.initial_value, 8),
13427 tsv.builtin);
13428 p = rs->buf.data () + strlen (rs->buf.data ());
13429 if ((p - rs->buf.data ()) + tsv.name.length () * 2
13430 >= get_remote_packet_size ())
13431 error (_("Trace state variable name too long for tsv definition packet"));
13432 p += 2 * bin2hex ((gdb_byte *) (tsv.name.data ()), p, tsv.name.length ());
13433 *p++ = '\0';
13434 putpkt (rs->buf);
13435 remote_get_noisy_reply ();
13436 if (rs->buf[0] == '\0')
13437 error (_("Target does not support this command."));
13438 if (strcmp (rs->buf.data (), "OK") != 0)
13439 error (_("Error on target while downloading trace state variable."));
13442 void
13443 remote_target::enable_tracepoint (struct bp_location *location)
13445 struct remote_state *rs = get_remote_state ();
13447 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTEnable:%x:%s",
13448 location->owner->number,
13449 phex (location->address, sizeof (CORE_ADDR)));
13450 putpkt (rs->buf);
13451 remote_get_noisy_reply ();
13452 if (rs->buf[0] == '\0')
13453 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
13454 if (strcmp (rs->buf.data (), "OK") != 0)
13455 error (_("Error on target while enabling tracepoint."));
13458 void
13459 remote_target::disable_tracepoint (struct bp_location *location)
13461 struct remote_state *rs = get_remote_state ();
13463 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDisable:%x:%s",
13464 location->owner->number,
13465 phex (location->address, sizeof (CORE_ADDR)));
13466 putpkt (rs->buf);
13467 remote_get_noisy_reply ();
13468 if (rs->buf[0] == '\0')
13469 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
13470 if (strcmp (rs->buf.data (), "OK") != 0)
13471 error (_("Error on target while disabling tracepoint."));
13474 void
13475 remote_target::trace_set_readonly_regions ()
13477 asection *s;
13478 bfd_size_type size;
13479 bfd_vma vma;
13480 int anysecs = 0;
13481 int offset = 0;
13483 if (!current_program_space->exec_bfd ())
13484 return; /* No information to give. */
13486 struct remote_state *rs = get_remote_state ();
13488 strcpy (rs->buf.data (), "QTro");
13489 offset = strlen (rs->buf.data ());
13490 for (s = current_program_space->exec_bfd ()->sections; s; s = s->next)
13492 char tmp1[40], tmp2[40];
13493 int sec_length;
13495 if ((s->flags & SEC_LOAD) == 0 ||
13496 /* (s->flags & SEC_CODE) == 0 || */
13497 (s->flags & SEC_READONLY) == 0)
13498 continue;
13500 anysecs = 1;
13501 vma = bfd_section_vma (s);
13502 size = bfd_section_size (s);
13503 sprintf_vma (tmp1, vma);
13504 sprintf_vma (tmp2, vma + size);
13505 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
13506 if (offset + sec_length + 1 > rs->buf.size ())
13508 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
13509 warning (_("\
13510 Too many sections for read-only sections definition packet."));
13511 break;
13513 xsnprintf (rs->buf.data () + offset, rs->buf.size () - offset, ":%s,%s",
13514 tmp1, tmp2);
13515 offset += sec_length;
13517 if (anysecs)
13519 putpkt (rs->buf);
13520 getpkt (&rs->buf, 0);
13524 void
13525 remote_target::trace_start ()
13527 struct remote_state *rs = get_remote_state ();
13529 putpkt ("QTStart");
13530 remote_get_noisy_reply ();
13531 if (rs->buf[0] == '\0')
13532 error (_("Target does not support this command."));
13533 if (strcmp (rs->buf.data (), "OK") != 0)
13534 error (_("Bogus reply from target: %s"), rs->buf.data ());
13538 remote_target::get_trace_status (struct trace_status *ts)
13540 /* Initialize it just to avoid a GCC false warning. */
13541 char *p = NULL;
13542 enum packet_result result;
13543 struct remote_state *rs = get_remote_state ();
13545 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
13546 return -1;
13548 /* FIXME we need to get register block size some other way. */
13549 trace_regblock_size
13550 = rs->get_remote_arch_state (target_gdbarch ())->sizeof_g_packet;
13552 putpkt ("qTStatus");
13556 p = remote_get_noisy_reply ();
13558 catch (const gdb_exception_error &ex)
13560 if (ex.error != TARGET_CLOSE_ERROR)
13562 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
13563 return -1;
13565 throw;
13568 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
13570 /* If the remote target doesn't do tracing, flag it. */
13571 if (result == PACKET_UNKNOWN)
13572 return -1;
13574 /* We're working with a live target. */
13575 ts->filename = NULL;
13577 if (*p++ != 'T')
13578 error (_("Bogus trace status reply from target: %s"), rs->buf.data ());
13580 /* Function 'parse_trace_status' sets default value of each field of
13581 'ts' at first, so we don't have to do it here. */
13582 parse_trace_status (p, ts);
13584 return ts->running;
13587 void
13588 remote_target::get_tracepoint_status (struct breakpoint *bp,
13589 struct uploaded_tp *utp)
13591 struct remote_state *rs = get_remote_state ();
13592 char *reply;
13593 struct tracepoint *tp = (struct tracepoint *) bp;
13594 size_t size = get_remote_packet_size ();
13596 if (tp)
13598 tp->hit_count = 0;
13599 tp->traceframe_usage = 0;
13600 for (bp_location *loc : tp->locations ())
13602 /* If the tracepoint was never downloaded, don't go asking for
13603 any status. */
13604 if (tp->number_on_target == 0)
13605 continue;
13606 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", tp->number_on_target,
13607 phex_nz (loc->address, 0));
13608 putpkt (rs->buf);
13609 reply = remote_get_noisy_reply ();
13610 if (reply && *reply)
13612 if (*reply == 'V')
13613 parse_tracepoint_status (reply + 1, bp, utp);
13617 else if (utp)
13619 utp->hit_count = 0;
13620 utp->traceframe_usage = 0;
13621 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", utp->number,
13622 phex_nz (utp->addr, 0));
13623 putpkt (rs->buf);
13624 reply = remote_get_noisy_reply ();
13625 if (reply && *reply)
13627 if (*reply == 'V')
13628 parse_tracepoint_status (reply + 1, bp, utp);
13633 void
13634 remote_target::trace_stop ()
13636 struct remote_state *rs = get_remote_state ();
13638 putpkt ("QTStop");
13639 remote_get_noisy_reply ();
13640 if (rs->buf[0] == '\0')
13641 error (_("Target does not support this command."));
13642 if (strcmp (rs->buf.data (), "OK") != 0)
13643 error (_("Bogus reply from target: %s"), rs->buf.data ());
13647 remote_target::trace_find (enum trace_find_type type, int num,
13648 CORE_ADDR addr1, CORE_ADDR addr2,
13649 int *tpp)
13651 struct remote_state *rs = get_remote_state ();
13652 char *endbuf = rs->buf.data () + get_remote_packet_size ();
13653 char *p, *reply;
13654 int target_frameno = -1, target_tracept = -1;
13656 /* Lookups other than by absolute frame number depend on the current
13657 trace selected, so make sure it is correct on the remote end
13658 first. */
13659 if (type != tfind_number)
13660 set_remote_traceframe ();
13662 p = rs->buf.data ();
13663 strcpy (p, "QTFrame:");
13664 p = strchr (p, '\0');
13665 switch (type)
13667 case tfind_number:
13668 xsnprintf (p, endbuf - p, "%x", num);
13669 break;
13670 case tfind_pc:
13671 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
13672 break;
13673 case tfind_tp:
13674 xsnprintf (p, endbuf - p, "tdp:%x", num);
13675 break;
13676 case tfind_range:
13677 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
13678 phex_nz (addr2, 0));
13679 break;
13680 case tfind_outside:
13681 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
13682 phex_nz (addr2, 0));
13683 break;
13684 default:
13685 error (_("Unknown trace find type %d"), type);
13688 putpkt (rs->buf);
13689 reply = remote_get_noisy_reply ();
13690 if (*reply == '\0')
13691 error (_("Target does not support this command."));
13693 while (reply && *reply)
13694 switch (*reply)
13696 case 'F':
13697 p = ++reply;
13698 target_frameno = (int) strtol (p, &reply, 16);
13699 if (reply == p)
13700 error (_("Unable to parse trace frame number"));
13701 /* Don't update our remote traceframe number cache on failure
13702 to select a remote traceframe. */
13703 if (target_frameno == -1)
13704 return -1;
13705 break;
13706 case 'T':
13707 p = ++reply;
13708 target_tracept = (int) strtol (p, &reply, 16);
13709 if (reply == p)
13710 error (_("Unable to parse tracepoint number"));
13711 break;
13712 case 'O': /* "OK"? */
13713 if (reply[1] == 'K' && reply[2] == '\0')
13714 reply += 2;
13715 else
13716 error (_("Bogus reply from target: %s"), reply);
13717 break;
13718 default:
13719 error (_("Bogus reply from target: %s"), reply);
13721 if (tpp)
13722 *tpp = target_tracept;
13724 rs->remote_traceframe_number = target_frameno;
13725 return target_frameno;
13728 bool
13729 remote_target::get_trace_state_variable_value (int tsvnum, LONGEST *val)
13731 struct remote_state *rs = get_remote_state ();
13732 char *reply;
13733 ULONGEST uval;
13735 set_remote_traceframe ();
13737 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTV:%x", tsvnum);
13738 putpkt (rs->buf);
13739 reply = remote_get_noisy_reply ();
13740 if (reply && *reply)
13742 if (*reply == 'V')
13744 unpack_varlen_hex (reply + 1, &uval);
13745 *val = (LONGEST) uval;
13746 return true;
13749 return false;
13753 remote_target::save_trace_data (const char *filename)
13755 struct remote_state *rs = get_remote_state ();
13756 char *p, *reply;
13758 p = rs->buf.data ();
13759 strcpy (p, "QTSave:");
13760 p += strlen (p);
13761 if ((p - rs->buf.data ()) + strlen (filename) * 2
13762 >= get_remote_packet_size ())
13763 error (_("Remote file name too long for trace save packet"));
13764 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
13765 *p++ = '\0';
13766 putpkt (rs->buf);
13767 reply = remote_get_noisy_reply ();
13768 if (*reply == '\0')
13769 error (_("Target does not support this command."));
13770 if (strcmp (reply, "OK") != 0)
13771 error (_("Bogus reply from target: %s"), reply);
13772 return 0;
13775 /* This is basically a memory transfer, but needs to be its own packet
13776 because we don't know how the target actually organizes its trace
13777 memory, plus we want to be able to ask for as much as possible, but
13778 not be unhappy if we don't get as much as we ask for. */
13780 LONGEST
13781 remote_target::get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
13783 struct remote_state *rs = get_remote_state ();
13784 char *reply;
13785 char *p;
13786 int rslt;
13788 p = rs->buf.data ();
13789 strcpy (p, "qTBuffer:");
13790 p += strlen (p);
13791 p += hexnumstr (p, offset);
13792 *p++ = ',';
13793 p += hexnumstr (p, len);
13794 *p++ = '\0';
13796 putpkt (rs->buf);
13797 reply = remote_get_noisy_reply ();
13798 if (reply && *reply)
13800 /* 'l' by itself means we're at the end of the buffer and
13801 there is nothing more to get. */
13802 if (*reply == 'l')
13803 return 0;
13805 /* Convert the reply into binary. Limit the number of bytes to
13806 convert according to our passed-in buffer size, rather than
13807 what was returned in the packet; if the target is
13808 unexpectedly generous and gives us a bigger reply than we
13809 asked for, we don't want to crash. */
13810 rslt = hex2bin (reply, buf, len);
13811 return rslt;
13814 /* Something went wrong, flag as an error. */
13815 return -1;
13818 void
13819 remote_target::set_disconnected_tracing (int val)
13821 struct remote_state *rs = get_remote_state ();
13823 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
13825 char *reply;
13827 xsnprintf (rs->buf.data (), get_remote_packet_size (),
13828 "QTDisconnected:%x", val);
13829 putpkt (rs->buf);
13830 reply = remote_get_noisy_reply ();
13831 if (*reply == '\0')
13832 error (_("Target does not support this command."));
13833 if (strcmp (reply, "OK") != 0)
13834 error (_("Bogus reply from target: %s"), reply);
13836 else if (val)
13837 warning (_("Target does not support disconnected tracing."));
13841 remote_target::core_of_thread (ptid_t ptid)
13843 thread_info *info = find_thread_ptid (this, ptid);
13845 if (info != NULL && info->priv != NULL)
13846 return get_remote_thread_info (info)->core;
13848 return -1;
13851 void
13852 remote_target::set_circular_trace_buffer (int val)
13854 struct remote_state *rs = get_remote_state ();
13855 char *reply;
13857 xsnprintf (rs->buf.data (), get_remote_packet_size (),
13858 "QTBuffer:circular:%x", val);
13859 putpkt (rs->buf);
13860 reply = remote_get_noisy_reply ();
13861 if (*reply == '\0')
13862 error (_("Target does not support this command."));
13863 if (strcmp (reply, "OK") != 0)
13864 error (_("Bogus reply from target: %s"), reply);
13867 traceframe_info_up
13868 remote_target::traceframe_info ()
13870 gdb::optional<gdb::char_vector> text
13871 = target_read_stralloc (current_inferior ()->top_target (),
13872 TARGET_OBJECT_TRACEFRAME_INFO,
13873 NULL);
13874 if (text)
13875 return parse_traceframe_info (text->data ());
13877 return NULL;
13880 /* Handle the qTMinFTPILen packet. Returns the minimum length of
13881 instruction on which a fast tracepoint may be placed. Returns -1
13882 if the packet is not supported, and 0 if the minimum instruction
13883 length is unknown. */
13886 remote_target::get_min_fast_tracepoint_insn_len ()
13888 struct remote_state *rs = get_remote_state ();
13889 char *reply;
13891 /* If we're not debugging a process yet, the IPA can't be
13892 loaded. */
13893 if (!target_has_execution ())
13894 return 0;
13896 /* Make sure the remote is pointing at the right process. */
13897 set_general_process ();
13899 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTMinFTPILen");
13900 putpkt (rs->buf);
13901 reply = remote_get_noisy_reply ();
13902 if (*reply == '\0')
13903 return -1;
13904 else
13906 ULONGEST min_insn_len;
13908 unpack_varlen_hex (reply, &min_insn_len);
13910 return (int) min_insn_len;
13914 void
13915 remote_target::set_trace_buffer_size (LONGEST val)
13917 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
13919 struct remote_state *rs = get_remote_state ();
13920 char *buf = rs->buf.data ();
13921 char *endbuf = buf + get_remote_packet_size ();
13922 enum packet_result result;
13924 gdb_assert (val >= 0 || val == -1);
13925 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
13926 /* Send -1 as literal "-1" to avoid host size dependency. */
13927 if (val < 0)
13929 *buf++ = '-';
13930 buf += hexnumstr (buf, (ULONGEST) -val);
13932 else
13933 buf += hexnumstr (buf, (ULONGEST) val);
13935 putpkt (rs->buf);
13936 remote_get_noisy_reply ();
13937 result = packet_ok (rs->buf,
13938 &remote_protocol_packets[PACKET_QTBuffer_size]);
13940 if (result != PACKET_OK)
13941 warning (_("Bogus reply from target: %s"), rs->buf.data ());
13945 bool
13946 remote_target::set_trace_notes (const char *user, const char *notes,
13947 const char *stop_notes)
13949 struct remote_state *rs = get_remote_state ();
13950 char *reply;
13951 char *buf = rs->buf.data ();
13952 char *endbuf = buf + get_remote_packet_size ();
13953 int nbytes;
13955 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
13956 if (user)
13958 buf += xsnprintf (buf, endbuf - buf, "user:");
13959 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
13960 buf += 2 * nbytes;
13961 *buf++ = ';';
13963 if (notes)
13965 buf += xsnprintf (buf, endbuf - buf, "notes:");
13966 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
13967 buf += 2 * nbytes;
13968 *buf++ = ';';
13970 if (stop_notes)
13972 buf += xsnprintf (buf, endbuf - buf, "tstop:");
13973 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
13974 buf += 2 * nbytes;
13975 *buf++ = ';';
13977 /* Ensure the buffer is terminated. */
13978 *buf = '\0';
13980 putpkt (rs->buf);
13981 reply = remote_get_noisy_reply ();
13982 if (*reply == '\0')
13983 return false;
13985 if (strcmp (reply, "OK") != 0)
13986 error (_("Bogus reply from target: %s"), reply);
13988 return true;
13991 bool
13992 remote_target::use_agent (bool use)
13994 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
13996 struct remote_state *rs = get_remote_state ();
13998 /* If the stub supports QAgent. */
13999 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAgent:%d", use);
14000 putpkt (rs->buf);
14001 getpkt (&rs->buf, 0);
14003 if (strcmp (rs->buf.data (), "OK") == 0)
14005 ::use_agent = use;
14006 return true;
14010 return false;
14013 bool
14014 remote_target::can_use_agent ()
14016 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
14019 struct btrace_target_info
14021 /* The ptid of the traced thread. */
14022 ptid_t ptid;
14024 /* The obtained branch trace configuration. */
14025 struct btrace_config conf;
14028 /* Reset our idea of our target's btrace configuration. */
14030 static void
14031 remote_btrace_reset (remote_state *rs)
14033 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
14036 /* Synchronize the configuration with the target. */
14038 void
14039 remote_target::btrace_sync_conf (const btrace_config *conf)
14041 struct packet_config *packet;
14042 struct remote_state *rs;
14043 char *buf, *pos, *endbuf;
14045 rs = get_remote_state ();
14046 buf = rs->buf.data ();
14047 endbuf = buf + get_remote_packet_size ();
14049 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
14050 if (packet_config_support (packet) == PACKET_ENABLE
14051 && conf->bts.size != rs->btrace_config.bts.size)
14053 pos = buf;
14054 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
14055 conf->bts.size);
14057 putpkt (buf);
14058 getpkt (&rs->buf, 0);
14060 if (packet_ok (buf, packet) == PACKET_ERROR)
14062 if (buf[0] == 'E' && buf[1] == '.')
14063 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
14064 else
14065 error (_("Failed to configure the BTS buffer size."));
14068 rs->btrace_config.bts.size = conf->bts.size;
14071 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
14072 if (packet_config_support (packet) == PACKET_ENABLE
14073 && conf->pt.size != rs->btrace_config.pt.size)
14075 pos = buf;
14076 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
14077 conf->pt.size);
14079 putpkt (buf);
14080 getpkt (&rs->buf, 0);
14082 if (packet_ok (buf, packet) == PACKET_ERROR)
14084 if (buf[0] == 'E' && buf[1] == '.')
14085 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
14086 else
14087 error (_("Failed to configure the trace buffer size."));
14090 rs->btrace_config.pt.size = conf->pt.size;
14094 /* Read TP's btrace configuration from the target and store it into CONF. */
14096 static void
14097 btrace_read_config (thread_info *tp, struct btrace_config *conf)
14099 /* target_read_stralloc relies on INFERIOR_PTID. */
14100 scoped_restore_current_thread restore_thread;
14101 switch_to_thread (tp);
14103 gdb::optional<gdb::char_vector> xml
14104 = target_read_stralloc (current_inferior ()->top_target (),
14105 TARGET_OBJECT_BTRACE_CONF, "");
14106 if (xml)
14107 parse_xml_btrace_conf (conf, xml->data ());
14110 /* Maybe reopen target btrace. */
14112 void
14113 remote_target::remote_btrace_maybe_reopen ()
14115 struct remote_state *rs = get_remote_state ();
14116 int btrace_target_pushed = 0;
14117 #if !defined (HAVE_LIBIPT)
14118 int warned = 0;
14119 #endif
14121 /* Don't bother walking the entirety of the remote thread list when
14122 we know the feature isn't supported by the remote. */
14123 if (packet_support (PACKET_qXfer_btrace_conf) != PACKET_ENABLE)
14124 return;
14126 for (thread_info *tp : all_non_exited_threads (this))
14128 memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
14129 btrace_read_config (tp, &rs->btrace_config);
14131 if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
14132 continue;
14134 #if !defined (HAVE_LIBIPT)
14135 if (rs->btrace_config.format == BTRACE_FORMAT_PT)
14137 if (!warned)
14139 warned = 1;
14140 warning (_("Target is recording using Intel Processor Trace "
14141 "but support was disabled at compile time."));
14144 continue;
14146 #endif /* !defined (HAVE_LIBIPT) */
14148 /* Push target, once, but before anything else happens. This way our
14149 changes to the threads will be cleaned up by unpushing the target
14150 in case btrace_read_config () throws. */
14151 if (!btrace_target_pushed)
14153 btrace_target_pushed = 1;
14154 record_btrace_push_target ();
14155 gdb_printf (_("Target is recording using %s.\n"),
14156 btrace_format_string (rs->btrace_config.format));
14159 tp->btrace.target = XCNEW (struct btrace_target_info);
14160 tp->btrace.target->ptid = tp->ptid;
14161 tp->btrace.target->conf = rs->btrace_config;
14165 /* Enable branch tracing. */
14167 struct btrace_target_info *
14168 remote_target::enable_btrace (thread_info *tp,
14169 const struct btrace_config *conf)
14171 struct btrace_target_info *tinfo = NULL;
14172 struct packet_config *packet = NULL;
14173 struct remote_state *rs = get_remote_state ();
14174 char *buf = rs->buf.data ();
14175 char *endbuf = buf + get_remote_packet_size ();
14177 switch (conf->format)
14179 case BTRACE_FORMAT_BTS:
14180 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
14181 break;
14183 case BTRACE_FORMAT_PT:
14184 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
14185 break;
14188 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
14189 error (_("Target does not support branch tracing."));
14191 btrace_sync_conf (conf);
14193 ptid_t ptid = tp->ptid;
14194 set_general_thread (ptid);
14196 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
14197 putpkt (rs->buf);
14198 getpkt (&rs->buf, 0);
14200 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
14202 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
14203 error (_("Could not enable branch tracing for %s: %s"),
14204 target_pid_to_str (ptid).c_str (), &rs->buf[2]);
14205 else
14206 error (_("Could not enable branch tracing for %s."),
14207 target_pid_to_str (ptid).c_str ());
14210 tinfo = XCNEW (struct btrace_target_info);
14211 tinfo->ptid = ptid;
14213 /* If we fail to read the configuration, we lose some information, but the
14214 tracing itself is not impacted. */
14217 btrace_read_config (tp, &tinfo->conf);
14219 catch (const gdb_exception_error &err)
14221 if (err.message != NULL)
14222 warning ("%s", err.what ());
14225 return tinfo;
14228 /* Disable branch tracing. */
14230 void
14231 remote_target::disable_btrace (struct btrace_target_info *tinfo)
14233 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
14234 struct remote_state *rs = get_remote_state ();
14235 char *buf = rs->buf.data ();
14236 char *endbuf = buf + get_remote_packet_size ();
14238 if (packet_config_support (packet) != PACKET_ENABLE)
14239 error (_("Target does not support branch tracing."));
14241 set_general_thread (tinfo->ptid);
14243 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
14244 putpkt (rs->buf);
14245 getpkt (&rs->buf, 0);
14247 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
14249 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
14250 error (_("Could not disable branch tracing for %s: %s"),
14251 target_pid_to_str (tinfo->ptid).c_str (), &rs->buf[2]);
14252 else
14253 error (_("Could not disable branch tracing for %s."),
14254 target_pid_to_str (tinfo->ptid).c_str ());
14257 xfree (tinfo);
14260 /* Teardown branch tracing. */
14262 void
14263 remote_target::teardown_btrace (struct btrace_target_info *tinfo)
14265 /* We must not talk to the target during teardown. */
14266 xfree (tinfo);
14269 /* Read the branch trace. */
14271 enum btrace_error
14272 remote_target::read_btrace (struct btrace_data *btrace,
14273 struct btrace_target_info *tinfo,
14274 enum btrace_read_type type)
14276 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
14277 const char *annex;
14279 if (packet_config_support (packet) != PACKET_ENABLE)
14280 error (_("Target does not support branch tracing."));
14282 #if !defined(HAVE_LIBEXPAT)
14283 error (_("Cannot process branch tracing result. XML parsing not supported."));
14284 #endif
14286 switch (type)
14288 case BTRACE_READ_ALL:
14289 annex = "all";
14290 break;
14291 case BTRACE_READ_NEW:
14292 annex = "new";
14293 break;
14294 case BTRACE_READ_DELTA:
14295 annex = "delta";
14296 break;
14297 default:
14298 internal_error (__FILE__, __LINE__,
14299 _("Bad branch tracing read type: %u."),
14300 (unsigned int) type);
14303 gdb::optional<gdb::char_vector> xml
14304 = target_read_stralloc (current_inferior ()->top_target (),
14305 TARGET_OBJECT_BTRACE, annex);
14306 if (!xml)
14307 return BTRACE_ERR_UNKNOWN;
14309 parse_xml_btrace (btrace, xml->data ());
14311 return BTRACE_ERR_NONE;
14314 const struct btrace_config *
14315 remote_target::btrace_conf (const struct btrace_target_info *tinfo)
14317 return &tinfo->conf;
14320 bool
14321 remote_target::augmented_libraries_svr4_read ()
14323 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
14324 == PACKET_ENABLE);
14327 /* Implementation of to_load. */
14329 void
14330 remote_target::load (const char *name, int from_tty)
14332 generic_load (name, from_tty);
14335 /* Accepts an integer PID; returns a string representing a file that
14336 can be opened on the remote side to get the symbols for the child
14337 process. Returns NULL if the operation is not supported. */
14339 char *
14340 remote_target::pid_to_exec_file (int pid)
14342 static gdb::optional<gdb::char_vector> filename;
14343 char *annex = NULL;
14345 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
14346 return NULL;
14348 inferior *inf = find_inferior_pid (this, pid);
14349 if (inf == NULL)
14350 internal_error (__FILE__, __LINE__,
14351 _("not currently attached to process %d"), pid);
14353 if (!inf->fake_pid_p)
14355 const int annex_size = 9;
14357 annex = (char *) alloca (annex_size);
14358 xsnprintf (annex, annex_size, "%x", pid);
14361 filename = target_read_stralloc (current_inferior ()->top_target (),
14362 TARGET_OBJECT_EXEC_FILE, annex);
14364 return filename ? filename->data () : nullptr;
14367 /* Implement the to_can_do_single_step target_ops method. */
14370 remote_target::can_do_single_step ()
14372 /* We can only tell whether target supports single step or not by
14373 supported s and S vCont actions if the stub supports vContSupported
14374 feature. If the stub doesn't support vContSupported feature,
14375 we have conservatively to think target doesn't supports single
14376 step. */
14377 if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
14379 struct remote_state *rs = get_remote_state ();
14381 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
14382 remote_vcont_probe ();
14384 return rs->supports_vCont.s && rs->supports_vCont.S;
14386 else
14387 return 0;
14390 /* Implementation of the to_execution_direction method for the remote
14391 target. */
14393 enum exec_direction_kind
14394 remote_target::execution_direction ()
14396 struct remote_state *rs = get_remote_state ();
14398 return rs->last_resume_exec_dir;
14401 /* Return pointer to the thread_info struct which corresponds to
14402 THREAD_HANDLE (having length HANDLE_LEN). */
14404 thread_info *
14405 remote_target::thread_handle_to_thread_info (const gdb_byte *thread_handle,
14406 int handle_len,
14407 inferior *inf)
14409 for (thread_info *tp : all_non_exited_threads (this))
14411 remote_thread_info *priv = get_remote_thread_info (tp);
14413 if (tp->inf == inf && priv != NULL)
14415 if (handle_len != priv->thread_handle.size ())
14416 error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
14417 handle_len, priv->thread_handle.size ());
14418 if (memcmp (thread_handle, priv->thread_handle.data (),
14419 handle_len) == 0)
14420 return tp;
14424 return NULL;
14427 gdb::byte_vector
14428 remote_target::thread_info_to_thread_handle (struct thread_info *tp)
14430 remote_thread_info *priv = get_remote_thread_info (tp);
14431 return priv->thread_handle;
14434 bool
14435 remote_target::can_async_p ()
14437 /* This flag should be checked in the common target.c code. */
14438 gdb_assert (target_async_permitted);
14440 /* We're async whenever the serial device can. */
14441 struct remote_state *rs = get_remote_state ();
14442 return serial_can_async_p (rs->remote_desc);
14445 bool
14446 remote_target::is_async_p ()
14448 /* We're async whenever the serial device is. */
14449 struct remote_state *rs = get_remote_state ();
14450 return serial_is_async_p (rs->remote_desc);
14453 /* Pass the SERIAL event on and up to the client. One day this code
14454 will be able to delay notifying the client of an event until the
14455 point where an entire packet has been received. */
14457 static serial_event_ftype remote_async_serial_handler;
14459 static void
14460 remote_async_serial_handler (struct serial *scb, void *context)
14462 /* Don't propogate error information up to the client. Instead let
14463 the client find out about the error by querying the target. */
14464 inferior_event_handler (INF_REG_EVENT);
14467 static void
14468 remote_async_inferior_event_handler (gdb_client_data data)
14470 inferior_event_handler (INF_REG_EVENT);
14474 remote_target::async_wait_fd ()
14476 struct remote_state *rs = get_remote_state ();
14477 return rs->remote_desc->fd;
14480 void
14481 remote_target::async (int enable)
14483 struct remote_state *rs = get_remote_state ();
14485 if (enable)
14487 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
14489 /* If there are pending events in the stop reply queue tell the
14490 event loop to process them. */
14491 if (!rs->stop_reply_queue.empty ())
14492 mark_async_event_handler (rs->remote_async_inferior_event_token);
14493 /* For simplicity, below we clear the pending events token
14494 without remembering whether it is marked, so here we always
14495 mark it. If there's actually no pending notification to
14496 process, this ends up being a no-op (other than a spurious
14497 event-loop wakeup). */
14498 if (target_is_non_stop_p ())
14499 mark_async_event_handler (rs->notif_state->get_pending_events_token);
14501 else
14503 serial_async (rs->remote_desc, NULL, NULL);
14504 /* If the core is disabling async, it doesn't want to be
14505 disturbed with target events. Clear all async event sources
14506 too. */
14507 clear_async_event_handler (rs->remote_async_inferior_event_token);
14508 if (target_is_non_stop_p ())
14509 clear_async_event_handler (rs->notif_state->get_pending_events_token);
14513 /* Implementation of the to_thread_events method. */
14515 void
14516 remote_target::thread_events (int enable)
14518 struct remote_state *rs = get_remote_state ();
14519 size_t size = get_remote_packet_size ();
14521 if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
14522 return;
14524 xsnprintf (rs->buf.data (), size, "QThreadEvents:%x", enable ? 1 : 0);
14525 putpkt (rs->buf);
14526 getpkt (&rs->buf, 0);
14528 switch (packet_ok (rs->buf,
14529 &remote_protocol_packets[PACKET_QThreadEvents]))
14531 case PACKET_OK:
14532 if (strcmp (rs->buf.data (), "OK") != 0)
14533 error (_("Remote refused setting thread events: %s"), rs->buf.data ());
14534 break;
14535 case PACKET_ERROR:
14536 warning (_("Remote failure reply: %s"), rs->buf.data ());
14537 break;
14538 case PACKET_UNKNOWN:
14539 break;
14543 static void
14544 show_remote_cmd (const char *args, int from_tty)
14546 /* We can't just use cmd_show_list here, because we want to skip
14547 the redundant "show remote Z-packet" and the legacy aliases. */
14548 struct cmd_list_element *list = remote_show_cmdlist;
14549 struct ui_out *uiout = current_uiout;
14551 ui_out_emit_tuple tuple_emitter (uiout, "showlist");
14552 for (; list != NULL; list = list->next)
14553 if (strcmp (list->name, "Z-packet") == 0)
14554 continue;
14555 else if (list->type == not_set_cmd)
14556 /* Alias commands are exactly like the original, except they
14557 don't have the normal type. */
14558 continue;
14559 else
14561 ui_out_emit_tuple option_emitter (uiout, "option");
14563 uiout->field_string ("name", list->name);
14564 uiout->text (": ");
14565 if (list->type == show_cmd)
14566 do_show_command (NULL, from_tty, list);
14567 else
14568 cmd_func (list, NULL, from_tty);
14573 /* Function to be called whenever a new objfile (shlib) is detected. */
14574 static void
14575 remote_new_objfile (struct objfile *objfile)
14577 remote_target *remote = get_current_remote_target ();
14579 /* First, check whether the current inferior's process target is a remote
14580 target. */
14581 if (remote == nullptr)
14582 return;
14584 /* When we are attaching or handling a fork child and the shared library
14585 subsystem reads the list of loaded libraries, we receive new objfile
14586 events in between each found library. The libraries are read in an
14587 undefined order, so if we gave the remote side a chance to look up
14588 symbols between each objfile, we might give it an inconsistent picture
14589 of the inferior. It could appear that a library A appears loaded but
14590 a library B does not, even though library A requires library B. That
14591 would present a state that couldn't normally exist in the inferior.
14593 So, skip these events, we'll give the remote a chance to look up symbols
14594 once all the loaded libraries and their symbols are known to GDB. */
14595 if (current_inferior ()->in_initial_library_scan)
14596 return;
14598 remote->remote_check_symbols ();
14601 /* Pull all the tracepoints defined on the target and create local
14602 data structures representing them. We don't want to create real
14603 tracepoints yet, we don't want to mess up the user's existing
14604 collection. */
14607 remote_target::upload_tracepoints (struct uploaded_tp **utpp)
14609 struct remote_state *rs = get_remote_state ();
14610 char *p;
14612 /* Ask for a first packet of tracepoint definition. */
14613 putpkt ("qTfP");
14614 getpkt (&rs->buf, 0);
14615 p = rs->buf.data ();
14616 while (*p && *p != 'l')
14618 parse_tracepoint_definition (p, utpp);
14619 /* Ask for another packet of tracepoint definition. */
14620 putpkt ("qTsP");
14621 getpkt (&rs->buf, 0);
14622 p = rs->buf.data ();
14624 return 0;
14628 remote_target::upload_trace_state_variables (struct uploaded_tsv **utsvp)
14630 struct remote_state *rs = get_remote_state ();
14631 char *p;
14633 /* Ask for a first packet of variable definition. */
14634 putpkt ("qTfV");
14635 getpkt (&rs->buf, 0);
14636 p = rs->buf.data ();
14637 while (*p && *p != 'l')
14639 parse_tsv_definition (p, utsvp);
14640 /* Ask for another packet of variable definition. */
14641 putpkt ("qTsV");
14642 getpkt (&rs->buf, 0);
14643 p = rs->buf.data ();
14645 return 0;
14648 /* The "set/show range-stepping" show hook. */
14650 static void
14651 show_range_stepping (struct ui_file *file, int from_tty,
14652 struct cmd_list_element *c,
14653 const char *value)
14655 gdb_printf (file,
14656 _("Debugger's willingness to use range stepping "
14657 "is %s.\n"), value);
14660 /* Return true if the vCont;r action is supported by the remote
14661 stub. */
14663 bool
14664 remote_target::vcont_r_supported ()
14666 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
14667 remote_vcont_probe ();
14669 return (packet_support (PACKET_vCont) == PACKET_ENABLE
14670 && get_remote_state ()->supports_vCont.r);
14673 /* The "set/show range-stepping" set hook. */
14675 static void
14676 set_range_stepping (const char *ignore_args, int from_tty,
14677 struct cmd_list_element *c)
14679 /* When enabling, check whether range stepping is actually supported
14680 by the target, and warn if not. */
14681 if (use_range_stepping)
14683 remote_target *remote = get_current_remote_target ();
14684 if (remote == NULL
14685 || !remote->vcont_r_supported ())
14686 warning (_("Range stepping is not supported by the current target"));
14690 static void
14691 show_remote_debug (struct ui_file *file, int from_tty,
14692 struct cmd_list_element *c, const char *value)
14694 gdb_printf (file, _("Debugging of remote protocol is %s.\n"),
14695 value);
14698 static void
14699 show_remote_timeout (struct ui_file *file, int from_tty,
14700 struct cmd_list_element *c, const char *value)
14702 gdb_printf (file,
14703 _("Timeout limit to wait for target to respond is %s.\n"),
14704 value);
14707 /* Implement the "supports_memory_tagging" target_ops method. */
14709 bool
14710 remote_target::supports_memory_tagging ()
14712 return remote_memory_tagging_p ();
14715 /* Create the qMemTags packet given ADDRESS, LEN and TYPE. */
14717 static void
14718 create_fetch_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
14719 size_t len, int type)
14721 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
14723 std::string request = string_printf ("qMemTags:%s,%s:%s",
14724 phex_nz (address, addr_size),
14725 phex_nz (len, sizeof (len)),
14726 phex_nz (type, sizeof (type)));
14728 strcpy (packet.data (), request.c_str ());
14731 /* Parse the qMemTags packet reply into TAGS.
14733 Return true if successful, false otherwise. */
14735 static bool
14736 parse_fetch_memtags_reply (const gdb::char_vector &reply,
14737 gdb::byte_vector &tags)
14739 if (reply.empty () || reply[0] == 'E' || reply[0] != 'm')
14740 return false;
14742 /* Copy the tag data. */
14743 tags = hex2bin (reply.data () + 1);
14745 return true;
14748 /* Create the QMemTags packet given ADDRESS, LEN, TYPE and TAGS. */
14750 static void
14751 create_store_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
14752 size_t len, int type,
14753 const gdb::byte_vector &tags)
14755 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
14757 /* Put together the main packet, address and length. */
14758 std::string request = string_printf ("QMemTags:%s,%s:%s:",
14759 phex_nz (address, addr_size),
14760 phex_nz (len, sizeof (len)),
14761 phex_nz (type, sizeof (type)));
14762 request += bin2hex (tags.data (), tags.size ());
14764 /* Check if we have exceeded the maximum packet size. */
14765 if (packet.size () < request.length ())
14766 error (_("Contents too big for packet QMemTags."));
14768 strcpy (packet.data (), request.c_str ());
14771 /* Implement the "fetch_memtags" target_ops method. */
14773 bool
14774 remote_target::fetch_memtags (CORE_ADDR address, size_t len,
14775 gdb::byte_vector &tags, int type)
14777 /* Make sure the qMemTags packet is supported. */
14778 if (!remote_memory_tagging_p ())
14779 gdb_assert_not_reached ("remote fetch_memtags called with packet disabled");
14781 struct remote_state *rs = get_remote_state ();
14783 create_fetch_memtags_request (rs->buf, address, len, type);
14785 putpkt (rs->buf);
14786 getpkt (&rs->buf, 0);
14788 return parse_fetch_memtags_reply (rs->buf, tags);
14791 /* Implement the "store_memtags" target_ops method. */
14793 bool
14794 remote_target::store_memtags (CORE_ADDR address, size_t len,
14795 const gdb::byte_vector &tags, int type)
14797 /* Make sure the QMemTags packet is supported. */
14798 if (!remote_memory_tagging_p ())
14799 gdb_assert_not_reached ("remote store_memtags called with packet disabled");
14801 struct remote_state *rs = get_remote_state ();
14803 create_store_memtags_request (rs->buf, address, len, type, tags);
14805 putpkt (rs->buf);
14806 getpkt (&rs->buf, 0);
14808 /* Verify if the request was successful. */
14809 return packet_check_result (rs->buf.data ()) == PACKET_OK;
14812 /* Return true if remote target T is non-stop. */
14814 bool
14815 remote_target_is_non_stop_p (remote_target *t)
14817 scoped_restore_current_thread restore_thread;
14818 switch_to_target_no_thread (t);
14820 return target_is_non_stop_p ();
14823 #if GDB_SELF_TEST
14825 namespace selftests {
14827 static void
14828 test_memory_tagging_functions ()
14830 remote_target remote;
14832 struct packet_config *config
14833 = &remote_protocol_packets[PACKET_memory_tagging_feature];
14835 scoped_restore restore_memtag_support_
14836 = make_scoped_restore (&config->support);
14838 /* Test memory tagging packet support. */
14839 config->support = PACKET_SUPPORT_UNKNOWN;
14840 SELF_CHECK (remote.supports_memory_tagging () == false);
14841 config->support = PACKET_DISABLE;
14842 SELF_CHECK (remote.supports_memory_tagging () == false);
14843 config->support = PACKET_ENABLE;
14844 SELF_CHECK (remote.supports_memory_tagging () == true);
14846 /* Setup testing. */
14847 gdb::char_vector packet;
14848 gdb::byte_vector tags, bv;
14849 std::string expected, reply;
14850 packet.resize (32000);
14852 /* Test creating a qMemTags request. */
14854 expected = "qMemTags:0,0:0";
14855 create_fetch_memtags_request (packet, 0x0, 0x0, 0);
14856 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
14858 expected = "qMemTags:deadbeef,10:1";
14859 create_fetch_memtags_request (packet, 0xdeadbeef, 16, 1);
14860 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
14862 /* Test parsing a qMemTags reply. */
14864 /* Error reply, tags vector unmodified. */
14865 reply = "E00";
14866 strcpy (packet.data (), reply.c_str ());
14867 tags.resize (0);
14868 SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == false);
14869 SELF_CHECK (tags.size () == 0);
14871 /* Valid reply, tags vector updated. */
14872 tags.resize (0);
14873 bv.resize (0);
14875 for (int i = 0; i < 5; i++)
14876 bv.push_back (i);
14878 reply = "m" + bin2hex (bv.data (), bv.size ());
14879 strcpy (packet.data (), reply.c_str ());
14881 SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == true);
14882 SELF_CHECK (tags.size () == 5);
14884 for (int i = 0; i < 5; i++)
14885 SELF_CHECK (tags[i] == i);
14887 /* Test creating a QMemTags request. */
14889 /* Empty tag data. */
14890 tags.resize (0);
14891 expected = "QMemTags:0,0:0:";
14892 create_store_memtags_request (packet, 0x0, 0x0, 0, tags);
14893 SELF_CHECK (memcmp (packet.data (), expected.c_str (),
14894 expected.length ()) == 0);
14896 /* Non-empty tag data. */
14897 tags.resize (0);
14898 for (int i = 0; i < 5; i++)
14899 tags.push_back (i);
14900 expected = "QMemTags:deadbeef,ff:1:0001020304";
14901 create_store_memtags_request (packet, 0xdeadbeef, 255, 1, tags);
14902 SELF_CHECK (memcmp (packet.data (), expected.c_str (),
14903 expected.length ()) == 0);
14906 } // namespace selftests
14907 #endif /* GDB_SELF_TEST */
14909 void _initialize_remote ();
14910 void
14911 _initialize_remote ()
14913 /* architecture specific data */
14914 remote_g_packet_data_handle =
14915 gdbarch_data_register_pre_init (remote_g_packet_data_init);
14917 add_target (remote_target_info, remote_target::open);
14918 add_target (extended_remote_target_info, extended_remote_target::open);
14920 /* Hook into new objfile notification. */
14921 gdb::observers::new_objfile.attach (remote_new_objfile, "remote");
14923 #if 0
14924 init_remote_threadtests ();
14925 #endif
14927 /* set/show remote ... */
14929 add_basic_prefix_cmd ("remote", class_maintenance, _("\
14930 Remote protocol specific variables.\n\
14931 Configure various remote-protocol specific variables such as\n\
14932 the packets being used."),
14933 &remote_set_cmdlist,
14934 0 /* allow-unknown */, &setlist);
14935 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
14936 Remote protocol specific variables.\n\
14937 Configure various remote-protocol specific variables such as\n\
14938 the packets being used."),
14939 &remote_show_cmdlist,
14940 0 /* allow-unknown */, &showlist);
14942 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
14943 Compare section data on target to the exec file.\n\
14944 Argument is a single section name (default: all loaded sections).\n\
14945 To compare only read-only loaded sections, specify the -r option."),
14946 &cmdlist);
14948 add_cmd ("packet", class_maintenance, cli_packet_command, _("\
14949 Send an arbitrary packet to a remote target.\n\
14950 maintenance packet TEXT\n\
14951 If GDB is talking to an inferior via the GDB serial protocol, then\n\
14952 this command sends the string TEXT to the inferior, and displays the\n\
14953 response packet. GDB supplies the initial `$' character, and the\n\
14954 terminating `#' character and checksum."),
14955 &maintenancelist);
14957 set_show_commands remotebreak_cmds
14958 = add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
14959 Set whether to send break if interrupted."), _("\
14960 Show whether to send break if interrupted."), _("\
14961 If set, a break, instead of a cntrl-c, is sent to the remote target."),
14962 set_remotebreak, show_remotebreak,
14963 &setlist, &showlist);
14964 deprecate_cmd (remotebreak_cmds.set, "set remote interrupt-sequence");
14965 deprecate_cmd (remotebreak_cmds.show, "show remote interrupt-sequence");
14967 add_setshow_enum_cmd ("interrupt-sequence", class_support,
14968 interrupt_sequence_modes, &interrupt_sequence_mode,
14969 _("\
14970 Set interrupt sequence to remote target."), _("\
14971 Show interrupt sequence to remote target."), _("\
14972 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
14973 NULL, show_interrupt_sequence,
14974 &remote_set_cmdlist,
14975 &remote_show_cmdlist);
14977 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
14978 &interrupt_on_connect, _("\
14979 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
14980 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
14981 If set, interrupt sequence is sent to remote target."),
14982 NULL, NULL,
14983 &remote_set_cmdlist, &remote_show_cmdlist);
14985 /* Install commands for configuring memory read/write packets. */
14987 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
14988 Set the maximum number of bytes per memory write packet (deprecated)."),
14989 &setlist);
14990 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
14991 Show the maximum number of bytes per memory write packet (deprecated)."),
14992 &showlist);
14993 add_cmd ("memory-write-packet-size", no_class,
14994 set_memory_write_packet_size, _("\
14995 Set the maximum number of bytes per memory-write packet.\n\
14996 Specify the number of bytes in a packet or 0 (zero) for the\n\
14997 default packet size. The actual limit is further reduced\n\
14998 dependent on the target. Specify ``fixed'' to disable the\n\
14999 further restriction and ``limit'' to enable that restriction."),
15000 &remote_set_cmdlist);
15001 add_cmd ("memory-read-packet-size", no_class,
15002 set_memory_read_packet_size, _("\
15003 Set the maximum number of bytes per memory-read packet.\n\
15004 Specify the number of bytes in a packet or 0 (zero) for the\n\
15005 default packet size. The actual limit is further reduced\n\
15006 dependent on the target. Specify ``fixed'' to disable the\n\
15007 further restriction and ``limit'' to enable that restriction."),
15008 &remote_set_cmdlist);
15009 add_cmd ("memory-write-packet-size", no_class,
15010 show_memory_write_packet_size,
15011 _("Show the maximum number of bytes per memory-write packet."),
15012 &remote_show_cmdlist);
15013 add_cmd ("memory-read-packet-size", no_class,
15014 show_memory_read_packet_size,
15015 _("Show the maximum number of bytes per memory-read packet."),
15016 &remote_show_cmdlist);
15018 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-limit", no_class,
15019 &remote_hw_watchpoint_limit, _("\
15020 Set the maximum number of target hardware watchpoints."), _("\
15021 Show the maximum number of target hardware watchpoints."), _("\
15022 Specify \"unlimited\" for unlimited hardware watchpoints."),
15023 NULL, show_hardware_watchpoint_limit,
15024 &remote_set_cmdlist,
15025 &remote_show_cmdlist);
15026 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-length-limit",
15027 no_class,
15028 &remote_hw_watchpoint_length_limit, _("\
15029 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
15030 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
15031 Specify \"unlimited\" to allow watchpoints of unlimited size."),
15032 NULL, show_hardware_watchpoint_length_limit,
15033 &remote_set_cmdlist, &remote_show_cmdlist);
15034 add_setshow_zuinteger_unlimited_cmd ("hardware-breakpoint-limit", no_class,
15035 &remote_hw_breakpoint_limit, _("\
15036 Set the maximum number of target hardware breakpoints."), _("\
15037 Show the maximum number of target hardware breakpoints."), _("\
15038 Specify \"unlimited\" for unlimited hardware breakpoints."),
15039 NULL, show_hardware_breakpoint_limit,
15040 &remote_set_cmdlist, &remote_show_cmdlist);
15042 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
15043 &remote_address_size, _("\
15044 Set the maximum size of the address (in bits) in a memory packet."), _("\
15045 Show the maximum size of the address (in bits) in a memory packet."), NULL,
15046 NULL,
15047 NULL, /* FIXME: i18n: */
15048 &setlist, &showlist);
15050 init_all_packet_configs ();
15052 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
15053 "X", "binary-download", 1);
15055 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
15056 "vCont", "verbose-resume", 0);
15058 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
15059 "QPassSignals", "pass-signals", 0);
15061 add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
15062 "QCatchSyscalls", "catch-syscalls", 0);
15064 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
15065 "QProgramSignals", "program-signals", 0);
15067 add_packet_config_cmd (&remote_protocol_packets[PACKET_QSetWorkingDir],
15068 "QSetWorkingDir", "set-working-dir", 0);
15070 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartupWithShell],
15071 "QStartupWithShell", "startup-with-shell", 0);
15073 add_packet_config_cmd (&remote_protocol_packets
15074 [PACKET_QEnvironmentHexEncoded],
15075 "QEnvironmentHexEncoded", "environment-hex-encoded",
15078 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentReset],
15079 "QEnvironmentReset", "environment-reset",
15082 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentUnset],
15083 "QEnvironmentUnset", "environment-unset",
15086 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
15087 "qSymbol", "symbol-lookup", 0);
15089 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
15090 "P", "set-register", 1);
15092 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
15093 "p", "fetch-register", 1);
15095 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
15096 "Z0", "software-breakpoint", 0);
15098 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
15099 "Z1", "hardware-breakpoint", 0);
15101 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
15102 "Z2", "write-watchpoint", 0);
15104 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
15105 "Z3", "read-watchpoint", 0);
15107 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
15108 "Z4", "access-watchpoint", 0);
15110 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
15111 "qXfer:auxv:read", "read-aux-vector", 0);
15113 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
15114 "qXfer:exec-file:read", "pid-to-exec-file", 0);
15116 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
15117 "qXfer:features:read", "target-features", 0);
15119 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
15120 "qXfer:libraries:read", "library-info", 0);
15122 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
15123 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
15125 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
15126 "qXfer:memory-map:read", "memory-map", 0);
15128 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
15129 "qXfer:osdata:read", "osdata", 0);
15131 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
15132 "qXfer:threads:read", "threads", 0);
15134 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
15135 "qXfer:siginfo:read", "read-siginfo-object", 0);
15137 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
15138 "qXfer:siginfo:write", "write-siginfo-object", 0);
15140 add_packet_config_cmd
15141 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
15142 "qXfer:traceframe-info:read", "traceframe-info", 0);
15144 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
15145 "qXfer:uib:read", "unwind-info-block", 0);
15147 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
15148 "qGetTLSAddr", "get-thread-local-storage-address",
15151 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
15152 "qGetTIBAddr", "get-thread-information-block-address",
15155 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
15156 "bc", "reverse-continue", 0);
15158 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
15159 "bs", "reverse-step", 0);
15161 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
15162 "qSupported", "supported-packets", 0);
15164 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
15165 "qSearch:memory", "search-memory", 0);
15167 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
15168 "qTStatus", "trace-status", 0);
15170 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
15171 "vFile:setfs", "hostio-setfs", 0);
15173 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
15174 "vFile:open", "hostio-open", 0);
15176 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
15177 "vFile:pread", "hostio-pread", 0);
15179 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
15180 "vFile:pwrite", "hostio-pwrite", 0);
15182 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
15183 "vFile:close", "hostio-close", 0);
15185 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
15186 "vFile:unlink", "hostio-unlink", 0);
15188 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
15189 "vFile:readlink", "hostio-readlink", 0);
15191 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
15192 "vFile:fstat", "hostio-fstat", 0);
15194 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
15195 "vAttach", "attach", 0);
15197 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
15198 "vRun", "run", 0);
15200 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
15201 "QStartNoAckMode", "noack", 0);
15203 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
15204 "vKill", "kill", 0);
15206 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
15207 "qAttached", "query-attached", 0);
15209 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
15210 "ConditionalTracepoints",
15211 "conditional-tracepoints", 0);
15213 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
15214 "ConditionalBreakpoints",
15215 "conditional-breakpoints", 0);
15217 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
15218 "BreakpointCommands",
15219 "breakpoint-commands", 0);
15221 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
15222 "FastTracepoints", "fast-tracepoints", 0);
15224 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
15225 "TracepointSource", "TracepointSource", 0);
15227 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
15228 "QAllow", "allow", 0);
15230 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
15231 "StaticTracepoints", "static-tracepoints", 0);
15233 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
15234 "InstallInTrace", "install-in-trace", 0);
15236 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
15237 "qXfer:statictrace:read", "read-sdata-object", 0);
15239 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
15240 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
15242 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
15243 "QDisableRandomization", "disable-randomization", 0);
15245 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
15246 "QAgent", "agent", 0);
15248 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
15249 "QTBuffer:size", "trace-buffer-size", 0);
15251 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
15252 "Qbtrace:off", "disable-btrace", 0);
15254 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
15255 "Qbtrace:bts", "enable-btrace-bts", 0);
15257 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
15258 "Qbtrace:pt", "enable-btrace-pt", 0);
15260 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
15261 "qXfer:btrace", "read-btrace", 0);
15263 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
15264 "qXfer:btrace-conf", "read-btrace-conf", 0);
15266 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
15267 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
15269 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
15270 "multiprocess-feature", "multiprocess-feature", 0);
15272 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
15273 "swbreak-feature", "swbreak-feature", 0);
15275 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
15276 "hwbreak-feature", "hwbreak-feature", 0);
15278 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
15279 "fork-event-feature", "fork-event-feature", 0);
15281 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
15282 "vfork-event-feature", "vfork-event-feature", 0);
15284 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
15285 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
15287 add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
15288 "vContSupported", "verbose-resume-supported", 0);
15290 add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
15291 "exec-event-feature", "exec-event-feature", 0);
15293 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
15294 "vCtrlC", "ctrl-c", 0);
15296 add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
15297 "QThreadEvents", "thread-events", 0);
15299 add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
15300 "N stop reply", "no-resumed-stop-reply", 0);
15302 add_packet_config_cmd (&remote_protocol_packets[PACKET_memory_tagging_feature],
15303 "memory-tagging-feature", "memory-tagging-feature", 0);
15305 /* Assert that we've registered "set remote foo-packet" commands
15306 for all packet configs. */
15308 int i;
15310 for (i = 0; i < PACKET_MAX; i++)
15312 /* Ideally all configs would have a command associated. Some
15313 still don't though. */
15314 int excepted;
15316 switch (i)
15318 case PACKET_QNonStop:
15319 case PACKET_EnableDisableTracepoints_feature:
15320 case PACKET_tracenz_feature:
15321 case PACKET_DisconnectedTracing_feature:
15322 case PACKET_augmented_libraries_svr4_read_feature:
15323 case PACKET_qCRC:
15324 /* Additions to this list need to be well justified:
15325 pre-existing packets are OK; new packets are not. */
15326 excepted = 1;
15327 break;
15328 default:
15329 excepted = 0;
15330 break;
15333 /* This catches both forgetting to add a config command, and
15334 forgetting to remove a packet from the exception list. */
15335 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
15339 /* Keep the old ``set remote Z-packet ...'' working. Each individual
15340 Z sub-packet has its own set and show commands, but users may
15341 have sets to this variable in their .gdbinit files (or in their
15342 documentation). */
15343 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
15344 &remote_Z_packet_detect, _("\
15345 Set use of remote protocol `Z' packets."), _("\
15346 Show use of remote protocol `Z' packets."), _("\
15347 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
15348 packets."),
15349 set_remote_protocol_Z_packet_cmd,
15350 show_remote_protocol_Z_packet_cmd,
15351 /* FIXME: i18n: Use of remote protocol
15352 `Z' packets is %s. */
15353 &remote_set_cmdlist, &remote_show_cmdlist);
15355 add_basic_prefix_cmd ("remote", class_files, _("\
15356 Manipulate files on the remote system.\n\
15357 Transfer files to and from the remote target system."),
15358 &remote_cmdlist,
15359 0 /* allow-unknown */, &cmdlist);
15361 add_cmd ("put", class_files, remote_put_command,
15362 _("Copy a local file to the remote system."),
15363 &remote_cmdlist);
15365 add_cmd ("get", class_files, remote_get_command,
15366 _("Copy a remote file to the local system."),
15367 &remote_cmdlist);
15369 add_cmd ("delete", class_files, remote_delete_command,
15370 _("Delete a remote file."),
15371 &remote_cmdlist);
15373 add_setshow_string_noescape_cmd ("exec-file", class_files,
15374 &remote_exec_file_var, _("\
15375 Set the remote pathname for \"run\"."), _("\
15376 Show the remote pathname for \"run\"."), NULL,
15377 set_remote_exec_file,
15378 show_remote_exec_file,
15379 &remote_set_cmdlist,
15380 &remote_show_cmdlist);
15382 add_setshow_boolean_cmd ("range-stepping", class_run,
15383 &use_range_stepping, _("\
15384 Enable or disable range stepping."), _("\
15385 Show whether target-assisted range stepping is enabled."), _("\
15386 If on, and the target supports it, when stepping a source line, GDB\n\
15387 tells the target to step the corresponding range of addresses itself instead\n\
15388 of issuing multiple single-steps. This speeds up source level\n\
15389 stepping. If off, GDB always issues single-steps, even if range\n\
15390 stepping is supported by the target. The default is on."),
15391 set_range_stepping,
15392 show_range_stepping,
15393 &setlist,
15394 &showlist);
15396 add_setshow_zinteger_cmd ("watchdog", class_maintenance, &watchdog, _("\
15397 Set watchdog timer."), _("\
15398 Show watchdog timer."), _("\
15399 When non-zero, this timeout is used instead of waiting forever for a target\n\
15400 to finish a low-level step or continue operation. If the specified amount\n\
15401 of time passes without a response from the target, an error occurs."),
15402 NULL,
15403 show_watchdog,
15404 &setlist, &showlist);
15406 add_setshow_zuinteger_unlimited_cmd ("remote-packet-max-chars", no_class,
15407 &remote_packet_max_chars, _("\
15408 Set the maximum number of characters to display for each remote packet."), _("\
15409 Show the maximum number of characters to display for each remote packet."), _("\
15410 Specify \"unlimited\" to display all the characters."),
15411 NULL, show_remote_packet_max_chars,
15412 &setdebuglist, &showdebuglist);
15414 add_setshow_boolean_cmd ("remote", no_class, &remote_debug,
15415 _("Set debugging of remote protocol."),
15416 _("Show debugging of remote protocol."),
15417 _("\
15418 When enabled, each packet sent or received with the remote target\n\
15419 is displayed."),
15420 NULL,
15421 show_remote_debug,
15422 &setdebuglist, &showdebuglist);
15424 add_setshow_zuinteger_unlimited_cmd ("remotetimeout", no_class,
15425 &remote_timeout, _("\
15426 Set timeout limit to wait for target to respond."), _("\
15427 Show timeout limit to wait for target to respond."), _("\
15428 This value is used to set the time limit for gdb to wait for a response\n\
15429 from the target."),
15430 NULL,
15431 show_remote_timeout,
15432 &setlist, &showlist);
15434 /* Eventually initialize fileio. See fileio.c */
15435 initialize_remote_fileio (&remote_set_cmdlist, &remote_show_cmdlist);
15437 #if GDB_SELF_TEST
15438 selftests::register_test ("remote_memory_tagging",
15439 selftests::test_memory_tagging_functions);
15440 #endif