1 /* Remote target communications for serial-line targets in custom GDB protocol
3 Copyright (C) 1988-2018 Free Software Foundation, Inc.
5 This file is part of GDB.
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
20 /* See the GDB User Guide for details of the GDB remote protocol. */
30 /*#include "terminal.h" */
33 #include "gdb-stabs.h"
34 #include "gdbthread.h"
36 #include "remote-notif.h"
39 #include "observable.h"
41 #include "cli/cli-decode.h"
42 #include "cli/cli-setshow.h"
43 #include "target-descriptions.h"
45 #include "filestuff.h"
50 #include "gdb_sys_time.h"
52 #include "event-loop.h"
53 #include "event-top.h"
59 #include "gdbcore.h" /* for exec_bfd */
61 #include "remote-fileio.h"
62 #include "gdb/fileio.h"
64 #include "xml-support.h"
66 #include "memory-map.h"
68 #include "tracepoint.h"
73 #include "record-btrace.h"
75 #include "common/scoped_restore.h"
77 #include "common/byte-vector.h"
78 #include <unordered_map>
80 /* The remote target. */
82 static const char remote_doc[] = N_("\
83 Use a remote computer via a serial line, using a gdb-specific protocol.\n\
84 Specify the serial device it is connected to\n\
85 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).");
87 #define OPAQUETHREADBYTES 8
89 /* a 64 bit opaque identifier */
90 typedef unsigned char threadref[OPAQUETHREADBYTES];
92 struct gdb_ext_thread_info;
93 struct threads_listing_context;
94 typedef int (*rmt_thread_action) (threadref *ref, void *context);
95 struct protocol_feature;
99 static void stop_reply_xfree (struct stop_reply *);
101 struct stop_reply_deleter
103 void operator() (stop_reply *r) const
105 stop_reply_xfree (r);
109 typedef std::unique_ptr<stop_reply, stop_reply_deleter> stop_reply_up;
111 /* Generic configuration support for packets the stub optionally
112 supports. Allows the user to specify the use of the packet as well
113 as allowing GDB to auto-detect support in the remote stub. */
117 PACKET_SUPPORT_UNKNOWN = 0,
122 /* Analyze a packet's return value and update the packet config
132 struct threads_listing_context;
134 /* Stub vCont actions support.
136 Each field is a boolean flag indicating whether the stub reports
137 support for the corresponding action. */
139 struct vCont_action_support
154 /* About this many threadisds fit in a packet. */
156 #define MAXTHREADLISTRESULTS 32
158 /* Data for the vFile:pread readahead cache. */
160 struct readahead_cache
162 /* Invalidate the readahead cache. */
165 /* Invalidate the readahead cache if it is holding data for FD. */
166 void invalidate_fd (int fd);
168 /* Serve pread from the readahead cache. Returns number of bytes
169 read, or 0 if the request can't be served from the cache. */
170 int pread (int fd, gdb_byte *read_buf, size_t len, ULONGEST offset);
172 /* The file descriptor for the file that is being cached. -1 if the
176 /* The offset into the file that the cache buffer corresponds
180 /* The buffer holding the cache contents. */
181 gdb_byte *buf = nullptr;
182 /* The buffer's size. We try to read as much as fits into a packet
186 /* Cache hit and miss counters. */
187 ULONGEST hit_count = 0;
188 ULONGEST miss_count = 0;
191 /* Description of the remote protocol for a given architecture. */
195 long offset; /* Offset into G packet. */
196 long regnum; /* GDB's internal register number. */
197 LONGEST pnum; /* Remote protocol register number. */
198 int in_g_packet; /* Always part of G packet. */
199 /* long size in bytes; == register_size (target_gdbarch (), regnum);
201 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
205 struct remote_arch_state
207 explicit remote_arch_state (struct gdbarch *gdbarch);
209 /* Description of the remote protocol registers. */
210 long sizeof_g_packet;
212 /* Description of the remote protocol registers indexed by REGNUM
213 (making an array gdbarch_num_regs in size). */
214 std::unique_ptr<packet_reg[]> regs;
216 /* This is the size (in chars) of the first response to the ``g''
217 packet. It is used as a heuristic when determining the maximum
218 size of memory-read and memory-write packets. A target will
219 typically only reserve a buffer large enough to hold the ``g''
220 packet. The size does not include packet overhead (headers and
222 long actual_register_packet_size;
224 /* This is the maximum size (in chars) of a non read/write packet.
225 It is also used as a cap on the size of read/write packets. */
226 long remote_packet_size;
229 /* Description of the remote protocol state for the currently
230 connected target. This is per-target state, and independent of the
231 selected architecture. */
240 /* Get the remote arch state for GDBARCH. */
241 struct remote_arch_state *get_remote_arch_state (struct gdbarch *gdbarch);
245 /* A buffer to use for incoming packets, and its current size. The
246 buffer is grown dynamically for larger incoming packets.
247 Outgoing packets may also be constructed in this buffer.
248 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
249 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
254 /* True if we're going through initial connection setup (finding out
255 about the remote side's threads, relocating symbols, etc.). */
256 bool starting_up = false;
258 /* If we negotiated packet size explicitly (and thus can bypass
259 heuristics for the largest packet size that will not overflow
260 a buffer in the stub), this will be set to that packet size.
261 Otherwise zero, meaning to use the guessed size. */
262 long explicit_packet_size = 0;
264 /* remote_wait is normally called when the target is running and
265 waits for a stop reply packet. But sometimes we need to call it
266 when the target is already stopped. We can send a "?" packet
267 and have remote_wait read the response. Or, if we already have
268 the response, we can stash it in BUF and tell remote_wait to
269 skip calling getpkt. This flag is set when BUF contains a
270 stop reply packet and the target is not waiting. */
271 int cached_wait_status = 0;
273 /* True, if in no ack mode. That is, neither GDB nor the stub will
274 expect acks from each other. The connection is assumed to be
276 bool noack_mode = false;
278 /* True if we're connected in extended remote mode. */
279 bool extended = false;
281 /* True if we resumed the target and we're waiting for the target to
282 stop. In the mean time, we can't start another command/query.
283 The remote server wouldn't be ready to process it, so we'd
284 timeout waiting for a reply that would never come and eventually
285 we'd close the connection. This can happen in asynchronous mode
286 because we allow GDB commands while the target is running. */
287 bool waiting_for_stop_reply = false;
289 /* The status of the stub support for the various vCont actions. */
290 vCont_action_support supports_vCont;
292 /* True if the user has pressed Ctrl-C, but the target hasn't
293 responded to that. */
294 bool ctrlc_pending_p = false;
296 /* True if we saw a Ctrl-C while reading or writing from/to the
297 remote descriptor. At that point it is not safe to send a remote
298 interrupt packet, so we instead remember we saw the Ctrl-C and
299 process it once we're done with sending/receiving the current
300 packet, which should be shortly. If however that takes too long,
301 and the user presses Ctrl-C again, we offer to disconnect. */
302 bool got_ctrlc_during_io = false;
304 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
305 remote_open knows that we don't have a file open when the program
307 struct serial *remote_desc = nullptr;
309 /* These are the threads which we last sent to the remote system. The
310 TID member will be -1 for all or -2 for not sent yet. */
311 ptid_t general_thread = null_ptid;
312 ptid_t continue_thread = null_ptid;
314 /* This is the traceframe which we last selected on the remote system.
315 It will be -1 if no traceframe is selected. */
316 int remote_traceframe_number = -1;
318 char *last_pass_packet = nullptr;
320 /* The last QProgramSignals packet sent to the target. We bypass
321 sending a new program signals list down to the target if the new
322 packet is exactly the same as the last we sent. IOW, we only let
323 the target know about program signals list changes. */
324 char *last_program_signals_packet = nullptr;
326 gdb_signal last_sent_signal = GDB_SIGNAL_0;
328 bool last_sent_step = false;
330 /* The execution direction of the last resume we got. */
331 exec_direction_kind last_resume_exec_dir = EXEC_FORWARD;
333 char *finished_object = nullptr;
334 char *finished_annex = nullptr;
335 ULONGEST finished_offset = 0;
337 /* Should we try the 'ThreadInfo' query packet?
339 This variable (NOT available to the user: auto-detect only!)
340 determines whether GDB will use the new, simpler "ThreadInfo"
341 query or the older, more complex syntax for thread queries.
342 This is an auto-detect variable (set to true at each connect,
343 and set to false when the target fails to recognize it). */
344 bool use_threadinfo_query = false;
345 bool use_threadextra_query = false;
347 threadref echo_nextthread {};
348 threadref nextthread {};
349 threadref resultthreadlist[MAXTHREADLISTRESULTS] {};
351 /* The state of remote notification. */
352 struct remote_notif_state *notif_state = nullptr;
354 /* The branch trace configuration. */
355 struct btrace_config btrace_config {};
357 /* The argument to the last "vFile:setfs:" packet we sent, used
358 to avoid sending repeated unnecessary "vFile:setfs:" packets.
359 Initialized to -1 to indicate that no "vFile:setfs:" packet
360 has yet been sent. */
363 /* A readahead cache for vFile:pread. Often, reading a binary
364 involves a sequence of small reads. E.g., when parsing an ELF
365 file. A readahead cache helps mostly the case of remote
366 debugging on a connection with higher latency, due to the
367 request/reply nature of the RSP. We only cache data for a single
368 file descriptor at a time. */
369 struct readahead_cache readahead_cache;
371 /* The list of already fetched and acknowledged stop events. This
372 queue is used for notification Stop, and other notifications
373 don't need queue for their events, because the notification
374 events of Stop can't be consumed immediately, so that events
375 should be queued first, and be consumed by remote_wait_{ns,as}
376 one per time. Other notifications can consume their events
377 immediately, so queue is not needed for them. */
378 std::vector<stop_reply_up> stop_reply_queue;
380 /* Asynchronous signal handle registered as event loop source for
381 when we have pending events ready to be passed to the core. */
382 struct async_event_handler *remote_async_inferior_event_token = nullptr;
384 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
385 ``forever'' still use the normal timeout mechanism. This is
386 currently used by the ASYNC code to guarentee that target reads
387 during the initial connect always time-out. Once getpkt has been
388 modified to return a timeout indication and, in turn
389 remote_wait()/wait_for_inferior() have gained a timeout parameter
391 int wait_forever_enabled_p = 1;
394 /* Mapping of remote protocol data for each gdbarch. Usually there
395 is only one entry here, though we may see more with stubs that
396 support multi-process. */
397 std::unordered_map<struct gdbarch *, remote_arch_state>
401 static const target_info remote_target_info = {
403 N_("Remote serial target in gdb-specific protocol"),
407 class remote_target : public target_ops
412 to_stratum = process_stratum;
414 ~remote_target () override;
416 const target_info &info () const override
417 { return remote_target_info; }
419 thread_control_capabilities get_thread_control_capabilities () override
420 { return tc_schedlock; }
422 /* Open a remote connection. */
423 static void open (const char *, int);
425 void close () override;
427 void detach (inferior *, int) override;
428 void disconnect (const char *, int) override;
430 void commit_resume () override;
431 void resume (ptid_t, int, enum gdb_signal) override;
432 ptid_t wait (ptid_t, struct target_waitstatus *, int) override;
434 void fetch_registers (struct regcache *, int) override;
435 void store_registers (struct regcache *, int) override;
436 void prepare_to_store (struct regcache *) override;
438 void files_info () override;
440 int insert_breakpoint (struct gdbarch *, struct bp_target_info *) override;
442 int remove_breakpoint (struct gdbarch *, struct bp_target_info *,
443 enum remove_bp_reason) override;
446 bool stopped_by_sw_breakpoint () override;
447 bool supports_stopped_by_sw_breakpoint () override;
449 bool stopped_by_hw_breakpoint () override;
451 bool supports_stopped_by_hw_breakpoint () override;
453 bool stopped_by_watchpoint () override;
455 bool stopped_data_address (CORE_ADDR *) override;
457 bool watchpoint_addr_within_range (CORE_ADDR, CORE_ADDR, int) override;
459 int can_use_hw_breakpoint (enum bptype, int, int) override;
461 int insert_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
463 int remove_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
465 int region_ok_for_hw_watchpoint (CORE_ADDR, int) override;
467 int insert_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
468 struct expression *) override;
470 int remove_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
471 struct expression *) override;
473 void kill () override;
475 void load (const char *, int) override;
477 void mourn_inferior () override;
479 void pass_signals (int, unsigned char *) override;
481 int set_syscall_catchpoint (int, bool, int,
482 gdb::array_view<const int>) override;
484 void program_signals (int, unsigned char *) override;
486 bool thread_alive (ptid_t ptid) override;
488 const char *thread_name (struct thread_info *) override;
490 void update_thread_list () override;
492 const char *pid_to_str (ptid_t) override;
494 const char *extra_thread_info (struct thread_info *) override;
496 ptid_t get_ada_task_ptid (long lwp, long thread) override;
498 thread_info *thread_handle_to_thread_info (const gdb_byte *thread_handle,
500 inferior *inf) override;
502 void stop (ptid_t) override;
504 void interrupt () override;
506 void pass_ctrlc () override;
508 enum target_xfer_status xfer_partial (enum target_object object,
511 const gdb_byte *writebuf,
512 ULONGEST offset, ULONGEST len,
513 ULONGEST *xfered_len) override;
515 ULONGEST get_memory_xfer_limit () override;
517 void rcmd (const char *command, struct ui_file *output) override;
519 char *pid_to_exec_file (int pid) override;
521 void log_command (const char *cmd) override
523 serial_log_command (this, cmd);
526 CORE_ADDR get_thread_local_address (ptid_t ptid,
527 CORE_ADDR load_module_addr,
528 CORE_ADDR offset) override;
530 bool has_all_memory () override { return default_child_has_all_memory (); }
531 bool has_memory () override { return default_child_has_memory (); }
532 bool has_stack () override { return default_child_has_stack (); }
533 bool has_registers () override { return default_child_has_registers (); }
534 bool has_execution (ptid_t ptid) override { return default_child_has_execution (ptid); }
536 bool can_execute_reverse () override;
538 std::vector<mem_region> memory_map () override;
540 void flash_erase (ULONGEST address, LONGEST length) override;
542 void flash_done () override;
544 const struct target_desc *read_description () override;
546 int search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
547 const gdb_byte *pattern, ULONGEST pattern_len,
548 CORE_ADDR *found_addrp) override;
550 bool can_async_p () override;
552 bool is_async_p () override;
554 void async (int) override;
556 void thread_events (int) override;
558 int can_do_single_step () override;
560 void terminal_inferior () override;
562 void terminal_ours () override;
564 bool supports_non_stop () override;
566 bool supports_multi_process () override;
568 bool supports_disable_randomization () override;
570 bool filesystem_is_local () override;
573 int fileio_open (struct inferior *inf, const char *filename,
574 int flags, int mode, int warn_if_slow,
575 int *target_errno) override;
577 int fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
578 ULONGEST offset, int *target_errno) override;
580 int fileio_pread (int fd, gdb_byte *read_buf, int len,
581 ULONGEST offset, int *target_errno) override;
583 int fileio_fstat (int fd, struct stat *sb, int *target_errno) override;
585 int fileio_close (int fd, int *target_errno) override;
587 int fileio_unlink (struct inferior *inf,
588 const char *filename,
589 int *target_errno) override;
591 gdb::optional<std::string>
592 fileio_readlink (struct inferior *inf,
593 const char *filename,
594 int *target_errno) override;
596 bool supports_enable_disable_tracepoint () override;
598 bool supports_string_tracing () override;
600 bool supports_evaluation_of_breakpoint_conditions () override;
602 bool can_run_breakpoint_commands () override;
604 void trace_init () override;
606 void download_tracepoint (struct bp_location *location) override;
608 bool can_download_tracepoint () override;
610 void download_trace_state_variable (const trace_state_variable &tsv) override;
612 void enable_tracepoint (struct bp_location *location) override;
614 void disable_tracepoint (struct bp_location *location) override;
616 void trace_set_readonly_regions () override;
618 void trace_start () override;
620 int get_trace_status (struct trace_status *ts) override;
622 void get_tracepoint_status (struct breakpoint *tp, struct uploaded_tp *utp)
625 void trace_stop () override;
627 int trace_find (enum trace_find_type type, int num,
628 CORE_ADDR addr1, CORE_ADDR addr2, int *tpp) override;
630 bool get_trace_state_variable_value (int tsv, LONGEST *val) override;
632 int save_trace_data (const char *filename) override;
634 int upload_tracepoints (struct uploaded_tp **utpp) override;
636 int upload_trace_state_variables (struct uploaded_tsv **utsvp) override;
638 LONGEST get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len) override;
640 int get_min_fast_tracepoint_insn_len () override;
642 void set_disconnected_tracing (int val) override;
644 void set_circular_trace_buffer (int val) override;
646 void set_trace_buffer_size (LONGEST val) override;
648 bool set_trace_notes (const char *user, const char *notes,
649 const char *stopnotes) override;
651 int core_of_thread (ptid_t ptid) override;
653 int verify_memory (const gdb_byte *data,
654 CORE_ADDR memaddr, ULONGEST size) override;
657 bool get_tib_address (ptid_t ptid, CORE_ADDR *addr) override;
659 void set_permissions () override;
661 bool static_tracepoint_marker_at (CORE_ADDR,
662 struct static_tracepoint_marker *marker)
665 std::vector<static_tracepoint_marker>
666 static_tracepoint_markers_by_strid (const char *id) override;
668 traceframe_info_up traceframe_info () override;
670 bool use_agent (bool use) override;
671 bool can_use_agent () override;
673 struct btrace_target_info *enable_btrace (ptid_t ptid,
674 const struct btrace_config *conf) override;
676 void disable_btrace (struct btrace_target_info *tinfo) override;
678 void teardown_btrace (struct btrace_target_info *tinfo) override;
680 enum btrace_error read_btrace (struct btrace_data *data,
681 struct btrace_target_info *btinfo,
682 enum btrace_read_type type) override;
684 const struct btrace_config *btrace_conf (const struct btrace_target_info *) override;
685 bool augmented_libraries_svr4_read () override;
686 int follow_fork (int, int) override;
687 void follow_exec (struct inferior *, char *) override;
688 int insert_fork_catchpoint (int) override;
689 int remove_fork_catchpoint (int) override;
690 int insert_vfork_catchpoint (int) override;
691 int remove_vfork_catchpoint (int) override;
692 int insert_exec_catchpoint (int) override;
693 int remove_exec_catchpoint (int) override;
694 enum exec_direction_kind execution_direction () override;
696 public: /* Remote specific methods. */
698 void remote_download_command_source (int num, ULONGEST addr,
699 struct command_line *cmds);
701 void remote_file_put (const char *local_file, const char *remote_file,
703 void remote_file_get (const char *remote_file, const char *local_file,
705 void remote_file_delete (const char *remote_file, int from_tty);
707 int remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
708 ULONGEST offset, int *remote_errno);
709 int remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
710 ULONGEST offset, int *remote_errno);
711 int remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
712 ULONGEST offset, int *remote_errno);
714 int remote_hostio_send_command (int command_bytes, int which_packet,
715 int *remote_errno, char **attachment,
716 int *attachment_len);
717 int remote_hostio_set_filesystem (struct inferior *inf,
719 /* We should get rid of this and use fileio_open directly. */
720 int remote_hostio_open (struct inferior *inf, const char *filename,
721 int flags, int mode, int warn_if_slow,
723 int remote_hostio_close (int fd, int *remote_errno);
725 int remote_hostio_unlink (inferior *inf, const char *filename,
728 struct remote_state *get_remote_state ();
730 long get_remote_packet_size (void);
731 long get_memory_packet_size (struct memory_packet_config *config);
733 long get_memory_write_packet_size ();
734 long get_memory_read_packet_size ();
736 char *append_pending_thread_resumptions (char *p, char *endp,
738 static void open_1 (const char *name, int from_tty, int extended_p);
739 void start_remote (int from_tty, int extended_p);
740 void remote_detach_1 (struct inferior *inf, int from_tty);
742 char *append_resumption (char *p, char *endp,
743 ptid_t ptid, int step, gdb_signal siggnal);
744 int remote_resume_with_vcont (ptid_t ptid, int step,
747 void add_current_inferior_and_thread (char *wait_status);
749 ptid_t wait_ns (ptid_t ptid, struct target_waitstatus *status,
751 ptid_t wait_as (ptid_t ptid, target_waitstatus *status,
754 ptid_t process_stop_reply (struct stop_reply *stop_reply,
755 target_waitstatus *status);
757 void remote_notice_new_inferior (ptid_t currthread, int executing);
759 void process_initial_stop_replies (int from_tty);
761 thread_info *remote_add_thread (ptid_t ptid, bool running, bool executing);
763 void btrace_sync_conf (const btrace_config *conf);
765 void remote_btrace_maybe_reopen ();
767 void remove_new_fork_children (threads_listing_context *context);
768 void kill_new_fork_children (int pid);
769 void discard_pending_stop_replies (struct inferior *inf);
770 int stop_reply_queue_length ();
772 void check_pending_events_prevent_wildcard_vcont
773 (int *may_global_wildcard_vcont);
775 void discard_pending_stop_replies_in_queue ();
776 struct stop_reply *remote_notif_remove_queued_reply (ptid_t ptid);
777 struct stop_reply *queued_stop_reply (ptid_t ptid);
778 int peek_stop_reply (ptid_t ptid);
779 void remote_parse_stop_reply (char *buf, stop_reply *event);
781 void remote_stop_ns (ptid_t ptid);
782 void remote_interrupt_as ();
783 void remote_interrupt_ns ();
785 char *remote_get_noisy_reply ();
786 int remote_query_attached (int pid);
787 inferior *remote_add_inferior (int fake_pid_p, int pid, int attached,
790 ptid_t remote_current_thread (ptid_t oldpid);
791 ptid_t get_current_thread (char *wait_status);
793 void set_thread (ptid_t ptid, int gen);
794 void set_general_thread (ptid_t ptid);
795 void set_continue_thread (ptid_t ptid);
796 void set_general_process ();
798 char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
800 int remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
801 gdb_ext_thread_info *info);
802 int remote_get_threadinfo (threadref *threadid, int fieldset,
803 gdb_ext_thread_info *info);
805 int parse_threadlist_response (char *pkt, int result_limit,
806 threadref *original_echo,
807 threadref *resultlist,
809 int remote_get_threadlist (int startflag, threadref *nextthread,
810 int result_limit, int *done, int *result_count,
811 threadref *threadlist);
813 int remote_threadlist_iterator (rmt_thread_action stepfunction,
814 void *context, int looplimit);
816 int remote_get_threads_with_ql (threads_listing_context *context);
817 int remote_get_threads_with_qxfer (threads_listing_context *context);
818 int remote_get_threads_with_qthreadinfo (threads_listing_context *context);
820 void extended_remote_restart ();
824 void remote_check_symbols ();
826 void remote_supported_packet (const struct protocol_feature *feature,
827 enum packet_support support,
828 const char *argument);
830 void remote_query_supported ();
832 void remote_packet_size (const protocol_feature *feature,
833 packet_support support, const char *value);
835 void remote_serial_quit_handler ();
837 void remote_detach_pid (int pid);
839 void remote_vcont_probe ();
841 void remote_resume_with_hc (ptid_t ptid, int step,
844 void send_interrupt_sequence ();
845 void interrupt_query ();
847 void remote_notif_get_pending_events (notif_client *nc);
849 int fetch_register_using_p (struct regcache *regcache,
851 int send_g_packet ();
852 void process_g_packet (struct regcache *regcache);
853 void fetch_registers_using_g (struct regcache *regcache);
854 int store_register_using_P (const struct regcache *regcache,
856 void store_registers_using_G (const struct regcache *regcache);
858 void set_remote_traceframe ();
860 void check_binary_download (CORE_ADDR addr);
862 target_xfer_status remote_write_bytes_aux (const char *header,
864 const gdb_byte *myaddr,
867 ULONGEST *xfered_len_units,
871 target_xfer_status remote_write_bytes (CORE_ADDR memaddr,
872 const gdb_byte *myaddr, ULONGEST len,
873 int unit_size, ULONGEST *xfered_len);
875 target_xfer_status remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
877 int unit_size, ULONGEST *xfered_len_units);
879 target_xfer_status remote_xfer_live_readonly_partial (gdb_byte *readbuf,
883 ULONGEST *xfered_len);
885 target_xfer_status remote_read_bytes (CORE_ADDR memaddr,
886 gdb_byte *myaddr, ULONGEST len,
888 ULONGEST *xfered_len);
890 packet_result remote_send_printf (const char *format, ...)
891 ATTRIBUTE_PRINTF (2, 3);
893 target_xfer_status remote_flash_write (ULONGEST address,
894 ULONGEST length, ULONGEST *xfered_len,
895 const gdb_byte *data);
897 int readchar (int timeout);
899 void remote_serial_write (const char *str, int len);
901 int putpkt (const char *buf);
902 int putpkt_binary (const char *buf, int cnt);
905 long read_frame (char **buf_p, long *sizeof_buf);
906 void getpkt (char **buf, long *sizeof_buf, int forever);
907 int getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
908 int expecting_notif, int *is_notif);
909 int getpkt_sane (char **buf, long *sizeof_buf, int forever);
910 int getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
912 int remote_vkill (int pid);
913 void remote_kill_k ();
915 void extended_remote_disable_randomization (int val);
916 int extended_remote_run (const std::string &args);
918 void send_environment_packet (const char *action,
922 void extended_remote_environment_support ();
923 void extended_remote_set_inferior_cwd ();
925 target_xfer_status remote_write_qxfer (const char *object_name,
927 const gdb_byte *writebuf,
928 ULONGEST offset, LONGEST len,
929 ULONGEST *xfered_len,
930 struct packet_config *packet);
932 target_xfer_status remote_read_qxfer (const char *object_name,
934 gdb_byte *readbuf, ULONGEST offset,
936 ULONGEST *xfered_len,
937 struct packet_config *packet);
939 void push_stop_reply (struct stop_reply *new_event);
941 bool vcont_r_supported ();
943 void packet_command (const char *args, int from_tty);
945 private: /* data fields */
947 /* The remote state. Don't reference this directly. Use the
948 get_remote_state method instead. */
949 remote_state m_remote_state;
952 static const target_info extended_remote_target_info = {
954 N_("Extended remote serial target in gdb-specific protocol"),
958 /* Set up the extended remote target by extending the standard remote
959 target and adding to it. */
961 class extended_remote_target final : public remote_target
964 const target_info &info () const override
965 { return extended_remote_target_info; }
967 /* Open an extended-remote connection. */
968 static void open (const char *, int);
970 bool can_create_inferior () override { return true; }
971 void create_inferior (const char *, const std::string &,
972 char **, int) override;
974 void detach (inferior *, int) override;
976 bool can_attach () override { return true; }
977 void attach (const char *, int) override;
979 void post_attach (int) override;
980 bool supports_disable_randomization () override;
983 /* Per-program-space data key. */
984 static const struct program_space_data *remote_pspace_data;
986 /* The variable registered as the control variable used by the
987 remote exec-file commands. While the remote exec-file setting is
988 per-program-space, the set/show machinery uses this as the
989 location of the remote exec-file value. */
990 static char *remote_exec_file_var;
992 /* The size to align memory write packets, when practical. The protocol
993 does not guarantee any alignment, and gdb will generate short
994 writes and unaligned writes, but even as a best-effort attempt this
995 can improve bulk transfers. For instance, if a write is misaligned
996 relative to the target's data bus, the stub may need to make an extra
997 round trip fetching data from the target. This doesn't make a
998 huge difference, but it's easy to do, so we try to be helpful.
1000 The alignment chosen is arbitrary; usually data bus width is
1001 important here, not the possibly larger cache line size. */
1002 enum { REMOTE_ALIGN_WRITES = 16 };
1004 /* Prototypes for local functions. */
1006 static int hexnumlen (ULONGEST num);
1008 static int stubhex (int ch);
1010 static int hexnumstr (char *, ULONGEST);
1012 static int hexnumnstr (char *, ULONGEST, int);
1014 static CORE_ADDR remote_address_masked (CORE_ADDR);
1016 static void print_packet (const char *);
1018 static int stub_unpack_int (char *buff, int fieldlength);
1020 struct packet_config;
1022 static void show_packet_config_cmd (struct packet_config *config);
1024 static void show_remote_protocol_packet_cmd (struct ui_file *file,
1026 struct cmd_list_element *c,
1029 static ptid_t read_ptid (const char *buf, const char **obuf);
1031 static void remote_async_inferior_event_handler (gdb_client_data);
1033 static int remote_read_description_p (struct target_ops *target);
1035 static void remote_console_output (char *msg);
1037 static void remote_btrace_reset (remote_state *rs);
1039 static void remote_unpush_and_throw (void);
1043 static struct cmd_list_element *remote_cmdlist;
1045 /* For "set remote" and "show remote". */
1047 static struct cmd_list_element *remote_set_cmdlist;
1048 static struct cmd_list_element *remote_show_cmdlist;
1050 /* Controls whether GDB is willing to use range stepping. */
1052 static int use_range_stepping = 1;
1054 /* The max number of chars in debug output. The rest of chars are
1057 #define REMOTE_DEBUG_MAX_CHAR 512
1059 /* Private data that we'll store in (struct thread_info)->priv. */
1060 struct remote_thread_info : public private_thread_info
1066 /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
1067 sequence of bytes. */
1068 gdb::byte_vector thread_handle;
1070 /* Whether the target stopped for a breakpoint/watchpoint. */
1071 enum target_stop_reason stop_reason = TARGET_STOPPED_BY_NO_REASON;
1073 /* This is set to the data address of the access causing the target
1074 to stop for a watchpoint. */
1075 CORE_ADDR watch_data_address = 0;
1077 /* Fields used by the vCont action coalescing implemented in
1078 remote_resume / remote_commit_resume. remote_resume stores each
1079 thread's last resume request in these fields, so that a later
1080 remote_commit_resume knows which is the proper action for this
1081 thread to include in the vCont packet. */
1083 /* True if the last target_resume call for this thread was a step
1084 request, false if a continue request. */
1085 int last_resume_step = 0;
1087 /* The signal specified in the last target_resume call for this
1089 gdb_signal last_resume_sig = GDB_SIGNAL_0;
1091 /* Whether this thread was already vCont-resumed on the remote
1093 int vcont_resumed = 0;
1096 remote_state::remote_state ()
1098 /* The default buffer size is unimportant; it will be expanded
1099 whenever a larger buffer is needed. */
1100 this->buf_size = 400;
1101 this->buf = (char *) xmalloc (this->buf_size);
1104 remote_state::~remote_state ()
1106 xfree (this->last_pass_packet);
1107 xfree (this->last_program_signals_packet);
1109 xfree (this->finished_object);
1110 xfree (this->finished_annex);
1113 /* Utility: generate error from an incoming stub packet. */
1115 trace_error (char *buf)
1118 return; /* not an error msg */
1121 case '1': /* malformed packet error */
1122 if (*++buf == '0') /* general case: */
1123 error (_("remote.c: error in outgoing packet."));
1125 error (_("remote.c: error in outgoing packet at field #%ld."),
1126 strtol (buf, NULL, 16));
1128 error (_("Target returns error code '%s'."), buf);
1132 /* Utility: wait for reply from stub, while accepting "O" packets. */
1135 remote_target::remote_get_noisy_reply ()
1137 struct remote_state *rs = get_remote_state ();
1139 do /* Loop on reply from remote stub. */
1143 QUIT; /* Allow user to bail out with ^C. */
1144 getpkt (&rs->buf, &rs->buf_size, 0);
1148 else if (startswith (buf, "qRelocInsn:"))
1151 CORE_ADDR from, to, org_to;
1153 int adjusted_size = 0;
1156 p = buf + strlen ("qRelocInsn:");
1157 pp = unpack_varlen_hex (p, &ul);
1159 error (_("invalid qRelocInsn packet: %s"), buf);
1163 unpack_varlen_hex (p, &ul);
1170 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
1173 CATCH (ex, RETURN_MASK_ALL)
1175 if (ex.error == MEMORY_ERROR)
1177 /* Propagate memory errors silently back to the
1178 target. The stub may have limited the range of
1179 addresses we can write to, for example. */
1183 /* Something unexpectedly bad happened. Be verbose
1184 so we can tell what, and propagate the error back
1185 to the stub, so it doesn't get stuck waiting for
1187 exception_fprintf (gdb_stderr, ex,
1188 _("warning: relocating instruction: "));
1196 adjusted_size = to - org_to;
1198 xsnprintf (buf, rs->buf_size, "qRelocInsn:%x", adjusted_size);
1202 else if (buf[0] == 'O' && buf[1] != 'K')
1203 remote_console_output (buf + 1); /* 'O' message from stub */
1205 return buf; /* Here's the actual reply. */
1210 struct remote_arch_state *
1211 remote_state::get_remote_arch_state (struct gdbarch *gdbarch)
1213 remote_arch_state *rsa;
1215 auto it = this->m_arch_states.find (gdbarch);
1216 if (it == this->m_arch_states.end ())
1218 auto p = this->m_arch_states.emplace (std::piecewise_construct,
1219 std::forward_as_tuple (gdbarch),
1220 std::forward_as_tuple (gdbarch));
1221 rsa = &p.first->second;
1223 /* Make sure that the packet buffer is plenty big enough for
1224 this architecture. */
1225 if (this->buf_size < rsa->remote_packet_size)
1227 this->buf_size = 2 * rsa->remote_packet_size;
1228 this->buf = (char *) xrealloc (this->buf, this->buf_size);
1237 /* Fetch the global remote target state. */
1240 remote_target::get_remote_state ()
1242 /* Make sure that the remote architecture state has been
1243 initialized, because doing so might reallocate rs->buf. Any
1244 function which calls getpkt also needs to be mindful of changes
1245 to rs->buf, but this call limits the number of places which run
1247 m_remote_state.get_remote_arch_state (target_gdbarch ());
1249 return &m_remote_state;
1252 /* Cleanup routine for the remote module's pspace data. */
1255 remote_pspace_data_cleanup (struct program_space *pspace, void *arg)
1257 char *remote_exec_file = (char *) arg;
1259 xfree (remote_exec_file);
1262 /* Fetch the remote exec-file from the current program space. */
1265 get_remote_exec_file (void)
1267 char *remote_exec_file;
1270 = (char *) program_space_data (current_program_space,
1271 remote_pspace_data);
1272 if (remote_exec_file == NULL)
1275 return remote_exec_file;
1278 /* Set the remote exec file for PSPACE. */
1281 set_pspace_remote_exec_file (struct program_space *pspace,
1282 char *remote_exec_file)
1284 char *old_file = (char *) program_space_data (pspace, remote_pspace_data);
1287 set_program_space_data (pspace, remote_pspace_data,
1288 xstrdup (remote_exec_file));
1291 /* The "set/show remote exec-file" set command hook. */
1294 set_remote_exec_file (const char *ignored, int from_tty,
1295 struct cmd_list_element *c)
1297 gdb_assert (remote_exec_file_var != NULL);
1298 set_pspace_remote_exec_file (current_program_space, remote_exec_file_var);
1301 /* The "set/show remote exec-file" show command hook. */
1304 show_remote_exec_file (struct ui_file *file, int from_tty,
1305 struct cmd_list_element *cmd, const char *value)
1307 fprintf_filtered (file, "%s\n", remote_exec_file_var);
1311 compare_pnums (const void *lhs_, const void *rhs_)
1313 const struct packet_reg * const *lhs
1314 = (const struct packet_reg * const *) lhs_;
1315 const struct packet_reg * const *rhs
1316 = (const struct packet_reg * const *) rhs_;
1318 if ((*lhs)->pnum < (*rhs)->pnum)
1320 else if ((*lhs)->pnum == (*rhs)->pnum)
1327 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
1329 int regnum, num_remote_regs, offset;
1330 struct packet_reg **remote_regs;
1332 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
1334 struct packet_reg *r = ®s[regnum];
1336 if (register_size (gdbarch, regnum) == 0)
1337 /* Do not try to fetch zero-sized (placeholder) registers. */
1340 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
1345 /* Define the g/G packet format as the contents of each register
1346 with a remote protocol number, in order of ascending protocol
1349 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
1350 for (num_remote_regs = 0, regnum = 0;
1351 regnum < gdbarch_num_regs (gdbarch);
1353 if (regs[regnum].pnum != -1)
1354 remote_regs[num_remote_regs++] = ®s[regnum];
1356 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
1359 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
1361 remote_regs[regnum]->in_g_packet = 1;
1362 remote_regs[regnum]->offset = offset;
1363 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
1369 /* Given the architecture described by GDBARCH, return the remote
1370 protocol register's number and the register's offset in the g/G
1371 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
1372 If the target does not have a mapping for REGNUM, return false,
1373 otherwise, return true. */
1376 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
1377 int *pnum, int *poffset)
1379 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
1381 std::vector<packet_reg> regs (gdbarch_num_regs (gdbarch));
1383 map_regcache_remote_table (gdbarch, regs.data ());
1385 *pnum = regs[regnum].pnum;
1386 *poffset = regs[regnum].offset;
1391 remote_arch_state::remote_arch_state (struct gdbarch *gdbarch)
1393 /* Use the architecture to build a regnum<->pnum table, which will be
1394 1:1 unless a feature set specifies otherwise. */
1395 this->regs.reset (new packet_reg [gdbarch_num_regs (gdbarch)] ());
1397 /* Record the maximum possible size of the g packet - it may turn out
1399 this->sizeof_g_packet
1400 = map_regcache_remote_table (gdbarch, this->regs.get ());
1402 /* Default maximum number of characters in a packet body. Many
1403 remote stubs have a hardwired buffer size of 400 bytes
1404 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
1405 as the maximum packet-size to ensure that the packet and an extra
1406 NUL character can always fit in the buffer. This stops GDB
1407 trashing stubs that try to squeeze an extra NUL into what is
1408 already a full buffer (As of 1999-12-04 that was most stubs). */
1409 this->remote_packet_size = 400 - 1;
1411 /* This one is filled in when a ``g'' packet is received. */
1412 this->actual_register_packet_size = 0;
1414 /* Should rsa->sizeof_g_packet needs more space than the
1415 default, adjust the size accordingly. Remember that each byte is
1416 encoded as two characters. 32 is the overhead for the packet
1417 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
1418 (``$NN:G...#NN'') is a better guess, the below has been padded a
1420 if (this->sizeof_g_packet > ((this->remote_packet_size - 32) / 2))
1421 this->remote_packet_size = (this->sizeof_g_packet * 2 + 32);
1424 /* Get a pointer to the current remote target. If not connected to a
1425 remote target, return NULL. */
1427 static remote_target *
1428 get_current_remote_target ()
1430 target_ops *proc_target = find_target_at (process_stratum);
1431 return dynamic_cast<remote_target *> (proc_target);
1434 /* Return the current allowed size of a remote packet. This is
1435 inferred from the current architecture, and should be used to
1436 limit the length of outgoing packets. */
1438 remote_target::get_remote_packet_size ()
1440 struct remote_state *rs = get_remote_state ();
1441 remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
1443 if (rs->explicit_packet_size)
1444 return rs->explicit_packet_size;
1446 return rsa->remote_packet_size;
1449 static struct packet_reg *
1450 packet_reg_from_regnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1453 if (regnum < 0 && regnum >= gdbarch_num_regs (gdbarch))
1457 struct packet_reg *r = &rsa->regs[regnum];
1459 gdb_assert (r->regnum == regnum);
1464 static struct packet_reg *
1465 packet_reg_from_pnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1470 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
1472 struct packet_reg *r = &rsa->regs[i];
1474 if (r->pnum == pnum)
1480 /* Allow the user to specify what sequence to send to the remote
1481 when he requests a program interruption: Although ^C is usually
1482 what remote systems expect (this is the default, here), it is
1483 sometimes preferable to send a break. On other systems such
1484 as the Linux kernel, a break followed by g, which is Magic SysRq g
1485 is required in order to interrupt the execution. */
1486 const char interrupt_sequence_control_c[] = "Ctrl-C";
1487 const char interrupt_sequence_break[] = "BREAK";
1488 const char interrupt_sequence_break_g[] = "BREAK-g";
1489 static const char *const interrupt_sequence_modes[] =
1491 interrupt_sequence_control_c,
1492 interrupt_sequence_break,
1493 interrupt_sequence_break_g,
1496 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
1499 show_interrupt_sequence (struct ui_file *file, int from_tty,
1500 struct cmd_list_element *c,
1503 if (interrupt_sequence_mode == interrupt_sequence_control_c)
1504 fprintf_filtered (file,
1505 _("Send the ASCII ETX character (Ctrl-c) "
1506 "to the remote target to interrupt the "
1507 "execution of the program.\n"));
1508 else if (interrupt_sequence_mode == interrupt_sequence_break)
1509 fprintf_filtered (file,
1510 _("send a break signal to the remote target "
1511 "to interrupt the execution of the program.\n"));
1512 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
1513 fprintf_filtered (file,
1514 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
1515 "the remote target to interrupt the execution "
1516 "of Linux kernel.\n"));
1518 internal_error (__FILE__, __LINE__,
1519 _("Invalid value for interrupt_sequence_mode: %s."),
1520 interrupt_sequence_mode);
1523 /* This boolean variable specifies whether interrupt_sequence is sent
1524 to the remote target when gdb connects to it.
1525 This is mostly needed when you debug the Linux kernel: The Linux kernel
1526 expects BREAK g which is Magic SysRq g for connecting gdb. */
1527 static int interrupt_on_connect = 0;
1529 /* This variable is used to implement the "set/show remotebreak" commands.
1530 Since these commands are now deprecated in favor of "set/show remote
1531 interrupt-sequence", it no longer has any effect on the code. */
1532 static int remote_break;
1535 set_remotebreak (const char *args, int from_tty, struct cmd_list_element *c)
1538 interrupt_sequence_mode = interrupt_sequence_break;
1540 interrupt_sequence_mode = interrupt_sequence_control_c;
1544 show_remotebreak (struct ui_file *file, int from_tty,
1545 struct cmd_list_element *c,
1550 /* This variable sets the number of bits in an address that are to be
1551 sent in a memory ("M" or "m") packet. Normally, after stripping
1552 leading zeros, the entire address would be sent. This variable
1553 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
1554 initial implementation of remote.c restricted the address sent in
1555 memory packets to ``host::sizeof long'' bytes - (typically 32
1556 bits). Consequently, for 64 bit targets, the upper 32 bits of an
1557 address was never sent. Since fixing this bug may cause a break in
1558 some remote targets this variable is principly provided to
1559 facilitate backward compatibility. */
1561 static unsigned int remote_address_size;
1564 /* User configurable variables for the number of characters in a
1565 memory read/write packet. MIN (rsa->remote_packet_size,
1566 rsa->sizeof_g_packet) is the default. Some targets need smaller
1567 values (fifo overruns, et.al.) and some users need larger values
1568 (speed up transfers). The variables ``preferred_*'' (the user
1569 request), ``current_*'' (what was actually set) and ``forced_*''
1570 (Positive - a soft limit, negative - a hard limit). */
1572 struct memory_packet_config
1579 /* The default max memory-write-packet-size, when the setting is
1580 "fixed". The 16k is historical. (It came from older GDB's using
1581 alloca for buffers and the knowledge (folklore?) that some hosts
1582 don't cope very well with large alloca calls.) */
1583 #define DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED 16384
1585 /* The minimum remote packet size for memory transfers. Ensures we
1586 can write at least one byte. */
1587 #define MIN_MEMORY_PACKET_SIZE 20
1589 /* Get the memory packet size, assuming it is fixed. */
1592 get_fixed_memory_packet_size (struct memory_packet_config *config)
1594 gdb_assert (config->fixed_p);
1596 if (config->size <= 0)
1597 return DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED;
1599 return config->size;
1602 /* Compute the current size of a read/write packet. Since this makes
1603 use of ``actual_register_packet_size'' the computation is dynamic. */
1606 remote_target::get_memory_packet_size (struct memory_packet_config *config)
1608 struct remote_state *rs = get_remote_state ();
1609 remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
1612 if (config->fixed_p)
1613 what_they_get = get_fixed_memory_packet_size (config);
1616 what_they_get = get_remote_packet_size ();
1617 /* Limit the packet to the size specified by the user. */
1618 if (config->size > 0
1619 && what_they_get > config->size)
1620 what_they_get = config->size;
1622 /* Limit it to the size of the targets ``g'' response unless we have
1623 permission from the stub to use a larger packet size. */
1624 if (rs->explicit_packet_size == 0
1625 && rsa->actual_register_packet_size > 0
1626 && what_they_get > rsa->actual_register_packet_size)
1627 what_they_get = rsa->actual_register_packet_size;
1629 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1630 what_they_get = MIN_MEMORY_PACKET_SIZE;
1632 /* Make sure there is room in the global buffer for this packet
1633 (including its trailing NUL byte). */
1634 if (rs->buf_size < what_they_get + 1)
1636 rs->buf_size = 2 * what_they_get;
1637 rs->buf = (char *) xrealloc (rs->buf, 2 * what_they_get);
1640 return what_they_get;
1643 /* Update the size of a read/write packet. If they user wants
1644 something really big then do a sanity check. */
1647 set_memory_packet_size (const char *args, struct memory_packet_config *config)
1649 int fixed_p = config->fixed_p;
1650 long size = config->size;
1653 error (_("Argument required (integer, `fixed' or `limited')."));
1654 else if (strcmp (args, "hard") == 0
1655 || strcmp (args, "fixed") == 0)
1657 else if (strcmp (args, "soft") == 0
1658 || strcmp (args, "limit") == 0)
1664 size = strtoul (args, &end, 0);
1666 error (_("Invalid %s (bad syntax)."), config->name);
1668 /* Instead of explicitly capping the size of a packet to or
1669 disallowing it, the user is allowed to set the size to
1670 something arbitrarily large. */
1674 if (fixed_p && !config->fixed_p)
1676 /* So that the query shows the correct value. */
1677 long query_size = (size <= 0
1678 ? DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED
1681 if (! query (_("The target may not be able to correctly handle a %s\n"
1682 "of %ld bytes. Change the packet size? "),
1683 config->name, query_size))
1684 error (_("Packet size not changed."));
1686 /* Update the config. */
1687 config->fixed_p = fixed_p;
1688 config->size = size;
1692 show_memory_packet_size (struct memory_packet_config *config)
1694 if (config->size == 0)
1695 printf_filtered (_("The %s is 0 (default). "), config->name);
1697 printf_filtered (_("The %s is %ld. "), config->name, config->size);
1698 if (config->fixed_p)
1699 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
1700 get_fixed_memory_packet_size (config));
1703 remote_target *remote = get_current_remote_target ();
1706 printf_filtered (_("Packets are limited to %ld bytes.\n"),
1707 remote->get_memory_packet_size (config));
1709 puts_filtered ("The actual limit will be further reduced "
1710 "dependent on the target.\n");
1714 static struct memory_packet_config memory_write_packet_config =
1716 "memory-write-packet-size",
1720 set_memory_write_packet_size (const char *args, int from_tty)
1722 set_memory_packet_size (args, &memory_write_packet_config);
1726 show_memory_write_packet_size (const char *args, int from_tty)
1728 show_memory_packet_size (&memory_write_packet_config);
1731 /* Show the number of hardware watchpoints that can be used. */
1734 show_hardware_watchpoint_limit (struct ui_file *file, int from_tty,
1735 struct cmd_list_element *c,
1738 fprintf_filtered (file, _("The maximum number of target hardware "
1739 "watchpoints is %s.\n"), value);
1742 /* Show the length limit (in bytes) for hardware watchpoints. */
1745 show_hardware_watchpoint_length_limit (struct ui_file *file, int from_tty,
1746 struct cmd_list_element *c,
1749 fprintf_filtered (file, _("The maximum length (in bytes) of a target "
1750 "hardware watchpoint is %s.\n"), value);
1753 /* Show the number of hardware breakpoints that can be used. */
1756 show_hardware_breakpoint_limit (struct ui_file *file, int from_tty,
1757 struct cmd_list_element *c,
1760 fprintf_filtered (file, _("The maximum number of target hardware "
1761 "breakpoints is %s.\n"), value);
1765 remote_target::get_memory_write_packet_size ()
1767 return get_memory_packet_size (&memory_write_packet_config);
1770 static struct memory_packet_config memory_read_packet_config =
1772 "memory-read-packet-size",
1776 set_memory_read_packet_size (const char *args, int from_tty)
1778 set_memory_packet_size (args, &memory_read_packet_config);
1782 show_memory_read_packet_size (const char *args, int from_tty)
1784 show_memory_packet_size (&memory_read_packet_config);
1788 remote_target::get_memory_read_packet_size ()
1790 long size = get_memory_packet_size (&memory_read_packet_config);
1792 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1793 extra buffer size argument before the memory read size can be
1794 increased beyond this. */
1795 if (size > get_remote_packet_size ())
1796 size = get_remote_packet_size ();
1802 struct packet_config
1807 /* If auto, GDB auto-detects support for this packet or feature,
1808 either through qSupported, or by trying the packet and looking
1809 at the response. If true, GDB assumes the target supports this
1810 packet. If false, the packet is disabled. Configs that don't
1811 have an associated command always have this set to auto. */
1812 enum auto_boolean detect;
1814 /* Does the target support this packet? */
1815 enum packet_support support;
1818 static enum packet_support packet_config_support (struct packet_config *config);
1819 static enum packet_support packet_support (int packet);
1822 show_packet_config_cmd (struct packet_config *config)
1824 const char *support = "internal-error";
1826 switch (packet_config_support (config))
1829 support = "enabled";
1831 case PACKET_DISABLE:
1832 support = "disabled";
1834 case PACKET_SUPPORT_UNKNOWN:
1835 support = "unknown";
1838 switch (config->detect)
1840 case AUTO_BOOLEAN_AUTO:
1841 printf_filtered (_("Support for the `%s' packet "
1842 "is auto-detected, currently %s.\n"),
1843 config->name, support);
1845 case AUTO_BOOLEAN_TRUE:
1846 case AUTO_BOOLEAN_FALSE:
1847 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1848 config->name, support);
1854 add_packet_config_cmd (struct packet_config *config, const char *name,
1855 const char *title, int legacy)
1861 config->name = name;
1862 config->title = title;
1863 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1865 show_doc = xstrprintf ("Show current use of remote "
1866 "protocol `%s' (%s) packet",
1868 /* set/show TITLE-packet {auto,on,off} */
1869 cmd_name = xstrprintf ("%s-packet", title);
1870 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
1871 &config->detect, set_doc,
1872 show_doc, NULL, /* help_doc */
1874 show_remote_protocol_packet_cmd,
1875 &remote_set_cmdlist, &remote_show_cmdlist);
1876 /* The command code copies the documentation strings. */
1879 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
1884 legacy_name = xstrprintf ("%s-packet", name);
1885 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1886 &remote_set_cmdlist);
1887 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1888 &remote_show_cmdlist);
1892 static enum packet_result
1893 packet_check_result (const char *buf)
1897 /* The stub recognized the packet request. Check that the
1898 operation succeeded. */
1900 && isxdigit (buf[1]) && isxdigit (buf[2])
1902 /* "Enn" - definitly an error. */
1903 return PACKET_ERROR;
1905 /* Always treat "E." as an error. This will be used for
1906 more verbose error messages, such as E.memtypes. */
1907 if (buf[0] == 'E' && buf[1] == '.')
1908 return PACKET_ERROR;
1910 /* The packet may or may not be OK. Just assume it is. */
1914 /* The stub does not support the packet. */
1915 return PACKET_UNKNOWN;
1918 static enum packet_result
1919 packet_ok (const char *buf, struct packet_config *config)
1921 enum packet_result result;
1923 if (config->detect != AUTO_BOOLEAN_TRUE
1924 && config->support == PACKET_DISABLE)
1925 internal_error (__FILE__, __LINE__,
1926 _("packet_ok: attempt to use a disabled packet"));
1928 result = packet_check_result (buf);
1933 /* The stub recognized the packet request. */
1934 if (config->support == PACKET_SUPPORT_UNKNOWN)
1937 fprintf_unfiltered (gdb_stdlog,
1938 "Packet %s (%s) is supported\n",
1939 config->name, config->title);
1940 config->support = PACKET_ENABLE;
1943 case PACKET_UNKNOWN:
1944 /* The stub does not support the packet. */
1945 if (config->detect == AUTO_BOOLEAN_AUTO
1946 && config->support == PACKET_ENABLE)
1948 /* If the stub previously indicated that the packet was
1949 supported then there is a protocol error. */
1950 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1951 config->name, config->title);
1953 else if (config->detect == AUTO_BOOLEAN_TRUE)
1955 /* The user set it wrong. */
1956 error (_("Enabled packet %s (%s) not recognized by stub"),
1957 config->name, config->title);
1961 fprintf_unfiltered (gdb_stdlog,
1962 "Packet %s (%s) is NOT supported\n",
1963 config->name, config->title);
1964 config->support = PACKET_DISABLE;
1985 PACKET_vFile_pwrite,
1987 PACKET_vFile_unlink,
1988 PACKET_vFile_readlink,
1991 PACKET_qXfer_features,
1992 PACKET_qXfer_exec_file,
1993 PACKET_qXfer_libraries,
1994 PACKET_qXfer_libraries_svr4,
1995 PACKET_qXfer_memory_map,
1996 PACKET_qXfer_spu_read,
1997 PACKET_qXfer_spu_write,
1998 PACKET_qXfer_osdata,
1999 PACKET_qXfer_threads,
2000 PACKET_qXfer_statictrace_read,
2001 PACKET_qXfer_traceframe_info,
2007 PACKET_QPassSignals,
2008 PACKET_QCatchSyscalls,
2009 PACKET_QProgramSignals,
2010 PACKET_QSetWorkingDir,
2011 PACKET_QStartupWithShell,
2012 PACKET_QEnvironmentHexEncoded,
2013 PACKET_QEnvironmentReset,
2014 PACKET_QEnvironmentUnset,
2016 PACKET_qSearch_memory,
2019 PACKET_QStartNoAckMode,
2021 PACKET_qXfer_siginfo_read,
2022 PACKET_qXfer_siginfo_write,
2025 /* Support for conditional tracepoints. */
2026 PACKET_ConditionalTracepoints,
2028 /* Support for target-side breakpoint conditions. */
2029 PACKET_ConditionalBreakpoints,
2031 /* Support for target-side breakpoint commands. */
2032 PACKET_BreakpointCommands,
2034 /* Support for fast tracepoints. */
2035 PACKET_FastTracepoints,
2037 /* Support for static tracepoints. */
2038 PACKET_StaticTracepoints,
2040 /* Support for installing tracepoints while a trace experiment is
2042 PACKET_InstallInTrace,
2046 PACKET_TracepointSource,
2049 PACKET_QDisableRandomization,
2051 PACKET_QTBuffer_size,
2055 PACKET_qXfer_btrace,
2057 /* Support for the QNonStop packet. */
2060 /* Support for the QThreadEvents packet. */
2061 PACKET_QThreadEvents,
2063 /* Support for multi-process extensions. */
2064 PACKET_multiprocess_feature,
2066 /* Support for enabling and disabling tracepoints while a trace
2067 experiment is running. */
2068 PACKET_EnableDisableTracepoints_feature,
2070 /* Support for collecting strings using the tracenz bytecode. */
2071 PACKET_tracenz_feature,
2073 /* Support for continuing to run a trace experiment while GDB is
2075 PACKET_DisconnectedTracing_feature,
2077 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
2078 PACKET_augmented_libraries_svr4_read_feature,
2080 /* Support for the qXfer:btrace-conf:read packet. */
2081 PACKET_qXfer_btrace_conf,
2083 /* Support for the Qbtrace-conf:bts:size packet. */
2084 PACKET_Qbtrace_conf_bts_size,
2086 /* Support for swbreak+ feature. */
2087 PACKET_swbreak_feature,
2089 /* Support for hwbreak+ feature. */
2090 PACKET_hwbreak_feature,
2092 /* Support for fork events. */
2093 PACKET_fork_event_feature,
2095 /* Support for vfork events. */
2096 PACKET_vfork_event_feature,
2098 /* Support for the Qbtrace-conf:pt:size packet. */
2099 PACKET_Qbtrace_conf_pt_size,
2101 /* Support for exec events. */
2102 PACKET_exec_event_feature,
2104 /* Support for query supported vCont actions. */
2105 PACKET_vContSupported,
2107 /* Support remote CTRL-C. */
2110 /* Support TARGET_WAITKIND_NO_RESUMED. */
2116 static struct packet_config remote_protocol_packets[PACKET_MAX];
2118 /* Returns the packet's corresponding "set remote foo-packet" command
2119 state. See struct packet_config for more details. */
2121 static enum auto_boolean
2122 packet_set_cmd_state (int packet)
2124 return remote_protocol_packets[packet].detect;
2127 /* Returns whether a given packet or feature is supported. This takes
2128 into account the state of the corresponding "set remote foo-packet"
2129 command, which may be used to bypass auto-detection. */
2131 static enum packet_support
2132 packet_config_support (struct packet_config *config)
2134 switch (config->detect)
2136 case AUTO_BOOLEAN_TRUE:
2137 return PACKET_ENABLE;
2138 case AUTO_BOOLEAN_FALSE:
2139 return PACKET_DISABLE;
2140 case AUTO_BOOLEAN_AUTO:
2141 return config->support;
2143 gdb_assert_not_reached (_("bad switch"));
2147 /* Same as packet_config_support, but takes the packet's enum value as
2150 static enum packet_support
2151 packet_support (int packet)
2153 struct packet_config *config = &remote_protocol_packets[packet];
2155 return packet_config_support (config);
2159 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
2160 struct cmd_list_element *c,
2163 struct packet_config *packet;
2165 for (packet = remote_protocol_packets;
2166 packet < &remote_protocol_packets[PACKET_MAX];
2169 if (&packet->detect == c->var)
2171 show_packet_config_cmd (packet);
2175 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
2179 /* Should we try one of the 'Z' requests? */
2183 Z_PACKET_SOFTWARE_BP,
2184 Z_PACKET_HARDWARE_BP,
2191 /* For compatibility with older distributions. Provide a ``set remote
2192 Z-packet ...'' command that updates all the Z packet types. */
2194 static enum auto_boolean remote_Z_packet_detect;
2197 set_remote_protocol_Z_packet_cmd (const char *args, int from_tty,
2198 struct cmd_list_element *c)
2202 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2203 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
2207 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
2208 struct cmd_list_element *c,
2213 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2215 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
2219 /* Returns true if the multi-process extensions are in effect. */
2222 remote_multi_process_p (struct remote_state *rs)
2224 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
2227 /* Returns true if fork events are supported. */
2230 remote_fork_event_p (struct remote_state *rs)
2232 return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
2235 /* Returns true if vfork events are supported. */
2238 remote_vfork_event_p (struct remote_state *rs)
2240 return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
2243 /* Returns true if exec events are supported. */
2246 remote_exec_event_p (struct remote_state *rs)
2248 return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
2251 /* Insert fork catchpoint target routine. If fork events are enabled
2252 then return success, nothing more to do. */
2255 remote_target::insert_fork_catchpoint (int pid)
2257 struct remote_state *rs = get_remote_state ();
2259 return !remote_fork_event_p (rs);
2262 /* Remove fork catchpoint target routine. Nothing to do, just
2266 remote_target::remove_fork_catchpoint (int pid)
2271 /* Insert vfork catchpoint target routine. If vfork events are enabled
2272 then return success, nothing more to do. */
2275 remote_target::insert_vfork_catchpoint (int pid)
2277 struct remote_state *rs = get_remote_state ();
2279 return !remote_vfork_event_p (rs);
2282 /* Remove vfork catchpoint target routine. Nothing to do, just
2286 remote_target::remove_vfork_catchpoint (int pid)
2291 /* Insert exec catchpoint target routine. If exec events are
2292 enabled, just return success. */
2295 remote_target::insert_exec_catchpoint (int pid)
2297 struct remote_state *rs = get_remote_state ();
2299 return !remote_exec_event_p (rs);
2302 /* Remove exec catchpoint target routine. Nothing to do, just
2306 remote_target::remove_exec_catchpoint (int pid)
2313 static ptid_t magic_null_ptid;
2314 static ptid_t not_sent_ptid;
2315 static ptid_t any_thread_ptid;
2317 /* Find out if the stub attached to PID (and hence GDB should offer to
2318 detach instead of killing it when bailing out). */
2321 remote_target::remote_query_attached (int pid)
2323 struct remote_state *rs = get_remote_state ();
2324 size_t size = get_remote_packet_size ();
2326 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
2329 if (remote_multi_process_p (rs))
2330 xsnprintf (rs->buf, size, "qAttached:%x", pid);
2332 xsnprintf (rs->buf, size, "qAttached");
2335 getpkt (&rs->buf, &rs->buf_size, 0);
2337 switch (packet_ok (rs->buf,
2338 &remote_protocol_packets[PACKET_qAttached]))
2341 if (strcmp (rs->buf, "1") == 0)
2345 warning (_("Remote failure reply: %s"), rs->buf);
2347 case PACKET_UNKNOWN:
2354 /* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
2355 has been invented by GDB, instead of reported by the target. Since
2356 we can be connected to a remote system before before knowing about
2357 any inferior, mark the target with execution when we find the first
2358 inferior. If ATTACHED is 1, then we had just attached to this
2359 inferior. If it is 0, then we just created this inferior. If it
2360 is -1, then try querying the remote stub to find out if it had
2361 attached to the inferior or not. If TRY_OPEN_EXEC is true then
2362 attempt to open this inferior's executable as the main executable
2363 if no main executable is open already. */
2366 remote_target::remote_add_inferior (int fake_pid_p, int pid, int attached,
2369 struct inferior *inf;
2371 /* Check whether this process we're learning about is to be
2372 considered attached, or if is to be considered to have been
2373 spawned by the stub. */
2375 attached = remote_query_attached (pid);
2377 if (gdbarch_has_global_solist (target_gdbarch ()))
2379 /* If the target shares code across all inferiors, then every
2380 attach adds a new inferior. */
2381 inf = add_inferior (pid);
2383 /* ... and every inferior is bound to the same program space.
2384 However, each inferior may still have its own address
2386 inf->aspace = maybe_new_address_space ();
2387 inf->pspace = current_program_space;
2391 /* In the traditional debugging scenario, there's a 1-1 match
2392 between program/address spaces. We simply bind the inferior
2393 to the program space's address space. */
2394 inf = current_inferior ();
2395 inferior_appeared (inf, pid);
2398 inf->attach_flag = attached;
2399 inf->fake_pid_p = fake_pid_p;
2401 /* If no main executable is currently open then attempt to
2402 open the file that was executed to create this inferior. */
2403 if (try_open_exec && get_exec_file (0) == NULL)
2404 exec_file_locate_attach (pid, 0, 1);
2409 static remote_thread_info *get_remote_thread_info (thread_info *thread);
2410 static remote_thread_info *get_remote_thread_info (ptid_t ptid);
2412 /* Add thread PTID to GDB's thread list. Tag it as executing/running
2413 according to RUNNING. */
2416 remote_target::remote_add_thread (ptid_t ptid, bool running, bool executing)
2418 struct remote_state *rs = get_remote_state ();
2419 struct thread_info *thread;
2421 /* GDB historically didn't pull threads in the initial connection
2422 setup. If the remote target doesn't even have a concept of
2423 threads (e.g., a bare-metal target), even if internally we
2424 consider that a single-threaded target, mentioning a new thread
2425 might be confusing to the user. Be silent then, preserving the
2426 age old behavior. */
2427 if (rs->starting_up)
2428 thread = add_thread_silent (ptid);
2430 thread = add_thread (ptid);
2432 get_remote_thread_info (thread)->vcont_resumed = executing;
2433 set_executing (ptid, executing);
2434 set_running (ptid, running);
2439 /* Come here when we learn about a thread id from the remote target.
2440 It may be the first time we hear about such thread, so take the
2441 opportunity to add it to GDB's thread list. In case this is the
2442 first time we're noticing its corresponding inferior, add it to
2443 GDB's inferior list as well. EXECUTING indicates whether the
2444 thread is (internally) executing or stopped. */
2447 remote_target::remote_notice_new_inferior (ptid_t currthread, int executing)
2449 /* In non-stop mode, we assume new found threads are (externally)
2450 running until proven otherwise with a stop reply. In all-stop,
2451 we can only get here if all threads are stopped. */
2452 int running = target_is_non_stop_p () ? 1 : 0;
2454 /* If this is a new thread, add it to GDB's thread list.
2455 If we leave it up to WFI to do this, bad things will happen. */
2457 thread_info *tp = find_thread_ptid (currthread);
2458 if (tp != NULL && tp->state == THREAD_EXITED)
2460 /* We're seeing an event on a thread id we knew had exited.
2461 This has to be a new thread reusing the old id. Add it. */
2462 remote_add_thread (currthread, running, executing);
2466 if (!in_thread_list (currthread))
2468 struct inferior *inf = NULL;
2469 int pid = currthread.pid ();
2471 if (inferior_ptid.is_pid ()
2472 && pid == inferior_ptid.pid ())
2474 /* inferior_ptid has no thread member yet. This can happen
2475 with the vAttach -> remote_wait,"TAAthread:" path if the
2476 stub doesn't support qC. This is the first stop reported
2477 after an attach, so this is the main thread. Update the
2478 ptid in the thread list. */
2479 if (in_thread_list (ptid_t (pid)))
2480 thread_change_ptid (inferior_ptid, currthread);
2483 remote_add_thread (currthread, running, executing);
2484 inferior_ptid = currthread;
2489 if (magic_null_ptid == inferior_ptid)
2491 /* inferior_ptid is not set yet. This can happen with the
2492 vRun -> remote_wait,"TAAthread:" path if the stub
2493 doesn't support qC. This is the first stop reported
2494 after an attach, so this is the main thread. Update the
2495 ptid in the thread list. */
2496 thread_change_ptid (inferior_ptid, currthread);
2500 /* When connecting to a target remote, or to a target
2501 extended-remote which already was debugging an inferior, we
2502 may not know about it yet. Add it before adding its child
2503 thread, so notifications are emitted in a sensible order. */
2504 if (find_inferior_pid (currthread.pid ()) == NULL)
2506 struct remote_state *rs = get_remote_state ();
2507 int fake_pid_p = !remote_multi_process_p (rs);
2509 inf = remote_add_inferior (fake_pid_p,
2510 currthread.pid (), -1, 1);
2513 /* This is really a new thread. Add it. */
2514 thread_info *new_thr
2515 = remote_add_thread (currthread, running, executing);
2517 /* If we found a new inferior, let the common code do whatever
2518 it needs to with it (e.g., read shared libraries, insert
2519 breakpoints), unless we're just setting up an all-stop
2523 struct remote_state *rs = get_remote_state ();
2525 if (!rs->starting_up)
2526 notice_new_inferior (new_thr, executing, 0);
2531 /* Return THREAD's private thread data, creating it if necessary. */
2533 static remote_thread_info *
2534 get_remote_thread_info (thread_info *thread)
2536 gdb_assert (thread != NULL);
2538 if (thread->priv == NULL)
2539 thread->priv.reset (new remote_thread_info);
2541 return static_cast<remote_thread_info *> (thread->priv.get ());
2544 static remote_thread_info *
2545 get_remote_thread_info (ptid_t ptid)
2547 thread_info *thr = find_thread_ptid (ptid);
2548 return get_remote_thread_info (thr);
2551 /* Call this function as a result of
2552 1) A halt indication (T packet) containing a thread id
2553 2) A direct query of currthread
2554 3) Successful execution of set thread */
2557 record_currthread (struct remote_state *rs, ptid_t currthread)
2559 rs->general_thread = currthread;
2562 /* If 'QPassSignals' is supported, tell the remote stub what signals
2563 it can simply pass through to the inferior without reporting. */
2566 remote_target::pass_signals (int numsigs, unsigned char *pass_signals)
2568 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
2570 char *pass_packet, *p;
2572 struct remote_state *rs = get_remote_state ();
2574 gdb_assert (numsigs < 256);
2575 for (i = 0; i < numsigs; i++)
2577 if (pass_signals[i])
2580 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
2581 strcpy (pass_packet, "QPassSignals:");
2582 p = pass_packet + strlen (pass_packet);
2583 for (i = 0; i < numsigs; i++)
2585 if (pass_signals[i])
2588 *p++ = tohex (i >> 4);
2589 *p++ = tohex (i & 15);
2598 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
2600 putpkt (pass_packet);
2601 getpkt (&rs->buf, &rs->buf_size, 0);
2602 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
2603 if (rs->last_pass_packet)
2604 xfree (rs->last_pass_packet);
2605 rs->last_pass_packet = pass_packet;
2608 xfree (pass_packet);
2612 /* If 'QCatchSyscalls' is supported, tell the remote stub
2613 to report syscalls to GDB. */
2616 remote_target::set_syscall_catchpoint (int pid, bool needed, int any_count,
2617 gdb::array_view<const int> syscall_counts)
2619 const char *catch_packet;
2620 enum packet_result result;
2623 if (packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2625 /* Not supported. */
2629 if (needed && any_count == 0)
2631 /* Count how many syscalls are to be caught. */
2632 for (size_t i = 0; i < syscall_counts.size (); i++)
2634 if (syscall_counts[i] != 0)
2641 fprintf_unfiltered (gdb_stdlog,
2642 "remote_set_syscall_catchpoint "
2643 "pid %d needed %d any_count %d n_sysno %d\n",
2644 pid, needed, any_count, n_sysno);
2647 std::string built_packet;
2650 /* Prepare a packet with the sysno list, assuming max 8+1
2651 characters for a sysno. If the resulting packet size is too
2652 big, fallback on the non-selective packet. */
2653 const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
2654 built_packet.reserve (maxpktsz);
2655 built_packet = "QCatchSyscalls:1";
2658 /* Add in each syscall to be caught. */
2659 for (size_t i = 0; i < syscall_counts.size (); i++)
2661 if (syscall_counts[i] != 0)
2662 string_appendf (built_packet, ";%zx", i);
2665 if (built_packet.size () > get_remote_packet_size ())
2667 /* catch_packet too big. Fallback to less efficient
2668 non selective mode, with GDB doing the filtering. */
2669 catch_packet = "QCatchSyscalls:1";
2672 catch_packet = built_packet.c_str ();
2675 catch_packet = "QCatchSyscalls:0";
2677 struct remote_state *rs = get_remote_state ();
2679 putpkt (catch_packet);
2680 getpkt (&rs->buf, &rs->buf_size, 0);
2681 result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_QCatchSyscalls]);
2682 if (result == PACKET_OK)
2688 /* If 'QProgramSignals' is supported, tell the remote stub what
2689 signals it should pass through to the inferior when detaching. */
2692 remote_target::program_signals (int numsigs, unsigned char *signals)
2694 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
2698 struct remote_state *rs = get_remote_state ();
2700 gdb_assert (numsigs < 256);
2701 for (i = 0; i < numsigs; i++)
2706 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
2707 strcpy (packet, "QProgramSignals:");
2708 p = packet + strlen (packet);
2709 for (i = 0; i < numsigs; i++)
2711 if (signal_pass_state (i))
2714 *p++ = tohex (i >> 4);
2715 *p++ = tohex (i & 15);
2724 if (!rs->last_program_signals_packet
2725 || strcmp (rs->last_program_signals_packet, packet) != 0)
2728 getpkt (&rs->buf, &rs->buf_size, 0);
2729 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
2730 xfree (rs->last_program_signals_packet);
2731 rs->last_program_signals_packet = packet;
2738 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
2739 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2740 thread. If GEN is set, set the general thread, if not, then set
2741 the step/continue thread. */
2743 remote_target::set_thread (ptid_t ptid, int gen)
2745 struct remote_state *rs = get_remote_state ();
2746 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
2747 char *buf = rs->buf;
2748 char *endbuf = rs->buf + get_remote_packet_size ();
2754 *buf++ = gen ? 'g' : 'c';
2755 if (ptid == magic_null_ptid)
2756 xsnprintf (buf, endbuf - buf, "0");
2757 else if (ptid == any_thread_ptid)
2758 xsnprintf (buf, endbuf - buf, "0");
2759 else if (ptid == minus_one_ptid)
2760 xsnprintf (buf, endbuf - buf, "-1");
2762 write_ptid (buf, endbuf, ptid);
2764 getpkt (&rs->buf, &rs->buf_size, 0);
2766 rs->general_thread = ptid;
2768 rs->continue_thread = ptid;
2772 remote_target::set_general_thread (ptid_t ptid)
2774 set_thread (ptid, 1);
2778 remote_target::set_continue_thread (ptid_t ptid)
2780 set_thread (ptid, 0);
2783 /* Change the remote current process. Which thread within the process
2784 ends up selected isn't important, as long as it is the same process
2785 as what INFERIOR_PTID points to.
2787 This comes from that fact that there is no explicit notion of
2788 "selected process" in the protocol. The selected process for
2789 general operations is the process the selected general thread
2793 remote_target::set_general_process ()
2795 struct remote_state *rs = get_remote_state ();
2797 /* If the remote can't handle multiple processes, don't bother. */
2798 if (!remote_multi_process_p (rs))
2801 /* We only need to change the remote current thread if it's pointing
2802 at some other process. */
2803 if (rs->general_thread.pid () != inferior_ptid.pid ())
2804 set_general_thread (inferior_ptid);
2808 /* Return nonzero if this is the main thread that we made up ourselves
2809 to model non-threaded targets as single-threaded. */
2812 remote_thread_always_alive (ptid_t ptid)
2814 if (ptid == magic_null_ptid)
2815 /* The main thread is always alive. */
2818 if (ptid.pid () != 0 && ptid.lwp () == 0)
2819 /* The main thread is always alive. This can happen after a
2820 vAttach, if the remote side doesn't support
2827 /* Return nonzero if the thread PTID is still alive on the remote
2831 remote_target::thread_alive (ptid_t ptid)
2833 struct remote_state *rs = get_remote_state ();
2836 /* Check if this is a thread that we made up ourselves to model
2837 non-threaded targets as single-threaded. */
2838 if (remote_thread_always_alive (ptid))
2842 endp = rs->buf + get_remote_packet_size ();
2845 write_ptid (p, endp, ptid);
2848 getpkt (&rs->buf, &rs->buf_size, 0);
2849 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
2852 /* Return a pointer to a thread name if we know it and NULL otherwise.
2853 The thread_info object owns the memory for the name. */
2856 remote_target::thread_name (struct thread_info *info)
2858 if (info->priv != NULL)
2860 const std::string &name = get_remote_thread_info (info)->name;
2861 return !name.empty () ? name.c_str () : NULL;
2867 /* About these extended threadlist and threadinfo packets. They are
2868 variable length packets but, the fields within them are often fixed
2869 length. They are redundent enough to send over UDP as is the
2870 remote protocol in general. There is a matching unit test module
2873 /* WARNING: This threadref data structure comes from the remote O.S.,
2874 libstub protocol encoding, and remote.c. It is not particularly
2877 /* Right now, the internal structure is int. We want it to be bigger.
2878 Plan to fix this. */
2880 typedef int gdb_threadref; /* Internal GDB thread reference. */
2882 /* gdb_ext_thread_info is an internal GDB data structure which is
2883 equivalent to the reply of the remote threadinfo packet. */
2885 struct gdb_ext_thread_info
2887 threadref threadid; /* External form of thread reference. */
2888 int active; /* Has state interesting to GDB?
2890 char display[256]; /* Brief state display, name,
2891 blocked/suspended. */
2892 char shortname[32]; /* To be used to name threads. */
2893 char more_display[256]; /* Long info, statistics, queue depth,
2897 /* The volume of remote transfers can be limited by submitting
2898 a mask containing bits specifying the desired information.
2899 Use a union of these values as the 'selection' parameter to
2900 get_thread_info. FIXME: Make these TAG names more thread specific. */
2902 #define TAG_THREADID 1
2903 #define TAG_EXISTS 2
2904 #define TAG_DISPLAY 4
2905 #define TAG_THREADNAME 8
2906 #define TAG_MOREDISPLAY 16
2908 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
2910 static char *unpack_nibble (char *buf, int *val);
2912 static char *unpack_byte (char *buf, int *value);
2914 static char *pack_int (char *buf, int value);
2916 static char *unpack_int (char *buf, int *value);
2918 static char *unpack_string (char *src, char *dest, int length);
2920 static char *pack_threadid (char *pkt, threadref *id);
2922 static char *unpack_threadid (char *inbuf, threadref *id);
2924 void int_to_threadref (threadref *id, int value);
2926 static int threadref_to_int (threadref *ref);
2928 static void copy_threadref (threadref *dest, threadref *src);
2930 static int threadmatch (threadref *dest, threadref *src);
2932 static char *pack_threadinfo_request (char *pkt, int mode,
2935 static char *pack_threadlist_request (char *pkt, int startflag,
2937 threadref *nextthread);
2939 static int remote_newthread_step (threadref *ref, void *context);
2942 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
2943 buffer we're allowed to write to. Returns
2944 BUF+CHARACTERS_WRITTEN. */
2947 remote_target::write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2950 struct remote_state *rs = get_remote_state ();
2952 if (remote_multi_process_p (rs))
2956 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2958 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2962 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2964 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2969 /* Extract a PTID from BUF. If non-null, OBUF is set to one past the
2970 last parsed char. Returns null_ptid if no thread id is found, and
2971 throws an error if the thread id has an invalid format. */
2974 read_ptid (const char *buf, const char **obuf)
2976 const char *p = buf;
2978 ULONGEST pid = 0, tid = 0;
2982 /* Multi-process ptid. */
2983 pp = unpack_varlen_hex (p + 1, &pid);
2985 error (_("invalid remote ptid: %s"), p);
2988 pp = unpack_varlen_hex (p + 1, &tid);
2991 return ptid_t (pid, tid, 0);
2994 /* No multi-process. Just a tid. */
2995 pp = unpack_varlen_hex (p, &tid);
2997 /* Return null_ptid when no thread id is found. */
3005 /* Since the stub is not sending a process id, then default to
3006 what's in inferior_ptid, unless it's null at this point. If so,
3007 then since there's no way to know the pid of the reported
3008 threads, use the magic number. */
3009 if (inferior_ptid == null_ptid)
3010 pid = magic_null_ptid.pid ();
3012 pid = inferior_ptid.pid ();
3016 return ptid_t (pid, tid, 0);
3022 if (ch >= 'a' && ch <= 'f')
3023 return ch - 'a' + 10;
3024 if (ch >= '0' && ch <= '9')
3026 if (ch >= 'A' && ch <= 'F')
3027 return ch - 'A' + 10;
3032 stub_unpack_int (char *buff, int fieldlength)
3039 nibble = stubhex (*buff++);
3043 retval = retval << 4;
3049 unpack_nibble (char *buf, int *val)
3051 *val = fromhex (*buf++);
3056 unpack_byte (char *buf, int *value)
3058 *value = stub_unpack_int (buf, 2);
3063 pack_int (char *buf, int value)
3065 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
3066 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
3067 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
3068 buf = pack_hex_byte (buf, (value & 0xff));
3073 unpack_int (char *buf, int *value)
3075 *value = stub_unpack_int (buf, 8);
3079 #if 0 /* Currently unused, uncomment when needed. */
3080 static char *pack_string (char *pkt, char *string);
3083 pack_string (char *pkt, char *string)
3088 len = strlen (string);
3090 len = 200; /* Bigger than most GDB packets, junk??? */
3091 pkt = pack_hex_byte (pkt, len);
3095 if ((ch == '\0') || (ch == '#'))
3096 ch = '*'; /* Protect encapsulation. */
3101 #endif /* 0 (unused) */
3104 unpack_string (char *src, char *dest, int length)
3113 pack_threadid (char *pkt, threadref *id)
3116 unsigned char *altid;
3118 altid = (unsigned char *) id;
3119 limit = pkt + BUF_THREAD_ID_SIZE;
3121 pkt = pack_hex_byte (pkt, *altid++);
3127 unpack_threadid (char *inbuf, threadref *id)
3130 char *limit = inbuf + BUF_THREAD_ID_SIZE;
3133 altref = (char *) id;
3135 while (inbuf < limit)
3137 x = stubhex (*inbuf++);
3138 y = stubhex (*inbuf++);
3139 *altref++ = (x << 4) | y;
3144 /* Externally, threadrefs are 64 bits but internally, they are still
3145 ints. This is due to a mismatch of specifications. We would like
3146 to use 64bit thread references internally. This is an adapter
3150 int_to_threadref (threadref *id, int value)
3152 unsigned char *scan;
3154 scan = (unsigned char *) id;
3160 *scan++ = (value >> 24) & 0xff;
3161 *scan++ = (value >> 16) & 0xff;
3162 *scan++ = (value >> 8) & 0xff;
3163 *scan++ = (value & 0xff);
3167 threadref_to_int (threadref *ref)
3170 unsigned char *scan;
3176 value = (value << 8) | ((*scan++) & 0xff);
3181 copy_threadref (threadref *dest, threadref *src)
3184 unsigned char *csrc, *cdest;
3186 csrc = (unsigned char *) src;
3187 cdest = (unsigned char *) dest;
3194 threadmatch (threadref *dest, threadref *src)
3196 /* Things are broken right now, so just assume we got a match. */
3198 unsigned char *srcp, *destp;
3200 srcp = (char *) src;
3201 destp = (char *) dest;
3205 result &= (*srcp++ == *destp++) ? 1 : 0;
3212 threadid:1, # always request threadid
3219 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
3222 pack_threadinfo_request (char *pkt, int mode, threadref *id)
3224 *pkt++ = 'q'; /* Info Query */
3225 *pkt++ = 'P'; /* process or thread info */
3226 pkt = pack_int (pkt, mode); /* mode */
3227 pkt = pack_threadid (pkt, id); /* threadid */
3228 *pkt = '\0'; /* terminate */
3232 /* These values tag the fields in a thread info response packet. */
3233 /* Tagging the fields allows us to request specific fields and to
3234 add more fields as time goes by. */
3236 #define TAG_THREADID 1 /* Echo the thread identifier. */
3237 #define TAG_EXISTS 2 /* Is this process defined enough to
3238 fetch registers and its stack? */
3239 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
3240 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
3241 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
3245 remote_target::remote_unpack_thread_info_response (char *pkt,
3246 threadref *expectedref,
3247 gdb_ext_thread_info *info)
3249 struct remote_state *rs = get_remote_state ();
3253 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
3256 /* info->threadid = 0; FIXME: implement zero_threadref. */
3258 info->display[0] = '\0';
3259 info->shortname[0] = '\0';
3260 info->more_display[0] = '\0';
3262 /* Assume the characters indicating the packet type have been
3264 pkt = unpack_int (pkt, &mask); /* arg mask */
3265 pkt = unpack_threadid (pkt, &ref);
3268 warning (_("Incomplete response to threadinfo request."));
3269 if (!threadmatch (&ref, expectedref))
3270 { /* This is an answer to a different request. */
3271 warning (_("ERROR RMT Thread info mismatch."));
3274 copy_threadref (&info->threadid, &ref);
3276 /* Loop on tagged fields , try to bail if somthing goes wrong. */
3278 /* Packets are terminated with nulls. */
3279 while ((pkt < limit) && mask && *pkt)
3281 pkt = unpack_int (pkt, &tag); /* tag */
3282 pkt = unpack_byte (pkt, &length); /* length */
3283 if (!(tag & mask)) /* Tags out of synch with mask. */
3285 warning (_("ERROR RMT: threadinfo tag mismatch."));
3289 if (tag == TAG_THREADID)
3293 warning (_("ERROR RMT: length of threadid is not 16."));
3297 pkt = unpack_threadid (pkt, &ref);
3298 mask = mask & ~TAG_THREADID;
3301 if (tag == TAG_EXISTS)
3303 info->active = stub_unpack_int (pkt, length);
3305 mask = mask & ~(TAG_EXISTS);
3308 warning (_("ERROR RMT: 'exists' length too long."));
3314 if (tag == TAG_THREADNAME)
3316 pkt = unpack_string (pkt, &info->shortname[0], length);
3317 mask = mask & ~TAG_THREADNAME;
3320 if (tag == TAG_DISPLAY)
3322 pkt = unpack_string (pkt, &info->display[0], length);
3323 mask = mask & ~TAG_DISPLAY;
3326 if (tag == TAG_MOREDISPLAY)
3328 pkt = unpack_string (pkt, &info->more_display[0], length);
3329 mask = mask & ~TAG_MOREDISPLAY;
3332 warning (_("ERROR RMT: unknown thread info tag."));
3333 break; /* Not a tag we know about. */
3339 remote_target::remote_get_threadinfo (threadref *threadid,
3341 gdb_ext_thread_info *info)
3343 struct remote_state *rs = get_remote_state ();
3346 pack_threadinfo_request (rs->buf, fieldset, threadid);
3348 getpkt (&rs->buf, &rs->buf_size, 0);
3350 if (rs->buf[0] == '\0')
3353 result = remote_unpack_thread_info_response (rs->buf + 2,
3358 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
3361 pack_threadlist_request (char *pkt, int startflag, int threadcount,
3362 threadref *nextthread)
3364 *pkt++ = 'q'; /* info query packet */
3365 *pkt++ = 'L'; /* Process LIST or threadLIST request */
3366 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
3367 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
3368 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
3373 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
3376 remote_target::parse_threadlist_response (char *pkt, int result_limit,
3377 threadref *original_echo,
3378 threadref *resultlist,
3381 struct remote_state *rs = get_remote_state ();
3383 int count, resultcount, done;
3386 /* Assume the 'q' and 'M chars have been stripped. */
3387 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
3388 /* done parse past here */
3389 pkt = unpack_byte (pkt, &count); /* count field */
3390 pkt = unpack_nibble (pkt, &done);
3391 /* The first threadid is the argument threadid. */
3392 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
3393 while ((count-- > 0) && (pkt < limit))
3395 pkt = unpack_threadid (pkt, resultlist++);
3396 if (resultcount++ >= result_limit)
3404 /* Fetch the next batch of threads from the remote. Returns -1 if the
3405 qL packet is not supported, 0 on error and 1 on success. */
3408 remote_target::remote_get_threadlist (int startflag, threadref *nextthread,
3409 int result_limit, int *done, int *result_count,
3410 threadref *threadlist)
3412 struct remote_state *rs = get_remote_state ();
3415 /* Trancate result limit to be smaller than the packet size. */
3416 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
3417 >= get_remote_packet_size ())
3418 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
3420 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
3422 getpkt (&rs->buf, &rs->buf_size, 0);
3423 if (*rs->buf == '\0')
3425 /* Packet not supported. */
3430 parse_threadlist_response (rs->buf + 2, result_limit,
3431 &rs->echo_nextthread, threadlist, done);
3433 if (!threadmatch (&rs->echo_nextthread, nextthread))
3435 /* FIXME: This is a good reason to drop the packet. */
3436 /* Possably, there is a duplicate response. */
3438 retransmit immediatly - race conditions
3439 retransmit after timeout - yes
3441 wait for packet, then exit
3443 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
3444 return 0; /* I choose simply exiting. */
3446 if (*result_count <= 0)
3450 warning (_("RMT ERROR : failed to get remote thread list."));
3453 return result; /* break; */
3455 if (*result_count > result_limit)
3458 warning (_("RMT ERROR: threadlist response longer than requested."));
3464 /* Fetch the list of remote threads, with the qL packet, and call
3465 STEPFUNCTION for each thread found. Stops iterating and returns 1
3466 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
3467 STEPFUNCTION returns false. If the packet is not supported,
3471 remote_target::remote_threadlist_iterator (rmt_thread_action stepfunction,
3472 void *context, int looplimit)
3474 struct remote_state *rs = get_remote_state ();
3475 int done, i, result_count;
3483 if (loopcount++ > looplimit)
3486 warning (_("Remote fetch threadlist -infinite loop-."));
3489 result = remote_get_threadlist (startflag, &rs->nextthread,
3490 MAXTHREADLISTRESULTS,
3491 &done, &result_count,
3492 rs->resultthreadlist);
3495 /* Clear for later iterations. */
3497 /* Setup to resume next batch of thread references, set nextthread. */
3498 if (result_count >= 1)
3499 copy_threadref (&rs->nextthread,
3500 &rs->resultthreadlist[result_count - 1]);
3502 while (result_count--)
3504 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
3514 /* A thread found on the remote target. */
3518 explicit thread_item (ptid_t ptid_)
3522 thread_item (thread_item &&other) = default;
3523 thread_item &operator= (thread_item &&other) = default;
3525 DISABLE_COPY_AND_ASSIGN (thread_item);
3527 /* The thread's PTID. */
3530 /* The thread's extra info. */
3533 /* The thread's name. */
3536 /* The core the thread was running on. -1 if not known. */
3539 /* The thread handle associated with the thread. */
3540 gdb::byte_vector thread_handle;
3543 /* Context passed around to the various methods listing remote
3544 threads. As new threads are found, they're added to the ITEMS
3547 struct threads_listing_context
3549 /* Return true if this object contains an entry for a thread with ptid
3552 bool contains_thread (ptid_t ptid) const
3554 auto match_ptid = [&] (const thread_item &item)
3556 return item.ptid == ptid;
3559 auto it = std::find_if (this->items.begin (),
3563 return it != this->items.end ();
3566 /* Remove the thread with ptid PTID. */
3568 void remove_thread (ptid_t ptid)
3570 auto match_ptid = [&] (const thread_item &item)
3572 return item.ptid == ptid;
3575 auto it = std::remove_if (this->items.begin (),
3579 if (it != this->items.end ())
3580 this->items.erase (it);
3583 /* The threads found on the remote target. */
3584 std::vector<thread_item> items;
3588 remote_newthread_step (threadref *ref, void *data)
3590 struct threads_listing_context *context
3591 = (struct threads_listing_context *) data;
3592 int pid = inferior_ptid.pid ();
3593 int lwp = threadref_to_int (ref);
3594 ptid_t ptid (pid, lwp);
3596 context->items.emplace_back (ptid);
3598 return 1; /* continue iterator */
3601 #define CRAZY_MAX_THREADS 1000
3604 remote_target::remote_current_thread (ptid_t oldpid)
3606 struct remote_state *rs = get_remote_state ();
3609 getpkt (&rs->buf, &rs->buf_size, 0);
3610 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
3615 result = read_ptid (&rs->buf[2], &obuf);
3616 if (*obuf != '\0' && remote_debug)
3617 fprintf_unfiltered (gdb_stdlog,
3618 "warning: garbage in qC reply\n");
3626 /* List remote threads using the deprecated qL packet. */
3629 remote_target::remote_get_threads_with_ql (threads_listing_context *context)
3631 if (remote_threadlist_iterator (remote_newthread_step, context,
3632 CRAZY_MAX_THREADS) >= 0)
3638 #if defined(HAVE_LIBEXPAT)
3641 start_thread (struct gdb_xml_parser *parser,
3642 const struct gdb_xml_element *element,
3644 std::vector<gdb_xml_value> &attributes)
3646 struct threads_listing_context *data
3647 = (struct threads_listing_context *) user_data;
3648 struct gdb_xml_value *attr;
3650 char *id = (char *) xml_find_attribute (attributes, "id")->value.get ();
3651 ptid_t ptid = read_ptid (id, NULL);
3653 data->items.emplace_back (ptid);
3654 thread_item &item = data->items.back ();
3656 attr = xml_find_attribute (attributes, "core");
3658 item.core = *(ULONGEST *) attr->value.get ();
3660 attr = xml_find_attribute (attributes, "name");
3662 item.name = (const char *) attr->value.get ();
3664 attr = xml_find_attribute (attributes, "handle");
3666 item.thread_handle = hex2bin ((const char *) attr->value.get ());
3670 end_thread (struct gdb_xml_parser *parser,
3671 const struct gdb_xml_element *element,
3672 void *user_data, const char *body_text)
3674 struct threads_listing_context *data
3675 = (struct threads_listing_context *) user_data;
3677 if (body_text != NULL && *body_text != '\0')
3678 data->items.back ().extra = body_text;
3681 const struct gdb_xml_attribute thread_attributes[] = {
3682 { "id", GDB_XML_AF_NONE, NULL, NULL },
3683 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
3684 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
3685 { "handle", GDB_XML_AF_OPTIONAL, NULL, NULL },
3686 { NULL, GDB_XML_AF_NONE, NULL, NULL }
3689 const struct gdb_xml_element thread_children[] = {
3690 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3693 const struct gdb_xml_element threads_children[] = {
3694 { "thread", thread_attributes, thread_children,
3695 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3696 start_thread, end_thread },
3697 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3700 const struct gdb_xml_element threads_elements[] = {
3701 { "threads", NULL, threads_children,
3702 GDB_XML_EF_NONE, NULL, NULL },
3703 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3708 /* List remote threads using qXfer:threads:read. */
3711 remote_target::remote_get_threads_with_qxfer (threads_listing_context *context)
3713 #if defined(HAVE_LIBEXPAT)
3714 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3716 gdb::optional<gdb::char_vector> xml
3717 = target_read_stralloc (this, TARGET_OBJECT_THREADS, NULL);
3719 if (xml && (*xml)[0] != '\0')
3721 gdb_xml_parse_quick (_("threads"), "threads.dtd",
3722 threads_elements, xml->data (), context);
3732 /* List remote threads using qfThreadInfo/qsThreadInfo. */
3735 remote_target::remote_get_threads_with_qthreadinfo (threads_listing_context *context)
3737 struct remote_state *rs = get_remote_state ();
3739 if (rs->use_threadinfo_query)
3743 putpkt ("qfThreadInfo");
3744 getpkt (&rs->buf, &rs->buf_size, 0);
3746 if (bufp[0] != '\0') /* q packet recognized */
3748 while (*bufp++ == 'm') /* reply contains one or more TID */
3752 ptid_t ptid = read_ptid (bufp, &bufp);
3753 context->items.emplace_back (ptid);
3755 while (*bufp++ == ','); /* comma-separated list */
3756 putpkt ("qsThreadInfo");
3757 getpkt (&rs->buf, &rs->buf_size, 0);
3764 /* Packet not recognized. */
3765 rs->use_threadinfo_query = 0;
3772 /* Implement the to_update_thread_list function for the remote
3776 remote_target::update_thread_list ()
3778 struct threads_listing_context context;
3781 /* We have a few different mechanisms to fetch the thread list. Try
3782 them all, starting with the most preferred one first, falling
3783 back to older methods. */
3784 if (remote_get_threads_with_qxfer (&context)
3785 || remote_get_threads_with_qthreadinfo (&context)
3786 || remote_get_threads_with_ql (&context))
3788 struct thread_info *tp, *tmp;
3792 if (context.items.empty ()
3793 && remote_thread_always_alive (inferior_ptid))
3795 /* Some targets don't really support threads, but still
3796 reply an (empty) thread list in response to the thread
3797 listing packets, instead of replying "packet not
3798 supported". Exit early so we don't delete the main
3803 /* CONTEXT now holds the current thread list on the remote
3804 target end. Delete GDB-side threads no longer found on the
3806 ALL_THREADS_SAFE (tp, tmp)
3808 if (!context.contains_thread (tp->ptid))
3815 /* Remove any unreported fork child threads from CONTEXT so
3816 that we don't interfere with follow fork, which is where
3817 creation of such threads is handled. */
3818 remove_new_fork_children (&context);
3820 /* And now add threads we don't know about yet to our list. */
3821 for (thread_item &item : context.items)
3823 if (item.ptid != null_ptid)
3825 /* In non-stop mode, we assume new found threads are
3826 executing until proven otherwise with a stop reply.
3827 In all-stop, we can only get here if all threads are
3829 int executing = target_is_non_stop_p () ? 1 : 0;
3831 remote_notice_new_inferior (item.ptid, executing);
3833 tp = find_thread_ptid (item.ptid);
3834 remote_thread_info *info = get_remote_thread_info (tp);
3835 info->core = item.core;
3836 info->extra = std::move (item.extra);
3837 info->name = std::move (item.name);
3838 info->thread_handle = std::move (item.thread_handle);
3845 /* If no thread listing method is supported, then query whether
3846 each known thread is alive, one by one, with the T packet.
3847 If the target doesn't support threads at all, then this is a
3848 no-op. See remote_thread_alive. */
3854 * Collect a descriptive string about the given thread.
3855 * The target may say anything it wants to about the thread
3856 * (typically info about its blocked / runnable state, name, etc.).
3857 * This string will appear in the info threads display.
3859 * Optional: targets are not required to implement this function.
3863 remote_target::extra_thread_info (thread_info *tp)
3865 struct remote_state *rs = get_remote_state ();
3868 struct gdb_ext_thread_info threadinfo;
3870 if (rs->remote_desc == 0) /* paranoia */
3871 internal_error (__FILE__, __LINE__,
3872 _("remote_threads_extra_info"));
3874 if (tp->ptid == magic_null_ptid
3875 || (tp->ptid.pid () != 0 && tp->ptid.lwp () == 0))
3876 /* This is the main thread which was added by GDB. The remote
3877 server doesn't know about it. */
3880 std::string &extra = get_remote_thread_info (tp)->extra;
3882 /* If already have cached info, use it. */
3883 if (!extra.empty ())
3884 return extra.c_str ();
3886 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3888 /* If we're using qXfer:threads:read, then the extra info is
3889 included in the XML. So if we didn't have anything cached,
3890 it's because there's really no extra info. */
3894 if (rs->use_threadextra_query)
3897 char *endb = rs->buf + get_remote_packet_size ();
3899 xsnprintf (b, endb - b, "qThreadExtraInfo,");
3901 write_ptid (b, endb, tp->ptid);
3904 getpkt (&rs->buf, &rs->buf_size, 0);
3905 if (rs->buf[0] != 0)
3907 extra.resize (strlen (rs->buf) / 2);
3908 hex2bin (rs->buf, (gdb_byte *) &extra[0], extra.size ());
3909 return extra.c_str ();
3913 /* If the above query fails, fall back to the old method. */
3914 rs->use_threadextra_query = 0;
3915 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3916 | TAG_MOREDISPLAY | TAG_DISPLAY;
3917 int_to_threadref (&id, tp->ptid.lwp ());
3918 if (remote_get_threadinfo (&id, set, &threadinfo))
3919 if (threadinfo.active)
3921 if (*threadinfo.shortname)
3922 string_appendf (extra, " Name: %s", threadinfo.shortname);
3923 if (*threadinfo.display)
3925 if (!extra.empty ())
3927 string_appendf (extra, " State: %s", threadinfo.display);
3929 if (*threadinfo.more_display)
3931 if (!extra.empty ())
3933 string_appendf (extra, " Priority: %s", threadinfo.more_display);
3935 return extra.c_str ();
3942 remote_target::static_tracepoint_marker_at (CORE_ADDR addr,
3943 struct static_tracepoint_marker *marker)
3945 struct remote_state *rs = get_remote_state ();
3948 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
3950 p += hexnumstr (p, addr);
3952 getpkt (&rs->buf, &rs->buf_size, 0);
3956 error (_("Remote failure reply: %s"), p);
3960 parse_static_tracepoint_marker_definition (p, NULL, marker);
3967 std::vector<static_tracepoint_marker>
3968 remote_target::static_tracepoint_markers_by_strid (const char *strid)
3970 struct remote_state *rs = get_remote_state ();
3971 std::vector<static_tracepoint_marker> markers;
3973 static_tracepoint_marker marker;
3975 /* Ask for a first packet of static tracepoint marker
3978 getpkt (&rs->buf, &rs->buf_size, 0);
3981 error (_("Remote failure reply: %s"), p);
3987 parse_static_tracepoint_marker_definition (p, &p, &marker);
3989 if (strid == NULL || marker.str_id == strid)
3990 markers.push_back (std::move (marker));
3992 while (*p++ == ','); /* comma-separated list */
3993 /* Ask for another packet of static tracepoint definition. */
3995 getpkt (&rs->buf, &rs->buf_size, 0);
4003 /* Implement the to_get_ada_task_ptid function for the remote targets. */
4006 remote_target::get_ada_task_ptid (long lwp, long thread)
4008 return ptid_t (inferior_ptid.pid (), lwp, 0);
4012 /* Restart the remote side; this is an extended protocol operation. */
4015 remote_target::extended_remote_restart ()
4017 struct remote_state *rs = get_remote_state ();
4019 /* Send the restart command; for reasons I don't understand the
4020 remote side really expects a number after the "R". */
4021 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
4024 remote_fileio_reset ();
4027 /* Clean up connection to a remote debugger. */
4030 remote_target::close ()
4032 /* Make sure we leave stdin registered in the event loop. */
4035 /* We don't have a connection to the remote stub anymore. Get rid
4036 of all the inferiors and their threads we were controlling.
4037 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
4038 will be unable to find the thread corresponding to (pid, 0, 0). */
4039 inferior_ptid = null_ptid;
4040 discard_all_inferiors ();
4042 trace_reset_local_state ();
4047 remote_target::~remote_target ()
4049 struct remote_state *rs = get_remote_state ();
4051 /* Check for NULL because we may get here with a partially
4052 constructed target/connection. */
4053 if (rs->remote_desc == nullptr)
4056 serial_close (rs->remote_desc);
4058 /* We are destroying the remote target, so we should discard
4059 everything of this target. */
4060 discard_pending_stop_replies_in_queue ();
4062 if (rs->remote_async_inferior_event_token)
4063 delete_async_event_handler (&rs->remote_async_inferior_event_token);
4065 remote_notif_state_xfree (rs->notif_state);
4068 /* Query the remote side for the text, data and bss offsets. */
4071 remote_target::get_offsets ()
4073 struct remote_state *rs = get_remote_state ();
4076 int lose, num_segments = 0, do_sections, do_segments;
4077 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
4078 struct section_offsets *offs;
4079 struct symfile_segment_data *data;
4081 if (symfile_objfile == NULL)
4084 putpkt ("qOffsets");
4085 getpkt (&rs->buf, &rs->buf_size, 0);
4088 if (buf[0] == '\000')
4089 return; /* Return silently. Stub doesn't support
4093 warning (_("Remote failure reply: %s"), buf);
4097 /* Pick up each field in turn. This used to be done with scanf, but
4098 scanf will make trouble if CORE_ADDR size doesn't match
4099 conversion directives correctly. The following code will work
4100 with any size of CORE_ADDR. */
4101 text_addr = data_addr = bss_addr = 0;
4105 if (startswith (ptr, "Text="))
4108 /* Don't use strtol, could lose on big values. */
4109 while (*ptr && *ptr != ';')
4110 text_addr = (text_addr << 4) + fromhex (*ptr++);
4112 if (startswith (ptr, ";Data="))
4115 while (*ptr && *ptr != ';')
4116 data_addr = (data_addr << 4) + fromhex (*ptr++);
4121 if (!lose && startswith (ptr, ";Bss="))
4124 while (*ptr && *ptr != ';')
4125 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
4127 if (bss_addr != data_addr)
4128 warning (_("Target reported unsupported offsets: %s"), buf);
4133 else if (startswith (ptr, "TextSeg="))
4136 /* Don't use strtol, could lose on big values. */
4137 while (*ptr && *ptr != ';')
4138 text_addr = (text_addr << 4) + fromhex (*ptr++);
4141 if (startswith (ptr, ";DataSeg="))
4144 while (*ptr && *ptr != ';')
4145 data_addr = (data_addr << 4) + fromhex (*ptr++);
4153 error (_("Malformed response to offset query, %s"), buf);
4154 else if (*ptr != '\0')
4155 warning (_("Target reported unsupported offsets: %s"), buf);
4157 offs = ((struct section_offsets *)
4158 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
4159 memcpy (offs, symfile_objfile->section_offsets,
4160 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
4162 data = get_symfile_segment_data (symfile_objfile->obfd);
4163 do_segments = (data != NULL);
4164 do_sections = num_segments == 0;
4166 if (num_segments > 0)
4168 segments[0] = text_addr;
4169 segments[1] = data_addr;
4171 /* If we have two segments, we can still try to relocate everything
4172 by assuming that the .text and .data offsets apply to the whole
4173 text and data segments. Convert the offsets given in the packet
4174 to base addresses for symfile_map_offsets_to_segments. */
4175 else if (data && data->num_segments == 2)
4177 segments[0] = data->segment_bases[0] + text_addr;
4178 segments[1] = data->segment_bases[1] + data_addr;
4181 /* If the object file has only one segment, assume that it is text
4182 rather than data; main programs with no writable data are rare,
4183 but programs with no code are useless. Of course the code might
4184 have ended up in the data segment... to detect that we would need
4185 the permissions here. */
4186 else if (data && data->num_segments == 1)
4188 segments[0] = data->segment_bases[0] + text_addr;
4191 /* There's no way to relocate by segment. */
4197 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
4198 offs, num_segments, segments);
4200 if (ret == 0 && !do_sections)
4201 error (_("Can not handle qOffsets TextSeg "
4202 "response with this symbol file"));
4209 free_symfile_segment_data (data);
4213 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
4215 /* This is a temporary kludge to force data and bss to use the
4216 same offsets because that's what nlmconv does now. The real
4217 solution requires changes to the stub and remote.c that I
4218 don't have time to do right now. */
4220 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
4221 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
4224 objfile_relocate (symfile_objfile, offs);
4227 /* Send interrupt_sequence to remote target. */
4230 remote_target::send_interrupt_sequence ()
4232 struct remote_state *rs = get_remote_state ();
4234 if (interrupt_sequence_mode == interrupt_sequence_control_c)
4235 remote_serial_write ("\x03", 1);
4236 else if (interrupt_sequence_mode == interrupt_sequence_break)
4237 serial_send_break (rs->remote_desc);
4238 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
4240 serial_send_break (rs->remote_desc);
4241 remote_serial_write ("g", 1);
4244 internal_error (__FILE__, __LINE__,
4245 _("Invalid value for interrupt_sequence_mode: %s."),
4246 interrupt_sequence_mode);
4250 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
4251 and extract the PTID. Returns NULL_PTID if not found. */
4254 stop_reply_extract_thread (char *stop_reply)
4256 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
4260 /* Txx r:val ; r:val (...) */
4263 /* Look for "register" named "thread". */
4268 p1 = strchr (p, ':');
4272 if (strncmp (p, "thread", p1 - p) == 0)
4273 return read_ptid (++p1, &p);
4275 p1 = strchr (p, ';');
4287 /* Determine the remote side's current thread. If we have a stop
4288 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
4289 "thread" register we can extract the current thread from. If not,
4290 ask the remote which is the current thread with qC. The former
4291 method avoids a roundtrip. */
4294 remote_target::get_current_thread (char *wait_status)
4296 ptid_t ptid = null_ptid;
4298 /* Note we don't use remote_parse_stop_reply as that makes use of
4299 the target architecture, which we haven't yet fully determined at
4301 if (wait_status != NULL)
4302 ptid = stop_reply_extract_thread (wait_status);
4303 if (ptid == null_ptid)
4304 ptid = remote_current_thread (inferior_ptid);
4309 /* Query the remote target for which is the current thread/process,
4310 add it to our tables, and update INFERIOR_PTID. The caller is
4311 responsible for setting the state such that the remote end is ready
4312 to return the current thread.
4314 This function is called after handling the '?' or 'vRun' packets,
4315 whose response is a stop reply from which we can also try
4316 extracting the thread. If the target doesn't support the explicit
4317 qC query, we infer the current thread from that stop reply, passed
4318 in in WAIT_STATUS, which may be NULL. */
4321 remote_target::add_current_inferior_and_thread (char *wait_status)
4323 struct remote_state *rs = get_remote_state ();
4326 inferior_ptid = null_ptid;
4328 /* Now, if we have thread information, update inferior_ptid. */
4329 ptid_t curr_ptid = get_current_thread (wait_status);
4331 if (curr_ptid != null_ptid)
4333 if (!remote_multi_process_p (rs))
4338 /* Without this, some commands which require an active target
4339 (such as kill) won't work. This variable serves (at least)
4340 double duty as both the pid of the target process (if it has
4341 such), and as a flag indicating that a target is active. */
4342 curr_ptid = magic_null_ptid;
4346 remote_add_inferior (fake_pid_p, curr_ptid.pid (), -1, 1);
4348 /* Add the main thread and switch to it. Don't try reading
4349 registers yet, since we haven't fetched the target description
4351 thread_info *tp = add_thread_silent (curr_ptid);
4352 switch_to_thread_no_regs (tp);
4355 /* Print info about a thread that was found already stopped on
4359 print_one_stopped_thread (struct thread_info *thread)
4361 struct target_waitstatus *ws = &thread->suspend.waitstatus;
4363 switch_to_thread (thread);
4364 thread->suspend.stop_pc = get_frame_pc (get_current_frame ());
4365 set_current_sal_from_frame (get_current_frame ());
4367 thread->suspend.waitstatus_pending_p = 0;
4369 if (ws->kind == TARGET_WAITKIND_STOPPED)
4371 enum gdb_signal sig = ws->value.sig;
4373 if (signal_print_state (sig))
4374 gdb::observers::signal_received.notify (sig);
4376 gdb::observers::normal_stop.notify (NULL, 1);
4379 /* Process all initial stop replies the remote side sent in response
4380 to the ? packet. These indicate threads that were already stopped
4381 on initial connection. We mark these threads as stopped and print
4382 their current frame before giving the user the prompt. */
4385 remote_target::process_initial_stop_replies (int from_tty)
4387 int pending_stop_replies = stop_reply_queue_length ();
4388 struct inferior *inf;
4389 struct thread_info *thread;
4390 struct thread_info *selected = NULL;
4391 struct thread_info *lowest_stopped = NULL;
4392 struct thread_info *first = NULL;
4394 /* Consume the initial pending events. */
4395 while (pending_stop_replies-- > 0)
4397 ptid_t waiton_ptid = minus_one_ptid;
4399 struct target_waitstatus ws;
4400 int ignore_event = 0;
4402 memset (&ws, 0, sizeof (ws));
4403 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
4405 print_target_wait_results (waiton_ptid, event_ptid, &ws);
4409 case TARGET_WAITKIND_IGNORE:
4410 case TARGET_WAITKIND_NO_RESUMED:
4411 case TARGET_WAITKIND_SIGNALLED:
4412 case TARGET_WAITKIND_EXITED:
4413 /* We shouldn't see these, but if we do, just ignore. */
4415 fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
4419 case TARGET_WAITKIND_EXECD:
4420 xfree (ws.value.execd_pathname);
4429 struct thread_info *evthread = find_thread_ptid (event_ptid);
4431 if (ws.kind == TARGET_WAITKIND_STOPPED)
4433 enum gdb_signal sig = ws.value.sig;
4435 /* Stubs traditionally report SIGTRAP as initial signal,
4436 instead of signal 0. Suppress it. */
4437 if (sig == GDB_SIGNAL_TRAP)
4439 evthread->suspend.stop_signal = sig;
4443 evthread->suspend.waitstatus = ws;
4445 if (ws.kind != TARGET_WAITKIND_STOPPED
4446 || ws.value.sig != GDB_SIGNAL_0)
4447 evthread->suspend.waitstatus_pending_p = 1;
4449 set_executing (event_ptid, 0);
4450 set_running (event_ptid, 0);
4451 get_remote_thread_info (evthread)->vcont_resumed = 0;
4454 /* "Notice" the new inferiors before anything related to
4455 registers/memory. */
4461 inf->needs_setup = 1;
4465 thread = any_live_thread_of_inferior (inf);
4466 notice_new_inferior (thread, thread->state == THREAD_RUNNING,
4471 /* If all-stop on top of non-stop, pause all threads. Note this
4472 records the threads' stop pc, so must be done after "noticing"
4476 stop_all_threads ();
4478 /* If all threads of an inferior were already stopped, we
4479 haven't setup the inferior yet. */
4485 if (inf->needs_setup)
4487 thread = any_live_thread_of_inferior (inf);
4488 switch_to_thread_no_regs (thread);
4494 /* Now go over all threads that are stopped, and print their current
4495 frame. If all-stop, then if there's a signalled thread, pick
4497 ALL_NON_EXITED_THREADS (thread)
4503 thread->set_running (false);
4504 else if (thread->state != THREAD_STOPPED)
4507 if (selected == NULL
4508 && thread->suspend.waitstatus_pending_p)
4511 if (lowest_stopped == NULL
4512 || thread->inf->num < lowest_stopped->inf->num
4513 || thread->per_inf_num < lowest_stopped->per_inf_num)
4514 lowest_stopped = thread;
4517 print_one_stopped_thread (thread);
4520 /* In all-stop, we only print the status of one thread, and leave
4521 others with their status pending. */
4526 thread = lowest_stopped;
4530 print_one_stopped_thread (thread);
4533 /* For "info program". */
4534 thread = inferior_thread ();
4535 if (thread->state == THREAD_STOPPED)
4536 set_last_target_status (inferior_ptid, thread->suspend.waitstatus);
4539 /* Start the remote connection and sync state. */
4542 remote_target::start_remote (int from_tty, int extended_p)
4544 struct remote_state *rs = get_remote_state ();
4545 struct packet_config *noack_config;
4546 char *wait_status = NULL;
4548 /* Signal other parts that we're going through the initial setup,
4549 and so things may not be stable yet. E.g., we don't try to
4550 install tracepoints until we've relocated symbols. Also, a
4551 Ctrl-C before we're connected and synced up can't interrupt the
4552 target. Instead, it offers to drop the (potentially wedged)
4554 rs->starting_up = 1;
4558 if (interrupt_on_connect)
4559 send_interrupt_sequence ();
4561 /* Ack any packet which the remote side has already sent. */
4562 remote_serial_write ("+", 1);
4564 /* The first packet we send to the target is the optional "supported
4565 packets" request. If the target can answer this, it will tell us
4566 which later probes to skip. */
4567 remote_query_supported ();
4569 /* If the stub wants to get a QAllow, compose one and send it. */
4570 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
4573 /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
4574 unknown 'v' packet with string "OK". "OK" gets interpreted by GDB
4575 as a reply to known packet. For packet "vFile:setfs:" it is an
4576 invalid reply and GDB would return error in
4577 remote_hostio_set_filesystem, making remote files access impossible.
4578 Disable "vFile:setfs:" in such case. Do not disable other 'v' packets as
4579 other "vFile" packets get correctly detected even on gdbserver < 7.7. */
4581 const char v_mustreplyempty[] = "vMustReplyEmpty";
4583 putpkt (v_mustreplyempty);
4584 getpkt (&rs->buf, &rs->buf_size, 0);
4585 if (strcmp (rs->buf, "OK") == 0)
4586 remote_protocol_packets[PACKET_vFile_setfs].support = PACKET_DISABLE;
4587 else if (strcmp (rs->buf, "") != 0)
4588 error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
4592 /* Next, we possibly activate noack mode.
4594 If the QStartNoAckMode packet configuration is set to AUTO,
4595 enable noack mode if the stub reported a wish for it with
4598 If set to TRUE, then enable noack mode even if the stub didn't
4599 report it in qSupported. If the stub doesn't reply OK, the
4600 session ends with an error.
4602 If FALSE, then don't activate noack mode, regardless of what the
4603 stub claimed should be the default with qSupported. */
4605 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4606 if (packet_config_support (noack_config) != PACKET_DISABLE)
4608 putpkt ("QStartNoAckMode");
4609 getpkt (&rs->buf, &rs->buf_size, 0);
4610 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
4616 /* Tell the remote that we are using the extended protocol. */
4618 getpkt (&rs->buf, &rs->buf_size, 0);
4621 /* Let the target know which signals it is allowed to pass down to
4623 update_signals_program_target ();
4625 /* Next, if the target can specify a description, read it. We do
4626 this before anything involving memory or registers. */
4627 target_find_description ();
4629 /* Next, now that we know something about the target, update the
4630 address spaces in the program spaces. */
4631 update_address_spaces ();
4633 /* On OSs where the list of libraries is global to all
4634 processes, we fetch them early. */
4635 if (gdbarch_has_global_solist (target_gdbarch ()))
4636 solib_add (NULL, from_tty, auto_solib_add);
4638 if (target_is_non_stop_p ())
4640 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
4641 error (_("Non-stop mode requested, but remote "
4642 "does not support non-stop"));
4644 putpkt ("QNonStop:1");
4645 getpkt (&rs->buf, &rs->buf_size, 0);
4647 if (strcmp (rs->buf, "OK") != 0)
4648 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
4650 /* Find about threads and processes the stub is already
4651 controlling. We default to adding them in the running state.
4652 The '?' query below will then tell us about which threads are
4654 this->update_thread_list ();
4656 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
4658 /* Don't assume that the stub can operate in all-stop mode.
4659 Request it explicitly. */
4660 putpkt ("QNonStop:0");
4661 getpkt (&rs->buf, &rs->buf_size, 0);
4663 if (strcmp (rs->buf, "OK") != 0)
4664 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
4667 /* Upload TSVs regardless of whether the target is running or not. The
4668 remote stub, such as GDBserver, may have some predefined or builtin
4669 TSVs, even if the target is not running. */
4670 if (get_trace_status (current_trace_status ()) != -1)
4672 struct uploaded_tsv *uploaded_tsvs = NULL;
4674 upload_trace_state_variables (&uploaded_tsvs);
4675 merge_uploaded_trace_state_variables (&uploaded_tsvs);
4678 /* Check whether the target is running now. */
4680 getpkt (&rs->buf, &rs->buf_size, 0);
4682 if (!target_is_non_stop_p ())
4684 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
4687 error (_("The target is not running (try extended-remote?)"));
4689 /* We're connected, but not running. Drop out before we
4690 call start_remote. */
4691 rs->starting_up = 0;
4696 /* Save the reply for later. */
4697 wait_status = (char *) alloca (strlen (rs->buf) + 1);
4698 strcpy (wait_status, rs->buf);
4701 /* Fetch thread list. */
4702 target_update_thread_list ();
4704 /* Let the stub know that we want it to return the thread. */
4705 set_continue_thread (minus_one_ptid);
4707 if (thread_count () == 0)
4709 /* Target has no concept of threads at all. GDB treats
4710 non-threaded target as single-threaded; add a main
4712 add_current_inferior_and_thread (wait_status);
4716 /* We have thread information; select the thread the target
4717 says should be current. If we're reconnecting to a
4718 multi-threaded program, this will ideally be the thread
4719 that last reported an event before GDB disconnected. */
4720 inferior_ptid = get_current_thread (wait_status);
4721 if (inferior_ptid == null_ptid)
4723 /* Odd... The target was able to list threads, but not
4724 tell us which thread was current (no "thread"
4725 register in T stop reply?). Just pick the first
4726 thread in the thread list then. */
4729 fprintf_unfiltered (gdb_stdlog,
4730 "warning: couldn't determine remote "
4731 "current thread; picking first in list.\n");
4733 inferior_ptid = thread_list->ptid;
4737 /* init_wait_for_inferior should be called before get_offsets in order
4738 to manage `inserted' flag in bp loc in a correct state.
4739 breakpoint_init_inferior, called from init_wait_for_inferior, set
4740 `inserted' flag to 0, while before breakpoint_re_set, called from
4741 start_remote, set `inserted' flag to 1. In the initialization of
4742 inferior, breakpoint_init_inferior should be called first, and then
4743 breakpoint_re_set can be called. If this order is broken, state of
4744 `inserted' flag is wrong, and cause some problems on breakpoint
4746 init_wait_for_inferior ();
4748 get_offsets (); /* Get text, data & bss offsets. */
4750 /* If we could not find a description using qXfer, and we know
4751 how to do it some other way, try again. This is not
4752 supported for non-stop; it could be, but it is tricky if
4753 there are no stopped threads when we connect. */
4754 if (remote_read_description_p (this)
4755 && gdbarch_target_desc (target_gdbarch ()) == NULL)
4757 target_clear_description ();
4758 target_find_description ();
4761 /* Use the previously fetched status. */
4762 gdb_assert (wait_status != NULL);
4763 strcpy (rs->buf, wait_status);
4764 rs->cached_wait_status = 1;
4766 ::start_remote (from_tty); /* Initialize gdb process mechanisms. */
4770 /* Clear WFI global state. Do this before finding about new
4771 threads and inferiors, and setting the current inferior.
4772 Otherwise we would clear the proceed status of the current
4773 inferior when we want its stop_soon state to be preserved
4774 (see notice_new_inferior). */
4775 init_wait_for_inferior ();
4777 /* In non-stop, we will either get an "OK", meaning that there
4778 are no stopped threads at this time; or, a regular stop
4779 reply. In the latter case, there may be more than one thread
4780 stopped --- we pull them all out using the vStopped
4782 if (strcmp (rs->buf, "OK") != 0)
4784 struct notif_client *notif = ¬if_client_stop;
4786 /* remote_notif_get_pending_replies acks this one, and gets
4788 rs->notif_state->pending_event[notif_client_stop.id]
4789 = remote_notif_parse (this, notif, rs->buf);
4790 remote_notif_get_pending_events (notif);
4793 if (thread_count () == 0)
4796 error (_("The target is not running (try extended-remote?)"));
4798 /* We're connected, but not running. Drop out before we
4799 call start_remote. */
4800 rs->starting_up = 0;
4804 /* In non-stop mode, any cached wait status will be stored in
4805 the stop reply queue. */
4806 gdb_assert (wait_status == NULL);
4808 /* Report all signals during attach/startup. */
4809 pass_signals (0, NULL);
4811 /* If there are already stopped threads, mark them stopped and
4812 report their stops before giving the prompt to the user. */
4813 process_initial_stop_replies (from_tty);
4815 if (target_can_async_p ())
4819 /* If we connected to a live target, do some additional setup. */
4820 if (target_has_execution)
4822 if (symfile_objfile) /* No use without a symbol-file. */
4823 remote_check_symbols ();
4826 /* Possibly the target has been engaged in a trace run started
4827 previously; find out where things are at. */
4828 if (get_trace_status (current_trace_status ()) != -1)
4830 struct uploaded_tp *uploaded_tps = NULL;
4832 if (current_trace_status ()->running)
4833 printf_filtered (_("Trace is already running on the target.\n"));
4835 upload_tracepoints (&uploaded_tps);
4837 merge_uploaded_tracepoints (&uploaded_tps);
4840 /* Possibly the target has been engaged in a btrace record started
4841 previously; find out where things are at. */
4842 remote_btrace_maybe_reopen ();
4844 /* The thread and inferior lists are now synchronized with the
4845 target, our symbols have been relocated, and we're merged the
4846 target's tracepoints with ours. We're done with basic start
4848 rs->starting_up = 0;
4850 /* Maybe breakpoints are global and need to be inserted now. */
4851 if (breakpoints_should_be_inserted_now ())
4852 insert_breakpoints ();
4855 /* Open a connection to a remote debugger.
4856 NAME is the filename used for communication. */
4859 remote_target::open (const char *name, int from_tty)
4861 open_1 (name, from_tty, 0);
4864 /* Open a connection to a remote debugger using the extended
4865 remote gdb protocol. NAME is the filename used for communication. */
4868 extended_remote_target::open (const char *name, int from_tty)
4870 open_1 (name, from_tty, 1 /*extended_p */);
4873 /* Reset all packets back to "unknown support". Called when opening a
4874 new connection to a remote target. */
4877 reset_all_packet_configs_support (void)
4881 for (i = 0; i < PACKET_MAX; i++)
4882 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4885 /* Initialize all packet configs. */
4888 init_all_packet_configs (void)
4892 for (i = 0; i < PACKET_MAX; i++)
4894 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
4895 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4899 /* Symbol look-up. */
4902 remote_target::remote_check_symbols ()
4904 char *msg, *reply, *tmp;
4907 struct cleanup *old_chain;
4909 /* The remote side has no concept of inferiors that aren't running
4910 yet, it only knows about running processes. If we're connected
4911 but our current inferior is not running, we should not invite the
4912 remote target to request symbol lookups related to its
4913 (unrelated) current process. */
4914 if (!target_has_execution)
4917 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
4920 /* Make sure the remote is pointing at the right process. Note
4921 there's no way to select "no process". */
4922 set_general_process ();
4924 /* Allocate a message buffer. We can't reuse the input buffer in RS,
4925 because we need both at the same time. */
4926 msg = (char *) xmalloc (get_remote_packet_size ());
4927 old_chain = make_cleanup (xfree, msg);
4928 reply = (char *) xmalloc (get_remote_packet_size ());
4929 make_cleanup (free_current_contents, &reply);
4930 reply_size = get_remote_packet_size ();
4932 /* Invite target to request symbol lookups. */
4934 putpkt ("qSymbol::");
4935 getpkt (&reply, &reply_size, 0);
4936 packet_ok (reply, &remote_protocol_packets[PACKET_qSymbol]);
4938 while (startswith (reply, "qSymbol:"))
4940 struct bound_minimal_symbol sym;
4943 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
4945 sym = lookup_minimal_symbol (msg, NULL, NULL);
4946 if (sym.minsym == NULL)
4947 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
4950 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4951 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
4953 /* If this is a function address, return the start of code
4954 instead of any data function descriptor. */
4955 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
4957 current_top_target ());
4959 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
4960 phex_nz (sym_addr, addr_size), &reply[8]);
4964 getpkt (&reply, &reply_size, 0);
4967 do_cleanups (old_chain);
4970 static struct serial *
4971 remote_serial_open (const char *name)
4973 static int udp_warning = 0;
4975 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
4976 of in ser-tcp.c, because it is the remote protocol assuming that the
4977 serial connection is reliable and not the serial connection promising
4979 if (!udp_warning && startswith (name, "udp:"))
4981 warning (_("The remote protocol may be unreliable over UDP.\n"
4982 "Some events may be lost, rendering further debugging "
4987 return serial_open (name);
4990 /* Inform the target of our permission settings. The permission flags
4991 work without this, but if the target knows the settings, it can do
4992 a couple things. First, it can add its own check, to catch cases
4993 that somehow manage to get by the permissions checks in target
4994 methods. Second, if the target is wired to disallow particular
4995 settings (for instance, a system in the field that is not set up to
4996 be able to stop at a breakpoint), it can object to any unavailable
5000 remote_target::set_permissions ()
5002 struct remote_state *rs = get_remote_state ();
5004 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
5005 "WriteReg:%x;WriteMem:%x;"
5006 "InsertBreak:%x;InsertTrace:%x;"
5007 "InsertFastTrace:%x;Stop:%x",
5008 may_write_registers, may_write_memory,
5009 may_insert_breakpoints, may_insert_tracepoints,
5010 may_insert_fast_tracepoints, may_stop);
5012 getpkt (&rs->buf, &rs->buf_size, 0);
5014 /* If the target didn't like the packet, warn the user. Do not try
5015 to undo the user's settings, that would just be maddening. */
5016 if (strcmp (rs->buf, "OK") != 0)
5017 warning (_("Remote refused setting permissions with: %s"), rs->buf);
5020 /* This type describes each known response to the qSupported
5022 struct protocol_feature
5024 /* The name of this protocol feature. */
5027 /* The default for this protocol feature. */
5028 enum packet_support default_support;
5030 /* The function to call when this feature is reported, or after
5031 qSupported processing if the feature is not supported.
5032 The first argument points to this structure. The second
5033 argument indicates whether the packet requested support be
5034 enabled, disabled, or probed (or the default, if this function
5035 is being called at the end of processing and this feature was
5036 not reported). The third argument may be NULL; if not NULL, it
5037 is a NUL-terminated string taken from the packet following
5038 this feature's name and an equals sign. */
5039 void (*func) (remote_target *remote, const struct protocol_feature *,
5040 enum packet_support, const char *);
5042 /* The corresponding packet for this feature. Only used if
5043 FUNC is remote_supported_packet. */
5048 remote_supported_packet (remote_target *remote,
5049 const struct protocol_feature *feature,
5050 enum packet_support support,
5051 const char *argument)
5055 warning (_("Remote qSupported response supplied an unexpected value for"
5056 " \"%s\"."), feature->name);
5060 remote_protocol_packets[feature->packet].support = support;
5064 remote_target::remote_packet_size (const protocol_feature *feature,
5065 enum packet_support support, const char *value)
5067 struct remote_state *rs = get_remote_state ();
5072 if (support != PACKET_ENABLE)
5075 if (value == NULL || *value == '\0')
5077 warning (_("Remote target reported \"%s\" without a size."),
5083 packet_size = strtol (value, &value_end, 16);
5084 if (errno != 0 || *value_end != '\0' || packet_size < 0)
5086 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
5087 feature->name, value);
5091 /* Record the new maximum packet size. */
5092 rs->explicit_packet_size = packet_size;
5096 remote_packet_size (remote_target *remote, const protocol_feature *feature,
5097 enum packet_support support, const char *value)
5099 remote->remote_packet_size (feature, support, value);
5102 static const struct protocol_feature remote_protocol_features[] = {
5103 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
5104 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
5105 PACKET_qXfer_auxv },
5106 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
5107 PACKET_qXfer_exec_file },
5108 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
5109 PACKET_qXfer_features },
5110 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
5111 PACKET_qXfer_libraries },
5112 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
5113 PACKET_qXfer_libraries_svr4 },
5114 { "augmented-libraries-svr4-read", PACKET_DISABLE,
5115 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
5116 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
5117 PACKET_qXfer_memory_map },
5118 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
5119 PACKET_qXfer_spu_read },
5120 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
5121 PACKET_qXfer_spu_write },
5122 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
5123 PACKET_qXfer_osdata },
5124 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
5125 PACKET_qXfer_threads },
5126 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
5127 PACKET_qXfer_traceframe_info },
5128 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
5129 PACKET_QPassSignals },
5130 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
5131 PACKET_QCatchSyscalls },
5132 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
5133 PACKET_QProgramSignals },
5134 { "QSetWorkingDir", PACKET_DISABLE, remote_supported_packet,
5135 PACKET_QSetWorkingDir },
5136 { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
5137 PACKET_QStartupWithShell },
5138 { "QEnvironmentHexEncoded", PACKET_DISABLE, remote_supported_packet,
5139 PACKET_QEnvironmentHexEncoded },
5140 { "QEnvironmentReset", PACKET_DISABLE, remote_supported_packet,
5141 PACKET_QEnvironmentReset },
5142 { "QEnvironmentUnset", PACKET_DISABLE, remote_supported_packet,
5143 PACKET_QEnvironmentUnset },
5144 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
5145 PACKET_QStartNoAckMode },
5146 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
5147 PACKET_multiprocess_feature },
5148 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
5149 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
5150 PACKET_qXfer_siginfo_read },
5151 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
5152 PACKET_qXfer_siginfo_write },
5153 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
5154 PACKET_ConditionalTracepoints },
5155 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
5156 PACKET_ConditionalBreakpoints },
5157 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
5158 PACKET_BreakpointCommands },
5159 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
5160 PACKET_FastTracepoints },
5161 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
5162 PACKET_StaticTracepoints },
5163 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
5164 PACKET_InstallInTrace},
5165 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
5166 PACKET_DisconnectedTracing_feature },
5167 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
5169 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
5171 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
5172 PACKET_TracepointSource },
5173 { "QAllow", PACKET_DISABLE, remote_supported_packet,
5175 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
5176 PACKET_EnableDisableTracepoints_feature },
5177 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
5178 PACKET_qXfer_fdpic },
5179 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
5181 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
5182 PACKET_QDisableRandomization },
5183 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
5184 { "QTBuffer:size", PACKET_DISABLE,
5185 remote_supported_packet, PACKET_QTBuffer_size},
5186 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
5187 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
5188 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
5189 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
5190 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
5191 PACKET_qXfer_btrace },
5192 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
5193 PACKET_qXfer_btrace_conf },
5194 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
5195 PACKET_Qbtrace_conf_bts_size },
5196 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
5197 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
5198 { "fork-events", PACKET_DISABLE, remote_supported_packet,
5199 PACKET_fork_event_feature },
5200 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
5201 PACKET_vfork_event_feature },
5202 { "exec-events", PACKET_DISABLE, remote_supported_packet,
5203 PACKET_exec_event_feature },
5204 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
5205 PACKET_Qbtrace_conf_pt_size },
5206 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
5207 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
5208 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
5211 static char *remote_support_xml;
5213 /* Register string appended to "xmlRegisters=" in qSupported query. */
5216 register_remote_support_xml (const char *xml)
5218 #if defined(HAVE_LIBEXPAT)
5219 if (remote_support_xml == NULL)
5220 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
5223 char *copy = xstrdup (remote_support_xml + 13);
5224 char *p = strtok (copy, ",");
5228 if (strcmp (p, xml) == 0)
5235 while ((p = strtok (NULL, ",")) != NULL);
5238 remote_support_xml = reconcat (remote_support_xml,
5239 remote_support_xml, ",", xml,
5246 remote_query_supported_append (std::string *msg, const char *append)
5250 msg->append (append);
5254 remote_target::remote_query_supported ()
5256 struct remote_state *rs = get_remote_state ();
5259 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
5261 /* The packet support flags are handled differently for this packet
5262 than for most others. We treat an error, a disabled packet, and
5263 an empty response identically: any features which must be reported
5264 to be used will be automatically disabled. An empty buffer
5265 accomplishes this, since that is also the representation for a list
5266 containing no features. */
5269 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
5273 if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
5274 remote_query_supported_append (&q, "multiprocess+");
5276 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
5277 remote_query_supported_append (&q, "swbreak+");
5278 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
5279 remote_query_supported_append (&q, "hwbreak+");
5281 remote_query_supported_append (&q, "qRelocInsn+");
5283 if (packet_set_cmd_state (PACKET_fork_event_feature)
5284 != AUTO_BOOLEAN_FALSE)
5285 remote_query_supported_append (&q, "fork-events+");
5286 if (packet_set_cmd_state (PACKET_vfork_event_feature)
5287 != AUTO_BOOLEAN_FALSE)
5288 remote_query_supported_append (&q, "vfork-events+");
5289 if (packet_set_cmd_state (PACKET_exec_event_feature)
5290 != AUTO_BOOLEAN_FALSE)
5291 remote_query_supported_append (&q, "exec-events+");
5293 if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
5294 remote_query_supported_append (&q, "vContSupported+");
5296 if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
5297 remote_query_supported_append (&q, "QThreadEvents+");
5299 if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
5300 remote_query_supported_append (&q, "no-resumed+");
5302 /* Keep this one last to work around a gdbserver <= 7.10 bug in
5303 the qSupported:xmlRegisters=i386 handling. */
5304 if (remote_support_xml != NULL
5305 && packet_support (PACKET_qXfer_features) != PACKET_DISABLE)
5306 remote_query_supported_append (&q, remote_support_xml);
5308 q = "qSupported:" + q;
5309 putpkt (q.c_str ());
5311 getpkt (&rs->buf, &rs->buf_size, 0);
5313 /* If an error occured, warn, but do not return - just reset the
5314 buffer to empty and go on to disable features. */
5315 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
5318 warning (_("Remote failure reply: %s"), rs->buf);
5323 memset (seen, 0, sizeof (seen));
5328 enum packet_support is_supported;
5329 char *p, *end, *name_end, *value;
5331 /* First separate out this item from the rest of the packet. If
5332 there's another item after this, we overwrite the separator
5333 (terminated strings are much easier to work with). */
5335 end = strchr (p, ';');
5338 end = p + strlen (p);
5348 warning (_("empty item in \"qSupported\" response"));
5353 name_end = strchr (p, '=');
5356 /* This is a name=value entry. */
5357 is_supported = PACKET_ENABLE;
5358 value = name_end + 1;
5367 is_supported = PACKET_ENABLE;
5371 is_supported = PACKET_DISABLE;
5375 is_supported = PACKET_SUPPORT_UNKNOWN;
5379 warning (_("unrecognized item \"%s\" "
5380 "in \"qSupported\" response"), p);
5386 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5387 if (strcmp (remote_protocol_features[i].name, p) == 0)
5389 const struct protocol_feature *feature;
5392 feature = &remote_protocol_features[i];
5393 feature->func (this, feature, is_supported, value);
5398 /* If we increased the packet size, make sure to increase the global
5399 buffer size also. We delay this until after parsing the entire
5400 qSupported packet, because this is the same buffer we were
5402 if (rs->buf_size < rs->explicit_packet_size)
5404 rs->buf_size = rs->explicit_packet_size;
5405 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
5408 /* Handle the defaults for unmentioned features. */
5409 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5412 const struct protocol_feature *feature;
5414 feature = &remote_protocol_features[i];
5415 feature->func (this, feature, feature->default_support, NULL);
5419 /* Serial QUIT handler for the remote serial descriptor.
5421 Defers handling a Ctrl-C until we're done with the current
5422 command/response packet sequence, unless:
5424 - We're setting up the connection. Don't send a remote interrupt
5425 request, as we're not fully synced yet. Quit immediately
5428 - The target has been resumed in the foreground
5429 (target_terminal::is_ours is false) with a synchronous resume
5430 packet, and we're blocked waiting for the stop reply, thus a
5431 Ctrl-C should be immediately sent to the target.
5433 - We get a second Ctrl-C while still within the same serial read or
5434 write. In that case the serial is seemingly wedged --- offer to
5437 - We see a second Ctrl-C without target response, after having
5438 previously interrupted the target. In that case the target/stub
5439 is probably wedged --- offer to quit/disconnect.
5443 remote_target::remote_serial_quit_handler ()
5445 struct remote_state *rs = get_remote_state ();
5447 if (check_quit_flag ())
5449 /* If we're starting up, we're not fully synced yet. Quit
5451 if (rs->starting_up)
5453 else if (rs->got_ctrlc_during_io)
5455 if (query (_("The target is not responding to GDB commands.\n"
5456 "Stop debugging it? ")))
5457 remote_unpush_and_throw ();
5459 /* If ^C has already been sent once, offer to disconnect. */
5460 else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
5462 /* All-stop protocol, and blocked waiting for stop reply. Send
5463 an interrupt request. */
5464 else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
5465 target_interrupt ();
5467 rs->got_ctrlc_during_io = 1;
5471 /* The remote_target that is current while the quit handler is
5472 overridden with remote_serial_quit_handler. */
5473 static remote_target *curr_quit_handler_target;
5476 remote_serial_quit_handler ()
5478 curr_quit_handler_target->remote_serial_quit_handler ();
5481 /* Remove any of the remote.c targets from target stack. Upper targets depend
5482 on it so remove them first. */
5485 remote_unpush_target (void)
5487 pop_all_targets_at_and_above (process_stratum);
5491 remote_unpush_and_throw (void)
5493 remote_unpush_target ();
5494 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5498 remote_target::open_1 (const char *name, int from_tty, int extended_p)
5500 remote_target *curr_remote = get_current_remote_target ();
5503 error (_("To open a remote debug connection, you need to specify what\n"
5504 "serial device is attached to the remote system\n"
5505 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
5507 /* If we're connected to a running target, target_preopen will kill it.
5508 Ask this question first, before target_preopen has a chance to kill
5510 if (curr_remote != NULL && !have_inferiors ())
5513 && !query (_("Already connected to a remote target. Disconnect? ")))
5514 error (_("Still connected."));
5517 /* Here the possibly existing remote target gets unpushed. */
5518 target_preopen (from_tty);
5520 remote_fileio_reset ();
5521 reopen_exec_file ();
5524 remote_target *remote
5525 = (extended_p ? new extended_remote_target () : new remote_target ());
5526 target_ops_up target_holder (remote);
5528 remote_state *rs = remote->get_remote_state ();
5530 /* See FIXME above. */
5531 if (!target_async_permitted)
5532 rs->wait_forever_enabled_p = 1;
5534 rs->remote_desc = remote_serial_open (name);
5535 if (!rs->remote_desc)
5536 perror_with_name (name);
5538 if (baud_rate != -1)
5540 if (serial_setbaudrate (rs->remote_desc, baud_rate))
5542 /* The requested speed could not be set. Error out to
5543 top level after closing remote_desc. Take care to
5544 set remote_desc to NULL to avoid closing remote_desc
5546 serial_close (rs->remote_desc);
5547 rs->remote_desc = NULL;
5548 perror_with_name (name);
5552 serial_setparity (rs->remote_desc, serial_parity);
5553 serial_raw (rs->remote_desc);
5555 /* If there is something sitting in the buffer we might take it as a
5556 response to a command, which would be bad. */
5557 serial_flush_input (rs->remote_desc);
5561 puts_filtered ("Remote debugging using ");
5562 puts_filtered (name);
5563 puts_filtered ("\n");
5566 /* Switch to using the remote target now. */
5567 push_target (remote);
5568 /* The target stack owns the target now. */
5569 target_holder.release ();
5571 /* Register extra event sources in the event loop. */
5572 rs->remote_async_inferior_event_token
5573 = create_async_event_handler (remote_async_inferior_event_handler,
5575 rs->notif_state = remote_notif_state_allocate (remote);
5577 /* Reset the target state; these things will be queried either by
5578 remote_query_supported or as they are needed. */
5579 reset_all_packet_configs_support ();
5580 rs->cached_wait_status = 0;
5581 rs->explicit_packet_size = 0;
5583 rs->extended = extended_p;
5584 rs->waiting_for_stop_reply = 0;
5585 rs->ctrlc_pending_p = 0;
5586 rs->got_ctrlc_during_io = 0;
5588 rs->general_thread = not_sent_ptid;
5589 rs->continue_thread = not_sent_ptid;
5590 rs->remote_traceframe_number = -1;
5592 rs->last_resume_exec_dir = EXEC_FORWARD;
5594 /* Probe for ability to use "ThreadInfo" query, as required. */
5595 rs->use_threadinfo_query = 1;
5596 rs->use_threadextra_query = 1;
5598 rs->readahead_cache.invalidate ();
5600 if (target_async_permitted)
5602 /* FIXME: cagney/1999-09-23: During the initial connection it is
5603 assumed that the target is already ready and able to respond to
5604 requests. Unfortunately remote_start_remote() eventually calls
5605 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
5606 around this. Eventually a mechanism that allows
5607 wait_for_inferior() to expect/get timeouts will be
5609 rs->wait_forever_enabled_p = 0;
5612 /* First delete any symbols previously loaded from shared libraries. */
5613 no_shared_libraries (NULL, 0);
5616 init_thread_list ();
5618 /* Start the remote connection. If error() or QUIT, discard this
5619 target (we'd otherwise be in an inconsistent state) and then
5620 propogate the error on up the exception chain. This ensures that
5621 the caller doesn't stumble along blindly assuming that the
5622 function succeeded. The CLI doesn't have this problem but other
5623 UI's, such as MI do.
5625 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
5626 this function should return an error indication letting the
5627 caller restore the previous state. Unfortunately the command
5628 ``target remote'' is directly wired to this function making that
5629 impossible. On a positive note, the CLI side of this problem has
5630 been fixed - the function set_cmd_context() makes it possible for
5631 all the ``target ....'' commands to share a common callback
5632 function. See cli-dump.c. */
5637 remote->start_remote (from_tty, extended_p);
5639 CATCH (ex, RETURN_MASK_ALL)
5641 /* Pop the partially set up target - unless something else did
5642 already before throwing the exception. */
5643 if (ex.error != TARGET_CLOSE_ERROR)
5644 remote_unpush_target ();
5645 throw_exception (ex);
5650 remote_btrace_reset (rs);
5652 if (target_async_permitted)
5653 rs->wait_forever_enabled_p = 1;
5656 /* Detach the specified process. */
5659 remote_target::remote_detach_pid (int pid)
5661 struct remote_state *rs = get_remote_state ();
5663 /* This should not be necessary, but the handling for D;PID in
5664 GDBserver versions prior to 8.2 incorrectly assumes that the
5665 selected process points to the same process we're detaching,
5666 leading to misbehavior (and possibly GDBserver crashing) when it
5667 does not. Since it's easy and cheap, work around it by forcing
5668 GDBserver to select GDB's current process. */
5669 set_general_process ();
5671 if (remote_multi_process_p (rs))
5672 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
5674 strcpy (rs->buf, "D");
5677 getpkt (&rs->buf, &rs->buf_size, 0);
5679 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
5681 else if (rs->buf[0] == '\0')
5682 error (_("Remote doesn't know how to detach"));
5684 error (_("Can't detach process."));
5687 /* This detaches a program to which we previously attached, using
5688 inferior_ptid to identify the process. After this is done, GDB
5689 can be used to debug some other program. We better not have left
5690 any breakpoints in the target program or it'll die when it hits
5694 remote_target::remote_detach_1 (inferior *inf, int from_tty)
5696 int pid = inferior_ptid.pid ();
5697 struct remote_state *rs = get_remote_state ();
5700 if (!target_has_execution)
5701 error (_("No process to detach from."));
5703 target_announce_detach (from_tty);
5705 /* Tell the remote target to detach. */
5706 remote_detach_pid (pid);
5708 /* Exit only if this is the only active inferior. */
5709 if (from_tty && !rs->extended && number_of_live_inferiors () == 1)
5710 puts_filtered (_("Ending remote debugging.\n"));
5712 struct thread_info *tp = find_thread_ptid (inferior_ptid);
5714 /* Check to see if we are detaching a fork parent. Note that if we
5715 are detaching a fork child, tp == NULL. */
5716 is_fork_parent = (tp != NULL
5717 && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
5719 /* If doing detach-on-fork, we don't mourn, because that will delete
5720 breakpoints that should be available for the followed inferior. */
5721 if (!is_fork_parent)
5723 /* Save the pid as a string before mourning, since that will
5724 unpush the remote target, and we need the string after. */
5725 std::string infpid = target_pid_to_str (ptid_t (pid));
5727 target_mourn_inferior (inferior_ptid);
5728 if (print_inferior_events)
5729 printf_unfiltered (_("[Inferior %d (%s) detached]\n"),
5730 inf->num, infpid.c_str ());
5734 inferior_ptid = null_ptid;
5735 detach_inferior (current_inferior ());
5740 remote_target::detach (inferior *inf, int from_tty)
5742 remote_detach_1 (inf, from_tty);
5746 extended_remote_target::detach (inferior *inf, int from_tty)
5748 remote_detach_1 (inf, from_tty);
5751 /* Target follow-fork function for remote targets. On entry, and
5752 at return, the current inferior is the fork parent.
5754 Note that although this is currently only used for extended-remote,
5755 it is named remote_follow_fork in anticipation of using it for the
5756 remote target as well. */
5759 remote_target::follow_fork (int follow_child, int detach_fork)
5761 struct remote_state *rs = get_remote_state ();
5762 enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
5764 if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
5765 || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
5767 /* When following the parent and detaching the child, we detach
5768 the child here. For the case of following the child and
5769 detaching the parent, the detach is done in the target-
5770 independent follow fork code in infrun.c. We can't use
5771 target_detach when detaching an unfollowed child because
5772 the client side doesn't know anything about the child. */
5773 if (detach_fork && !follow_child)
5775 /* Detach the fork child. */
5779 child_ptid = inferior_thread ()->pending_follow.value.related_pid;
5780 child_pid = child_ptid.pid ();
5782 remote_detach_pid (child_pid);
5788 /* Target follow-exec function for remote targets. Save EXECD_PATHNAME
5789 in the program space of the new inferior. On entry and at return the
5790 current inferior is the exec'ing inferior. INF is the new exec'd
5791 inferior, which may be the same as the exec'ing inferior unless
5792 follow-exec-mode is "new". */
5795 remote_target::follow_exec (struct inferior *inf, char *execd_pathname)
5797 /* We know that this is a target file name, so if it has the "target:"
5798 prefix we strip it off before saving it in the program space. */
5799 if (is_target_filename (execd_pathname))
5800 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
5802 set_pspace_remote_exec_file (inf->pspace, execd_pathname);
5805 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
5808 remote_target::disconnect (const char *args, int from_tty)
5811 error (_("Argument given to \"disconnect\" when remotely debugging."));
5813 /* Make sure we unpush even the extended remote targets. Calling
5814 target_mourn_inferior won't unpush, and remote_mourn won't
5815 unpush if there is more than one inferior left. */
5816 unpush_target (this);
5817 generic_mourn_inferior ();
5820 puts_filtered ("Ending remote debugging.\n");
5823 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
5824 be chatty about it. */
5827 extended_remote_target::attach (const char *args, int from_tty)
5829 struct remote_state *rs = get_remote_state ();
5831 char *wait_status = NULL;
5833 pid = parse_pid_to_attach (args);
5835 /* Remote PID can be freely equal to getpid, do not check it here the same
5836 way as in other targets. */
5838 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
5839 error (_("This target does not support attaching to a process"));
5843 char *exec_file = get_exec_file (0);
5846 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
5847 target_pid_to_str (ptid_t (pid)));
5849 printf_unfiltered (_("Attaching to %s\n"),
5850 target_pid_to_str (ptid_t (pid)));
5852 gdb_flush (gdb_stdout);
5855 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
5857 getpkt (&rs->buf, &rs->buf_size, 0);
5859 switch (packet_ok (rs->buf,
5860 &remote_protocol_packets[PACKET_vAttach]))
5863 if (!target_is_non_stop_p ())
5865 /* Save the reply for later. */
5866 wait_status = (char *) alloca (strlen (rs->buf) + 1);
5867 strcpy (wait_status, rs->buf);
5869 else if (strcmp (rs->buf, "OK") != 0)
5870 error (_("Attaching to %s failed with: %s"),
5871 target_pid_to_str (ptid_t (pid)),
5874 case PACKET_UNKNOWN:
5875 error (_("This target does not support attaching to a process"));
5877 error (_("Attaching to %s failed"),
5878 target_pid_to_str (ptid_t (pid)));
5881 set_current_inferior (remote_add_inferior (0, pid, 1, 0));
5883 inferior_ptid = ptid_t (pid);
5885 if (target_is_non_stop_p ())
5887 struct thread_info *thread;
5889 /* Get list of threads. */
5890 update_thread_list ();
5892 thread = first_thread_of_inferior (current_inferior ());
5894 inferior_ptid = thread->ptid;
5896 inferior_ptid = ptid_t (pid);
5898 /* Invalidate our notion of the remote current thread. */
5899 record_currthread (rs, minus_one_ptid);
5903 /* Now, if we have thread information, update inferior_ptid. */
5904 inferior_ptid = remote_current_thread (inferior_ptid);
5906 /* Add the main thread to the thread list. */
5907 thread_info *thr = add_thread_silent (inferior_ptid);
5908 /* Don't consider the thread stopped until we've processed the
5909 saved stop reply. */
5910 set_executing (thr->ptid, true);
5913 /* Next, if the target can specify a description, read it. We do
5914 this before anything involving memory or registers. */
5915 target_find_description ();
5917 if (!target_is_non_stop_p ())
5919 /* Use the previously fetched status. */
5920 gdb_assert (wait_status != NULL);
5922 if (target_can_async_p ())
5924 struct notif_event *reply
5925 = remote_notif_parse (this, ¬if_client_stop, wait_status);
5927 push_stop_reply ((struct stop_reply *) reply);
5933 gdb_assert (wait_status != NULL);
5934 strcpy (rs->buf, wait_status);
5935 rs->cached_wait_status = 1;
5939 gdb_assert (wait_status == NULL);
5942 /* Implementation of the to_post_attach method. */
5945 extended_remote_target::post_attach (int pid)
5947 /* Get text, data & bss offsets. */
5950 /* In certain cases GDB might not have had the chance to start
5951 symbol lookup up until now. This could happen if the debugged
5952 binary is not using shared libraries, the vsyscall page is not
5953 present (on Linux) and the binary itself hadn't changed since the
5954 debugging process was started. */
5955 if (symfile_objfile != NULL)
5956 remote_check_symbols();
5960 /* Check for the availability of vCont. This function should also check
5964 remote_target::remote_vcont_probe ()
5966 remote_state *rs = get_remote_state ();
5969 strcpy (rs->buf, "vCont?");
5971 getpkt (&rs->buf, &rs->buf_size, 0);
5974 /* Make sure that the features we assume are supported. */
5975 if (startswith (buf, "vCont"))
5978 int support_c, support_C;
5980 rs->supports_vCont.s = 0;
5981 rs->supports_vCont.S = 0;
5984 rs->supports_vCont.t = 0;
5985 rs->supports_vCont.r = 0;
5986 while (p && *p == ';')
5989 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
5990 rs->supports_vCont.s = 1;
5991 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
5992 rs->supports_vCont.S = 1;
5993 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
5995 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
5997 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
5998 rs->supports_vCont.t = 1;
5999 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
6000 rs->supports_vCont.r = 1;
6002 p = strchr (p, ';');
6005 /* If c, and C are not all supported, we can't use vCont. Clearing
6006 BUF will make packet_ok disable the packet. */
6007 if (!support_c || !support_C)
6011 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
6014 /* Helper function for building "vCont" resumptions. Write a
6015 resumption to P. ENDP points to one-passed-the-end of the buffer
6016 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
6017 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
6018 resumed thread should be single-stepped and/or signalled. If PTID
6019 equals minus_one_ptid, then all threads are resumed; if PTID
6020 represents a process, then all threads of the process are resumed;
6021 the thread to be stepped and/or signalled is given in the global
6025 remote_target::append_resumption (char *p, char *endp,
6026 ptid_t ptid, int step, gdb_signal siggnal)
6028 struct remote_state *rs = get_remote_state ();
6030 if (step && siggnal != GDB_SIGNAL_0)
6031 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
6033 /* GDB is willing to range step. */
6034 && use_range_stepping
6035 /* Target supports range stepping. */
6036 && rs->supports_vCont.r
6037 /* We don't currently support range stepping multiple
6038 threads with a wildcard (though the protocol allows it,
6039 so stubs shouldn't make an active effort to forbid
6041 && !(remote_multi_process_p (rs) && ptid.is_pid ()))
6043 struct thread_info *tp;
6045 if (ptid == minus_one_ptid)
6047 /* If we don't know about the target thread's tid, then
6048 we're resuming magic_null_ptid (see caller). */
6049 tp = find_thread_ptid (magic_null_ptid);
6052 tp = find_thread_ptid (ptid);
6053 gdb_assert (tp != NULL);
6055 if (tp->control.may_range_step)
6057 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
6059 p += xsnprintf (p, endp - p, ";r%s,%s",
6060 phex_nz (tp->control.step_range_start,
6062 phex_nz (tp->control.step_range_end,
6066 p += xsnprintf (p, endp - p, ";s");
6069 p += xsnprintf (p, endp - p, ";s");
6070 else if (siggnal != GDB_SIGNAL_0)
6071 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
6073 p += xsnprintf (p, endp - p, ";c");
6075 if (remote_multi_process_p (rs) && ptid.is_pid ())
6079 /* All (-1) threads of process. */
6080 nptid = ptid_t (ptid.pid (), -1, 0);
6082 p += xsnprintf (p, endp - p, ":");
6083 p = write_ptid (p, endp, nptid);
6085 else if (ptid != minus_one_ptid)
6087 p += xsnprintf (p, endp - p, ":");
6088 p = write_ptid (p, endp, ptid);
6094 /* Clear the thread's private info on resume. */
6097 resume_clear_thread_private_info (struct thread_info *thread)
6099 if (thread->priv != NULL)
6101 remote_thread_info *priv = get_remote_thread_info (thread);
6103 priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6104 priv->watch_data_address = 0;
6108 /* Append a vCont continue-with-signal action for threads that have a
6109 non-zero stop signal. */
6112 remote_target::append_pending_thread_resumptions (char *p, char *endp,
6115 struct thread_info *thread;
6117 ALL_NON_EXITED_THREADS (thread)
6118 if (thread->ptid.matches (ptid)
6119 && inferior_ptid != thread->ptid
6120 && thread->suspend.stop_signal != GDB_SIGNAL_0)
6122 p = append_resumption (p, endp, thread->ptid,
6123 0, thread->suspend.stop_signal);
6124 thread->suspend.stop_signal = GDB_SIGNAL_0;
6125 resume_clear_thread_private_info (thread);
6131 /* Set the target running, using the packets that use Hc
6135 remote_target::remote_resume_with_hc (ptid_t ptid, int step,
6138 struct remote_state *rs = get_remote_state ();
6139 struct thread_info *thread;
6142 rs->last_sent_signal = siggnal;
6143 rs->last_sent_step = step;
6145 /* The c/s/C/S resume packets use Hc, so set the continue
6147 if (ptid == minus_one_ptid)
6148 set_continue_thread (any_thread_ptid);
6150 set_continue_thread (ptid);
6152 ALL_NON_EXITED_THREADS (thread)
6153 resume_clear_thread_private_info (thread);
6156 if (::execution_direction == EXEC_REVERSE)
6158 /* We don't pass signals to the target in reverse exec mode. */
6159 if (info_verbose && siggnal != GDB_SIGNAL_0)
6160 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
6163 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
6164 error (_("Remote reverse-step not supported."));
6165 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
6166 error (_("Remote reverse-continue not supported."));
6168 strcpy (buf, step ? "bs" : "bc");
6170 else if (siggnal != GDB_SIGNAL_0)
6172 buf[0] = step ? 'S' : 'C';
6173 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
6174 buf[2] = tohex (((int) siggnal) & 0xf);
6178 strcpy (buf, step ? "s" : "c");
6183 /* Resume the remote inferior by using a "vCont" packet. The thread
6184 to be resumed is PTID; STEP and SIGGNAL indicate whether the
6185 resumed thread should be single-stepped and/or signalled. If PTID
6186 equals minus_one_ptid, then all threads are resumed; the thread to
6187 be stepped and/or signalled is given in the global INFERIOR_PTID.
6188 This function returns non-zero iff it resumes the inferior.
6190 This function issues a strict subset of all possible vCont commands
6194 remote_target::remote_resume_with_vcont (ptid_t ptid, int step,
6195 enum gdb_signal siggnal)
6197 struct remote_state *rs = get_remote_state ();
6201 /* No reverse execution actions defined for vCont. */
6202 if (::execution_direction == EXEC_REVERSE)
6205 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6206 remote_vcont_probe ();
6208 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
6212 endp = rs->buf + get_remote_packet_size ();
6214 /* If we could generate a wider range of packets, we'd have to worry
6215 about overflowing BUF. Should there be a generic
6216 "multi-part-packet" packet? */
6218 p += xsnprintf (p, endp - p, "vCont");
6220 if (ptid == magic_null_ptid)
6222 /* MAGIC_NULL_PTID means that we don't have any active threads,
6223 so we don't have any TID numbers the inferior will
6224 understand. Make sure to only send forms that do not specify
6226 append_resumption (p, endp, minus_one_ptid, step, siggnal);
6228 else if (ptid == minus_one_ptid || ptid.is_pid ())
6230 /* Resume all threads (of all processes, or of a single
6231 process), with preference for INFERIOR_PTID. This assumes
6232 inferior_ptid belongs to the set of all threads we are about
6234 if (step || siggnal != GDB_SIGNAL_0)
6236 /* Step inferior_ptid, with or without signal. */
6237 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
6240 /* Also pass down any pending signaled resumption for other
6241 threads not the current. */
6242 p = append_pending_thread_resumptions (p, endp, ptid);
6244 /* And continue others without a signal. */
6245 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
6249 /* Scheduler locking; resume only PTID. */
6250 append_resumption (p, endp, ptid, step, siggnal);
6253 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
6256 if (target_is_non_stop_p ())
6258 /* In non-stop, the stub replies to vCont with "OK". The stop
6259 reply will be reported asynchronously by means of a `%Stop'
6261 getpkt (&rs->buf, &rs->buf_size, 0);
6262 if (strcmp (rs->buf, "OK") != 0)
6263 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
6269 /* Tell the remote machine to resume. */
6272 remote_target::resume (ptid_t ptid, int step, enum gdb_signal siggnal)
6274 struct remote_state *rs = get_remote_state ();
6276 /* When connected in non-stop mode, the core resumes threads
6277 individually. Resuming remote threads directly in target_resume
6278 would thus result in sending one packet per thread. Instead, to
6279 minimize roundtrip latency, here we just store the resume
6280 request; the actual remote resumption will be done in
6281 target_commit_resume / remote_commit_resume, where we'll be able
6282 to do vCont action coalescing. */
6283 if (target_is_non_stop_p () && ::execution_direction != EXEC_REVERSE)
6285 remote_thread_info *remote_thr;
6287 if (minus_one_ptid == ptid || ptid.is_pid ())
6288 remote_thr = get_remote_thread_info (inferior_ptid);
6290 remote_thr = get_remote_thread_info (ptid);
6292 remote_thr->last_resume_step = step;
6293 remote_thr->last_resume_sig = siggnal;
6297 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
6298 (explained in remote-notif.c:handle_notification) so
6299 remote_notif_process is not called. We need find a place where
6300 it is safe to start a 'vNotif' sequence. It is good to do it
6301 before resuming inferior, because inferior was stopped and no RSP
6302 traffic at that moment. */
6303 if (!target_is_non_stop_p ())
6304 remote_notif_process (rs->notif_state, ¬if_client_stop);
6306 rs->last_resume_exec_dir = ::execution_direction;
6308 /* Prefer vCont, and fallback to s/c/S/C, which use Hc. */
6309 if (!remote_resume_with_vcont (ptid, step, siggnal))
6310 remote_resume_with_hc (ptid, step, siggnal);
6312 /* We are about to start executing the inferior, let's register it
6313 with the event loop. NOTE: this is the one place where all the
6314 execution commands end up. We could alternatively do this in each
6315 of the execution commands in infcmd.c. */
6316 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
6317 into infcmd.c in order to allow inferior function calls to work
6318 NOT asynchronously. */
6319 if (target_can_async_p ())
6322 /* We've just told the target to resume. The remote server will
6323 wait for the inferior to stop, and then send a stop reply. In
6324 the mean time, we can't start another command/query ourselves
6325 because the stub wouldn't be ready to process it. This applies
6326 only to the base all-stop protocol, however. In non-stop (which
6327 only supports vCont), the stub replies with an "OK", and is
6328 immediate able to process further serial input. */
6329 if (!target_is_non_stop_p ())
6330 rs->waiting_for_stop_reply = 1;
6333 static int is_pending_fork_parent_thread (struct thread_info *thread);
6335 /* Private per-inferior info for target remote processes. */
6337 struct remote_inferior : public private_inferior
6339 /* Whether we can send a wildcard vCont for this process. */
6340 bool may_wildcard_vcont = true;
6343 /* Get the remote private inferior data associated to INF. */
6345 static remote_inferior *
6346 get_remote_inferior (inferior *inf)
6348 if (inf->priv == NULL)
6349 inf->priv.reset (new remote_inferior);
6351 return static_cast<remote_inferior *> (inf->priv.get ());
6354 /* Class used to track the construction of a vCont packet in the
6355 outgoing packet buffer. This is used to send multiple vCont
6356 packets if we have more actions than would fit a single packet. */
6361 explicit vcont_builder (remote_target *remote)
6368 void push_action (ptid_t ptid, bool step, gdb_signal siggnal);
6373 /* The remote target. */
6374 remote_target *m_remote;
6376 /* Pointer to the first action. P points here if no action has been
6378 char *m_first_action;
6380 /* Where the next action will be appended. */
6383 /* The end of the buffer. Must never write past this. */
6387 /* Prepare the outgoing buffer for a new vCont packet. */
6390 vcont_builder::restart ()
6392 struct remote_state *rs = m_remote->get_remote_state ();
6395 m_endp = rs->buf + m_remote->get_remote_packet_size ();
6396 m_p += xsnprintf (m_p, m_endp - m_p, "vCont");
6397 m_first_action = m_p;
6400 /* If the vCont packet being built has any action, send it to the
6404 vcont_builder::flush ()
6406 struct remote_state *rs;
6408 if (m_p == m_first_action)
6411 rs = m_remote->get_remote_state ();
6412 m_remote->putpkt (rs->buf);
6413 m_remote->getpkt (&rs->buf, &rs->buf_size, 0);
6414 if (strcmp (rs->buf, "OK") != 0)
6415 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
6418 /* The largest action is range-stepping, with its two addresses. This
6419 is more than sufficient. If a new, bigger action is created, it'll
6420 quickly trigger a failed assertion in append_resumption (and we'll
6422 #define MAX_ACTION_SIZE 200
6424 /* Append a new vCont action in the outgoing packet being built. If
6425 the action doesn't fit the packet along with previous actions, push
6426 what we've got so far to the remote end and start over a new vCont
6427 packet (with the new action). */
6430 vcont_builder::push_action (ptid_t ptid, bool step, gdb_signal siggnal)
6432 char buf[MAX_ACTION_SIZE + 1];
6434 char *endp = m_remote->append_resumption (buf, buf + sizeof (buf),
6435 ptid, step, siggnal);
6437 /* Check whether this new action would fit in the vCont packet along
6438 with previous actions. If not, send what we've got so far and
6439 start a new vCont packet. */
6440 size_t rsize = endp - buf;
6441 if (rsize > m_endp - m_p)
6446 /* Should now fit. */
6447 gdb_assert (rsize <= m_endp - m_p);
6450 memcpy (m_p, buf, rsize);
6455 /* to_commit_resume implementation. */
6458 remote_target::commit_resume ()
6460 struct inferior *inf;
6461 struct thread_info *tp;
6462 int any_process_wildcard;
6463 int may_global_wildcard_vcont;
6465 /* If connected in all-stop mode, we'd send the remote resume
6466 request directly from remote_resume. Likewise if
6467 reverse-debugging, as there are no defined vCont actions for
6468 reverse execution. */
6469 if (!target_is_non_stop_p () || ::execution_direction == EXEC_REVERSE)
6472 /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
6473 instead of resuming all threads of each process individually.
6474 However, if any thread of a process must remain halted, we can't
6475 send wildcard resumes and must send one action per thread.
6477 Care must be taken to not resume threads/processes the server
6478 side already told us are stopped, but the core doesn't know about
6479 yet, because the events are still in the vStopped notification
6482 #1 => vCont s:p1.1;c
6484 #3 <= %Stopped T05 p1.1
6489 #8 (infrun handles the stop for p1.1 and continues stepping)
6490 #9 => vCont s:p1.1;c
6492 The last vCont above would resume thread p1.2 by mistake, because
6493 the server has no idea that the event for p1.2 had not been
6496 The server side must similarly ignore resume actions for the
6497 thread that has a pending %Stopped notification (and any other
6498 threads with events pending), until GDB acks the notification
6499 with vStopped. Otherwise, e.g., the following case is
6502 #1 => g (or any other packet)
6504 #3 <= %Stopped T05 p1.2
6505 #4 => vCont s:p1.1;c
6508 Above, the server must not resume thread p1.2. GDB can't know
6509 that p1.2 stopped until it acks the %Stopped notification, and
6510 since from GDB's perspective all threads should be running, it
6513 Finally, special care must also be given to handling fork/vfork
6514 events. A (v)fork event actually tells us that two processes
6515 stopped -- the parent and the child. Until we follow the fork,
6516 we must not resume the child. Therefore, if we have a pending
6517 fork follow, we must not send a global wildcard resume action
6518 (vCont;c). We can still send process-wide wildcards though. */
6520 /* Start by assuming a global wildcard (vCont;c) is possible. */
6521 may_global_wildcard_vcont = 1;
6523 /* And assume every process is individually wildcard-able too. */
6524 ALL_NON_EXITED_INFERIORS (inf)
6526 remote_inferior *priv = get_remote_inferior (inf);
6528 priv->may_wildcard_vcont = true;
6531 /* Check for any pending events (not reported or processed yet) and
6532 disable process and global wildcard resumes appropriately. */
6533 check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
6535 ALL_NON_EXITED_THREADS (tp)
6537 /* If a thread of a process is not meant to be resumed, then we
6538 can't wildcard that process. */
6541 get_remote_inferior (tp->inf)->may_wildcard_vcont = false;
6543 /* And if we can't wildcard a process, we can't wildcard
6544 everything either. */
6545 may_global_wildcard_vcont = 0;
6549 /* If a thread is the parent of an unfollowed fork, then we
6550 can't do a global wildcard, as that would resume the fork
6552 if (is_pending_fork_parent_thread (tp))
6553 may_global_wildcard_vcont = 0;
6556 /* Now let's build the vCont packet(s). Actions must be appended
6557 from narrower to wider scopes (thread -> process -> global). If
6558 we end up with too many actions for a single packet vcont_builder
6559 flushes the current vCont packet to the remote side and starts a
6561 struct vcont_builder vcont_builder (this);
6563 /* Threads first. */
6564 ALL_NON_EXITED_THREADS (tp)
6566 remote_thread_info *remote_thr = get_remote_thread_info (tp);
6568 if (!tp->executing || remote_thr->vcont_resumed)
6571 gdb_assert (!thread_is_in_step_over_chain (tp));
6573 if (!remote_thr->last_resume_step
6574 && remote_thr->last_resume_sig == GDB_SIGNAL_0
6575 && get_remote_inferior (tp->inf)->may_wildcard_vcont)
6577 /* We'll send a wildcard resume instead. */
6578 remote_thr->vcont_resumed = 1;
6582 vcont_builder.push_action (tp->ptid,
6583 remote_thr->last_resume_step,
6584 remote_thr->last_resume_sig);
6585 remote_thr->vcont_resumed = 1;
6588 /* Now check whether we can send any process-wide wildcard. This is
6589 to avoid sending a global wildcard in the case nothing is
6590 supposed to be resumed. */
6591 any_process_wildcard = 0;
6593 ALL_NON_EXITED_INFERIORS (inf)
6595 if (get_remote_inferior (inf)->may_wildcard_vcont)
6597 any_process_wildcard = 1;
6602 if (any_process_wildcard)
6604 /* If all processes are wildcard-able, then send a single "c"
6605 action, otherwise, send an "all (-1) threads of process"
6606 continue action for each running process, if any. */
6607 if (may_global_wildcard_vcont)
6609 vcont_builder.push_action (minus_one_ptid,
6610 false, GDB_SIGNAL_0);
6614 ALL_NON_EXITED_INFERIORS (inf)
6616 if (get_remote_inferior (inf)->may_wildcard_vcont)
6618 vcont_builder.push_action (ptid_t (inf->pid),
6619 false, GDB_SIGNAL_0);
6625 vcont_builder.flush ();
6630 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
6631 thread, all threads of a remote process, or all threads of all
6635 remote_target::remote_stop_ns (ptid_t ptid)
6637 struct remote_state *rs = get_remote_state ();
6639 char *endp = rs->buf + get_remote_packet_size ();
6641 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6642 remote_vcont_probe ();
6644 if (!rs->supports_vCont.t)
6645 error (_("Remote server does not support stopping threads"));
6647 if (ptid == minus_one_ptid
6648 || (!remote_multi_process_p (rs) && ptid.is_pid ()))
6649 p += xsnprintf (p, endp - p, "vCont;t");
6654 p += xsnprintf (p, endp - p, "vCont;t:");
6657 /* All (-1) threads of process. */
6658 nptid = ptid_t (ptid.pid (), -1, 0);
6661 /* Small optimization: if we already have a stop reply for
6662 this thread, no use in telling the stub we want this
6664 if (peek_stop_reply (ptid))
6670 write_ptid (p, endp, nptid);
6673 /* In non-stop, we get an immediate OK reply. The stop reply will
6674 come in asynchronously by notification. */
6676 getpkt (&rs->buf, &rs->buf_size, 0);
6677 if (strcmp (rs->buf, "OK") != 0)
6678 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
6681 /* All-stop version of target_interrupt. Sends a break or a ^C to
6682 interrupt the remote target. It is undefined which thread of which
6683 process reports the interrupt. */
6686 remote_target::remote_interrupt_as ()
6688 struct remote_state *rs = get_remote_state ();
6690 rs->ctrlc_pending_p = 1;
6692 /* If the inferior is stopped already, but the core didn't know
6693 about it yet, just ignore the request. The cached wait status
6694 will be collected in remote_wait. */
6695 if (rs->cached_wait_status)
6698 /* Send interrupt_sequence to remote target. */
6699 send_interrupt_sequence ();
6702 /* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
6703 the remote target. It is undefined which thread of which process
6704 reports the interrupt. Throws an error if the packet is not
6705 supported by the server. */
6708 remote_target::remote_interrupt_ns ()
6710 struct remote_state *rs = get_remote_state ();
6712 char *endp = rs->buf + get_remote_packet_size ();
6714 xsnprintf (p, endp - p, "vCtrlC");
6716 /* In non-stop, we get an immediate OK reply. The stop reply will
6717 come in asynchronously by notification. */
6719 getpkt (&rs->buf, &rs->buf_size, 0);
6721 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
6725 case PACKET_UNKNOWN:
6726 error (_("No support for interrupting the remote target."));
6728 error (_("Interrupting target failed: %s"), rs->buf);
6732 /* Implement the to_stop function for the remote targets. */
6735 remote_target::stop (ptid_t ptid)
6738 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
6740 if (target_is_non_stop_p ())
6741 remote_stop_ns (ptid);
6744 /* We don't currently have a way to transparently pause the
6745 remote target in all-stop mode. Interrupt it instead. */
6746 remote_interrupt_as ();
6750 /* Implement the to_interrupt function for the remote targets. */
6753 remote_target::interrupt ()
6756 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
6758 if (target_is_non_stop_p ())
6759 remote_interrupt_ns ();
6761 remote_interrupt_as ();
6764 /* Implement the to_pass_ctrlc function for the remote targets. */
6767 remote_target::pass_ctrlc ()
6769 struct remote_state *rs = get_remote_state ();
6772 fprintf_unfiltered (gdb_stdlog, "remote_pass_ctrlc called\n");
6774 /* If we're starting up, we're not fully synced yet. Quit
6776 if (rs->starting_up)
6778 /* If ^C has already been sent once, offer to disconnect. */
6779 else if (rs->ctrlc_pending_p)
6782 target_interrupt ();
6785 /* Ask the user what to do when an interrupt is received. */
6788 remote_target::interrupt_query ()
6790 struct remote_state *rs = get_remote_state ();
6792 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
6794 if (query (_("The target is not responding to interrupt requests.\n"
6795 "Stop debugging it? ")))
6797 remote_unpush_target ();
6798 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
6803 if (query (_("Interrupted while waiting for the program.\n"
6804 "Give up waiting? ")))
6809 /* Enable/disable target terminal ownership. Most targets can use
6810 terminal groups to control terminal ownership. Remote targets are
6811 different in that explicit transfer of ownership to/from GDB/target
6815 remote_target::terminal_inferior ()
6817 /* NOTE: At this point we could also register our selves as the
6818 recipient of all input. Any characters typed could then be
6819 passed on down to the target. */
6823 remote_target::terminal_ours ()
6828 remote_console_output (char *msg)
6832 for (p = msg; p[0] && p[1]; p += 2)
6835 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
6839 fputs_unfiltered (tb, gdb_stdtarg);
6841 gdb_flush (gdb_stdtarg);
6844 DEF_VEC_O(cached_reg_t);
6846 typedef struct stop_reply
6848 struct notif_event base;
6850 /* The identifier of the thread about this event */
6853 /* The remote state this event is associated with. When the remote
6854 connection, represented by a remote_state object, is closed,
6855 all the associated stop_reply events should be released. */
6856 struct remote_state *rs;
6858 struct target_waitstatus ws;
6860 /* The architecture associated with the expedited registers. */
6863 /* Expedited registers. This makes remote debugging a bit more
6864 efficient for those targets that provide critical registers as
6865 part of their normal status mechanism (as another roundtrip to
6866 fetch them is avoided). */
6867 VEC(cached_reg_t) *regcache;
6869 enum target_stop_reason stop_reason;
6871 CORE_ADDR watch_data_address;
6877 stop_reply_xfree (struct stop_reply *r)
6879 notif_event_xfree ((struct notif_event *) r);
6882 /* Return the length of the stop reply queue. */
6885 remote_target::stop_reply_queue_length ()
6887 remote_state *rs = get_remote_state ();
6888 return rs->stop_reply_queue.size ();
6892 remote_notif_stop_parse (remote_target *remote,
6893 struct notif_client *self, char *buf,
6894 struct notif_event *event)
6896 remote->remote_parse_stop_reply (buf, (struct stop_reply *) event);
6900 remote_notif_stop_ack (remote_target *remote,
6901 struct notif_client *self, char *buf,
6902 struct notif_event *event)
6904 struct stop_reply *stop_reply = (struct stop_reply *) event;
6907 putpkt (remote, self->ack_command);
6909 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
6911 /* We got an unknown stop reply. */
6912 error (_("Unknown stop reply"));
6915 remote->push_stop_reply (stop_reply);
6919 remote_notif_stop_can_get_pending_events (remote_target *remote,
6920 struct notif_client *self)
6922 /* We can't get pending events in remote_notif_process for
6923 notification stop, and we have to do this in remote_wait_ns
6924 instead. If we fetch all queued events from stub, remote stub
6925 may exit and we have no chance to process them back in
6927 remote_state *rs = remote->get_remote_state ();
6928 mark_async_event_handler (rs->remote_async_inferior_event_token);
6933 stop_reply_dtr (struct notif_event *event)
6935 struct stop_reply *r = (struct stop_reply *) event;
6940 VEC_iterate (cached_reg_t, r->regcache, ix, reg);
6944 VEC_free (cached_reg_t, r->regcache);
6947 static struct notif_event *
6948 remote_notif_stop_alloc_reply (void)
6950 /* We cast to a pointer to the "base class". */
6951 struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
6953 r->dtr = stop_reply_dtr;
6958 /* A client of notification Stop. */
6960 struct notif_client notif_client_stop =
6964 remote_notif_stop_parse,
6965 remote_notif_stop_ack,
6966 remote_notif_stop_can_get_pending_events,
6967 remote_notif_stop_alloc_reply,
6971 /* Determine if THREAD_PTID is a pending fork parent thread. ARG contains
6972 the pid of the process that owns the threads we want to check, or
6973 -1 if we want to check all threads. */
6976 is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
6979 if (ws->kind == TARGET_WAITKIND_FORKED
6980 || ws->kind == TARGET_WAITKIND_VFORKED)
6982 if (event_pid == -1 || event_pid == thread_ptid.pid ())
6989 /* Return the thread's pending status used to determine whether the
6990 thread is a fork parent stopped at a fork event. */
6992 static struct target_waitstatus *
6993 thread_pending_fork_status (struct thread_info *thread)
6995 if (thread->suspend.waitstatus_pending_p)
6996 return &thread->suspend.waitstatus;
6998 return &thread->pending_follow;
7001 /* Determine if THREAD is a pending fork parent thread. */
7004 is_pending_fork_parent_thread (struct thread_info *thread)
7006 struct target_waitstatus *ws = thread_pending_fork_status (thread);
7009 return is_pending_fork_parent (ws, pid, thread->ptid);
7012 /* If CONTEXT contains any fork child threads that have not been
7013 reported yet, remove them from the CONTEXT list. If such a
7014 thread exists it is because we are stopped at a fork catchpoint
7015 and have not yet called follow_fork, which will set up the
7016 host-side data structures for the new process. */
7019 remote_target::remove_new_fork_children (threads_listing_context *context)
7021 struct thread_info * thread;
7023 struct notif_client *notif = ¬if_client_stop;
7025 /* For any threads stopped at a fork event, remove the corresponding
7026 fork child threads from the CONTEXT list. */
7027 ALL_NON_EXITED_THREADS (thread)
7029 struct target_waitstatus *ws = thread_pending_fork_status (thread);
7031 if (is_pending_fork_parent (ws, pid, thread->ptid))
7032 context->remove_thread (ws->value.related_pid);
7035 /* Check for any pending fork events (not reported or processed yet)
7036 in process PID and remove those fork child threads from the
7037 CONTEXT list as well. */
7038 remote_notif_get_pending_events (notif);
7039 for (auto &event : get_remote_state ()->stop_reply_queue)
7040 if (event->ws.kind == TARGET_WAITKIND_FORKED
7041 || event->ws.kind == TARGET_WAITKIND_VFORKED
7042 || event->ws.kind == TARGET_WAITKIND_THREAD_EXITED)
7043 context->remove_thread (event->ws.value.related_pid);
7046 /* Check whether any event pending in the vStopped queue would prevent
7047 a global or process wildcard vCont action. Clear
7048 *may_global_wildcard if we can't do a global wildcard (vCont;c),
7049 and clear the event inferior's may_wildcard_vcont flag if we can't
7050 do a process-wide wildcard resume (vCont;c:pPID.-1). */
7053 remote_target::check_pending_events_prevent_wildcard_vcont
7054 (int *may_global_wildcard)
7056 struct notif_client *notif = ¬if_client_stop;
7058 remote_notif_get_pending_events (notif);
7059 for (auto &event : get_remote_state ()->stop_reply_queue)
7061 if (event->ws.kind == TARGET_WAITKIND_NO_RESUMED
7062 || event->ws.kind == TARGET_WAITKIND_NO_HISTORY)
7065 if (event->ws.kind == TARGET_WAITKIND_FORKED
7066 || event->ws.kind == TARGET_WAITKIND_VFORKED)
7067 *may_global_wildcard = 0;
7069 struct inferior *inf = find_inferior_ptid (event->ptid);
7071 /* This may be the first time we heard about this process.
7072 Regardless, we must not do a global wildcard resume, otherwise
7073 we'd resume this process too. */
7074 *may_global_wildcard = 0;
7076 get_remote_inferior (inf)->may_wildcard_vcont = false;
7080 /* Discard all pending stop replies of inferior INF. */
7083 remote_target::discard_pending_stop_replies (struct inferior *inf)
7085 struct stop_reply *reply;
7086 struct remote_state *rs = get_remote_state ();
7087 struct remote_notif_state *rns = rs->notif_state;
7089 /* This function can be notified when an inferior exists. When the
7090 target is not remote, the notification state is NULL. */
7091 if (rs->remote_desc == NULL)
7094 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
7096 /* Discard the in-flight notification. */
7097 if (reply != NULL && reply->ptid.pid () == inf->pid)
7099 stop_reply_xfree (reply);
7100 rns->pending_event[notif_client_stop.id] = NULL;
7103 /* Discard the stop replies we have already pulled with
7105 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7106 rs->stop_reply_queue.end (),
7107 [=] (const stop_reply_up &event)
7109 return event->ptid.pid () == inf->pid;
7111 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7114 /* Discard the stop replies for RS in stop_reply_queue. */
7117 remote_target::discard_pending_stop_replies_in_queue ()
7119 remote_state *rs = get_remote_state ();
7121 /* Discard the stop replies we have already pulled with
7123 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7124 rs->stop_reply_queue.end (),
7125 [=] (const stop_reply_up &event)
7127 return event->rs == rs;
7129 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7132 /* Remove the first reply in 'stop_reply_queue' which matches
7136 remote_target::remote_notif_remove_queued_reply (ptid_t ptid)
7138 remote_state *rs = get_remote_state ();
7140 auto iter = std::find_if (rs->stop_reply_queue.begin (),
7141 rs->stop_reply_queue.end (),
7142 [=] (const stop_reply_up &event)
7144 return event->ptid.matches (ptid);
7146 struct stop_reply *result;
7147 if (iter == rs->stop_reply_queue.end ())
7151 result = iter->release ();
7152 rs->stop_reply_queue.erase (iter);
7156 fprintf_unfiltered (gdb_stdlog,
7157 "notif: discard queued event: 'Stop' in %s\n",
7158 target_pid_to_str (ptid));
7163 /* Look for a queued stop reply belonging to PTID. If one is found,
7164 remove it from the queue, and return it. Returns NULL if none is
7165 found. If there are still queued events left to process, tell the
7166 event loop to get back to target_wait soon. */
7169 remote_target::queued_stop_reply (ptid_t ptid)
7171 remote_state *rs = get_remote_state ();
7172 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
7174 if (!rs->stop_reply_queue.empty ())
7176 /* There's still at least an event left. */
7177 mark_async_event_handler (rs->remote_async_inferior_event_token);
7183 /* Push a fully parsed stop reply in the stop reply queue. Since we
7184 know that we now have at least one queued event left to pass to the
7185 core side, tell the event loop to get back to target_wait soon. */
7188 remote_target::push_stop_reply (struct stop_reply *new_event)
7190 remote_state *rs = get_remote_state ();
7191 rs->stop_reply_queue.push_back (stop_reply_up (new_event));
7194 fprintf_unfiltered (gdb_stdlog,
7195 "notif: push 'Stop' %s to queue %d\n",
7196 target_pid_to_str (new_event->ptid),
7197 int (rs->stop_reply_queue.size ()));
7199 mark_async_event_handler (rs->remote_async_inferior_event_token);
7202 /* Returns true if we have a stop reply for PTID. */
7205 remote_target::peek_stop_reply (ptid_t ptid)
7207 remote_state *rs = get_remote_state ();
7208 for (auto &event : rs->stop_reply_queue)
7209 if (ptid == event->ptid
7210 && event->ws.kind == TARGET_WAITKIND_STOPPED)
7215 /* Helper for remote_parse_stop_reply. Return nonzero if the substring
7216 starting with P and ending with PEND matches PREFIX. */
7219 strprefix (const char *p, const char *pend, const char *prefix)
7221 for ( ; p < pend; p++, prefix++)
7224 return *prefix == '\0';
7227 /* Parse the stop reply in BUF. Either the function succeeds, and the
7228 result is stored in EVENT, or throws an error. */
7231 remote_target::remote_parse_stop_reply (char *buf, stop_reply *event)
7233 remote_arch_state *rsa = NULL;
7238 event->ptid = null_ptid;
7239 event->rs = get_remote_state ();
7240 event->ws.kind = TARGET_WAITKIND_IGNORE;
7241 event->ws.value.integer = 0;
7242 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
7243 event->regcache = NULL;
7248 case 'T': /* Status with PC, SP, FP, ... */
7249 /* Expedited reply, containing Signal, {regno, reg} repeat. */
7250 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
7252 n... = register number
7253 r... = register contents
7256 p = &buf[3]; /* after Txx */
7262 p1 = strchr (p, ':');
7264 error (_("Malformed packet(a) (missing colon): %s\n\
7268 error (_("Malformed packet(a) (missing register number): %s\n\
7272 /* Some "registers" are actually extended stop information.
7273 Note if you're adding a new entry here: GDB 7.9 and
7274 earlier assume that all register "numbers" that start
7275 with an hex digit are real register numbers. Make sure
7276 the server only sends such a packet if it knows the
7277 client understands it. */
7279 if (strprefix (p, p1, "thread"))
7280 event->ptid = read_ptid (++p1, &p);
7281 else if (strprefix (p, p1, "syscall_entry"))
7285 event->ws.kind = TARGET_WAITKIND_SYSCALL_ENTRY;
7286 p = unpack_varlen_hex (++p1, &sysno);
7287 event->ws.value.syscall_number = (int) sysno;
7289 else if (strprefix (p, p1, "syscall_return"))
7293 event->ws.kind = TARGET_WAITKIND_SYSCALL_RETURN;
7294 p = unpack_varlen_hex (++p1, &sysno);
7295 event->ws.value.syscall_number = (int) sysno;
7297 else if (strprefix (p, p1, "watch")
7298 || strprefix (p, p1, "rwatch")
7299 || strprefix (p, p1, "awatch"))
7301 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
7302 p = unpack_varlen_hex (++p1, &addr);
7303 event->watch_data_address = (CORE_ADDR) addr;
7305 else if (strprefix (p, p1, "swbreak"))
7307 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
7309 /* Make sure the stub doesn't forget to indicate support
7311 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
7312 error (_("Unexpected swbreak stop reason"));
7314 /* The value part is documented as "must be empty",
7315 though we ignore it, in case we ever decide to make
7316 use of it in a backward compatible way. */
7317 p = strchrnul (p1 + 1, ';');
7319 else if (strprefix (p, p1, "hwbreak"))
7321 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
7323 /* Make sure the stub doesn't forget to indicate support
7325 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
7326 error (_("Unexpected hwbreak stop reason"));
7329 p = strchrnul (p1 + 1, ';');
7331 else if (strprefix (p, p1, "library"))
7333 event->ws.kind = TARGET_WAITKIND_LOADED;
7334 p = strchrnul (p1 + 1, ';');
7336 else if (strprefix (p, p1, "replaylog"))
7338 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
7339 /* p1 will indicate "begin" or "end", but it makes
7340 no difference for now, so ignore it. */
7341 p = strchrnul (p1 + 1, ';');
7343 else if (strprefix (p, p1, "core"))
7347 p = unpack_varlen_hex (++p1, &c);
7350 else if (strprefix (p, p1, "fork"))
7352 event->ws.value.related_pid = read_ptid (++p1, &p);
7353 event->ws.kind = TARGET_WAITKIND_FORKED;
7355 else if (strprefix (p, p1, "vfork"))
7357 event->ws.value.related_pid = read_ptid (++p1, &p);
7358 event->ws.kind = TARGET_WAITKIND_VFORKED;
7360 else if (strprefix (p, p1, "vforkdone"))
7362 event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
7363 p = strchrnul (p1 + 1, ';');
7365 else if (strprefix (p, p1, "exec"))
7368 char pathname[PATH_MAX];
7371 /* Determine the length of the execd pathname. */
7372 p = unpack_varlen_hex (++p1, &ignored);
7373 pathlen = (p - p1) / 2;
7375 /* Save the pathname for event reporting and for
7376 the next run command. */
7377 hex2bin (p1, (gdb_byte *) pathname, pathlen);
7378 pathname[pathlen] = '\0';
7380 /* This is freed during event handling. */
7381 event->ws.value.execd_pathname = xstrdup (pathname);
7382 event->ws.kind = TARGET_WAITKIND_EXECD;
7384 /* Skip the registers included in this packet, since
7385 they may be for an architecture different from the
7386 one used by the original program. */
7389 else if (strprefix (p, p1, "create"))
7391 event->ws.kind = TARGET_WAITKIND_THREAD_CREATED;
7392 p = strchrnul (p1 + 1, ';');
7401 p = strchrnul (p1 + 1, ';');
7406 /* Maybe a real ``P'' register number. */
7407 p_temp = unpack_varlen_hex (p, &pnum);
7408 /* If the first invalid character is the colon, we got a
7409 register number. Otherwise, it's an unknown stop
7413 /* If we haven't parsed the event's thread yet, find
7414 it now, in order to find the architecture of the
7415 reported expedited registers. */
7416 if (event->ptid == null_ptid)
7418 const char *thr = strstr (p1 + 1, ";thread:");
7420 event->ptid = read_ptid (thr + strlen (";thread:"),
7424 /* Either the current thread hasn't changed,
7425 or the inferior is not multi-threaded.
7426 The event must be for the thread we last
7427 set as (or learned as being) current. */
7428 event->ptid = event->rs->general_thread;
7434 inferior *inf = (event->ptid == null_ptid
7436 : find_inferior_ptid (event->ptid));
7437 /* If this is the first time we learn anything
7438 about this process, skip the registers
7439 included in this packet, since we don't yet
7440 know which architecture to use to parse them.
7441 We'll determine the architecture later when
7442 we process the stop reply and retrieve the
7443 target description, via
7444 remote_notice_new_inferior ->
7445 post_create_inferior. */
7448 p = strchrnul (p1 + 1, ';');
7453 event->arch = inf->gdbarch;
7454 rsa = event->rs->get_remote_arch_state (event->arch);
7458 = packet_reg_from_pnum (event->arch, rsa, pnum);
7459 cached_reg_t cached_reg;
7462 error (_("Remote sent bad register number %s: %s\n\
7464 hex_string (pnum), p, buf);
7466 cached_reg.num = reg->regnum;
7467 cached_reg.data = (gdb_byte *)
7468 xmalloc (register_size (event->arch, reg->regnum));
7471 fieldsize = hex2bin (p, cached_reg.data,
7472 register_size (event->arch, reg->regnum));
7474 if (fieldsize < register_size (event->arch, reg->regnum))
7475 warning (_("Remote reply is too short: %s"), buf);
7477 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
7481 /* Not a number. Silently skip unknown optional
7483 p = strchrnul (p1 + 1, ';');
7488 error (_("Remote register badly formatted: %s\nhere: %s"),
7493 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
7497 case 'S': /* Old style status, just signal only. */
7501 event->ws.kind = TARGET_WAITKIND_STOPPED;
7502 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
7503 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
7504 event->ws.value.sig = (enum gdb_signal) sig;
7506 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
7509 case 'w': /* Thread exited. */
7513 event->ws.kind = TARGET_WAITKIND_THREAD_EXITED;
7514 p = unpack_varlen_hex (&buf[1], &value);
7515 event->ws.value.integer = value;
7517 error (_("stop reply packet badly formatted: %s"), buf);
7518 event->ptid = read_ptid (++p, NULL);
7521 case 'W': /* Target exited. */
7527 /* GDB used to accept only 2 hex chars here. Stubs should
7528 only send more if they detect GDB supports multi-process
7530 p = unpack_varlen_hex (&buf[1], &value);
7534 /* The remote process exited. */
7535 event->ws.kind = TARGET_WAITKIND_EXITED;
7536 event->ws.value.integer = value;
7540 /* The remote process exited with a signal. */
7541 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
7542 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
7543 event->ws.value.sig = (enum gdb_signal) value;
7545 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
7548 /* If no process is specified, assume inferior_ptid. */
7549 pid = inferior_ptid.pid ();
7558 else if (startswith (p, "process:"))
7562 p += sizeof ("process:") - 1;
7563 unpack_varlen_hex (p, &upid);
7567 error (_("unknown stop reply packet: %s"), buf);
7570 error (_("unknown stop reply packet: %s"), buf);
7571 event->ptid = ptid_t (pid);
7575 event->ws.kind = TARGET_WAITKIND_NO_RESUMED;
7576 event->ptid = minus_one_ptid;
7580 if (target_is_non_stop_p () && event->ptid == null_ptid)
7581 error (_("No process or thread specified in stop reply: %s"), buf);
7584 /* When the stub wants to tell GDB about a new notification reply, it
7585 sends a notification (%Stop, for example). Those can come it at
7586 any time, hence, we have to make sure that any pending
7587 putpkt/getpkt sequence we're making is finished, before querying
7588 the stub for more events with the corresponding ack command
7589 (vStopped, for example). E.g., if we started a vStopped sequence
7590 immediately upon receiving the notification, something like this
7598 1.6) <-- (registers reply to step #1.3)
7600 Obviously, the reply in step #1.6 would be unexpected to a vStopped
7603 To solve this, whenever we parse a %Stop notification successfully,
7604 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
7605 doing whatever we were doing:
7611 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
7612 2.5) <-- (registers reply to step #2.3)
7614 Eventualy after step #2.5, we return to the event loop, which
7615 notices there's an event on the
7616 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
7617 associated callback --- the function below. At this point, we're
7618 always safe to start a vStopped sequence. :
7621 2.7) <-- T05 thread:2
7627 remote_target::remote_notif_get_pending_events (notif_client *nc)
7629 struct remote_state *rs = get_remote_state ();
7631 if (rs->notif_state->pending_event[nc->id] != NULL)
7634 fprintf_unfiltered (gdb_stdlog,
7635 "notif: process: '%s' ack pending event\n",
7639 nc->ack (this, nc, rs->buf, rs->notif_state->pending_event[nc->id]);
7640 rs->notif_state->pending_event[nc->id] = NULL;
7644 getpkt (&rs->buf, &rs->buf_size, 0);
7645 if (strcmp (rs->buf, "OK") == 0)
7648 remote_notif_ack (this, nc, rs->buf);
7654 fprintf_unfiltered (gdb_stdlog,
7655 "notif: process: '%s' no pending reply\n",
7660 /* Wrapper around remote_target::remote_notif_get_pending_events to
7661 avoid having to export the whole remote_target class. */
7664 remote_notif_get_pending_events (remote_target *remote, notif_client *nc)
7666 remote->remote_notif_get_pending_events (nc);
7669 /* Called when it is decided that STOP_REPLY holds the info of the
7670 event that is to be returned to the core. This function always
7671 destroys STOP_REPLY. */
7674 remote_target::process_stop_reply (struct stop_reply *stop_reply,
7675 struct target_waitstatus *status)
7679 *status = stop_reply->ws;
7680 ptid = stop_reply->ptid;
7682 /* If no thread/process was reported by the stub, assume the current
7684 if (ptid == null_ptid)
7685 ptid = inferior_ptid;
7687 if (status->kind != TARGET_WAITKIND_EXITED
7688 && status->kind != TARGET_WAITKIND_SIGNALLED
7689 && status->kind != TARGET_WAITKIND_NO_RESUMED)
7691 /* Expedited registers. */
7692 if (stop_reply->regcache)
7694 struct regcache *regcache
7695 = get_thread_arch_regcache (ptid, stop_reply->arch);
7700 VEC_iterate (cached_reg_t, stop_reply->regcache, ix, reg);
7703 regcache->raw_supply (reg->num, reg->data);
7707 VEC_free (cached_reg_t, stop_reply->regcache);
7710 remote_notice_new_inferior (ptid, 0);
7711 remote_thread_info *remote_thr = get_remote_thread_info (ptid);
7712 remote_thr->core = stop_reply->core;
7713 remote_thr->stop_reason = stop_reply->stop_reason;
7714 remote_thr->watch_data_address = stop_reply->watch_data_address;
7715 remote_thr->vcont_resumed = 0;
7718 stop_reply_xfree (stop_reply);
7722 /* The non-stop mode version of target_wait. */
7725 remote_target::wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
7727 struct remote_state *rs = get_remote_state ();
7728 struct stop_reply *stop_reply;
7732 /* If in non-stop mode, get out of getpkt even if a
7733 notification is received. */
7735 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7736 0 /* forever */, &is_notif);
7739 if (ret != -1 && !is_notif)
7742 case 'E': /* Error of some sort. */
7743 /* We're out of sync with the target now. Did it continue
7744 or not? We can't tell which thread it was in non-stop,
7745 so just ignore this. */
7746 warning (_("Remote failure reply: %s"), rs->buf);
7748 case 'O': /* Console output. */
7749 remote_console_output (rs->buf + 1);
7752 warning (_("Invalid remote reply: %s"), rs->buf);
7756 /* Acknowledge a pending stop reply that may have arrived in the
7758 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
7759 remote_notif_get_pending_events (¬if_client_stop);
7761 /* If indeed we noticed a stop reply, we're done. */
7762 stop_reply = queued_stop_reply (ptid);
7763 if (stop_reply != NULL)
7764 return process_stop_reply (stop_reply, status);
7766 /* Still no event. If we're just polling for an event, then
7767 return to the event loop. */
7768 if (options & TARGET_WNOHANG)
7770 status->kind = TARGET_WAITKIND_IGNORE;
7771 return minus_one_ptid;
7774 /* Otherwise do a blocking wait. */
7775 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7776 1 /* forever */, &is_notif);
7780 /* Wait until the remote machine stops, then return, storing status in
7781 STATUS just as `wait' would. */
7784 remote_target::wait_as (ptid_t ptid, target_waitstatus *status, int options)
7786 struct remote_state *rs = get_remote_state ();
7787 ptid_t event_ptid = null_ptid;
7789 struct stop_reply *stop_reply;
7793 status->kind = TARGET_WAITKIND_IGNORE;
7794 status->value.integer = 0;
7796 stop_reply = queued_stop_reply (ptid);
7797 if (stop_reply != NULL)
7798 return process_stop_reply (stop_reply, status);
7800 if (rs->cached_wait_status)
7801 /* Use the cached wait status, but only once. */
7802 rs->cached_wait_status = 0;
7807 int forever = ((options & TARGET_WNOHANG) == 0
7808 && rs->wait_forever_enabled_p);
7810 if (!rs->waiting_for_stop_reply)
7812 status->kind = TARGET_WAITKIND_NO_RESUMED;
7813 return minus_one_ptid;
7816 /* FIXME: cagney/1999-09-27: If we're in async mode we should
7817 _never_ wait for ever -> test on target_is_async_p().
7818 However, before we do that we need to ensure that the caller
7819 knows how to take the target into/out of async mode. */
7820 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7821 forever, &is_notif);
7823 /* GDB gets a notification. Return to core as this event is
7825 if (ret != -1 && is_notif)
7826 return minus_one_ptid;
7828 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
7829 return minus_one_ptid;
7834 /* Assume that the target has acknowledged Ctrl-C unless we receive
7835 an 'F' or 'O' packet. */
7836 if (buf[0] != 'F' && buf[0] != 'O')
7837 rs->ctrlc_pending_p = 0;
7841 case 'E': /* Error of some sort. */
7842 /* We're out of sync with the target now. Did it continue or
7843 not? Not is more likely, so report a stop. */
7844 rs->waiting_for_stop_reply = 0;
7846 warning (_("Remote failure reply: %s"), buf);
7847 status->kind = TARGET_WAITKIND_STOPPED;
7848 status->value.sig = GDB_SIGNAL_0;
7850 case 'F': /* File-I/O request. */
7851 /* GDB may access the inferior memory while handling the File-I/O
7852 request, but we don't want GDB accessing memory while waiting
7853 for a stop reply. See the comments in putpkt_binary. Set
7854 waiting_for_stop_reply to 0 temporarily. */
7855 rs->waiting_for_stop_reply = 0;
7856 remote_fileio_request (this, buf, rs->ctrlc_pending_p);
7857 rs->ctrlc_pending_p = 0;
7858 /* GDB handled the File-I/O request, and the target is running
7859 again. Keep waiting for events. */
7860 rs->waiting_for_stop_reply = 1;
7862 case 'N': case 'T': case 'S': case 'X': case 'W':
7864 /* There is a stop reply to handle. */
7865 rs->waiting_for_stop_reply = 0;
7868 = (struct stop_reply *) remote_notif_parse (this,
7872 event_ptid = process_stop_reply (stop_reply, status);
7875 case 'O': /* Console output. */
7876 remote_console_output (buf + 1);
7879 if (rs->last_sent_signal != GDB_SIGNAL_0)
7881 /* Zero length reply means that we tried 'S' or 'C' and the
7882 remote system doesn't support it. */
7883 target_terminal::ours_for_output ();
7885 ("Can't send signals to this remote system. %s not sent.\n",
7886 gdb_signal_to_name (rs->last_sent_signal));
7887 rs->last_sent_signal = GDB_SIGNAL_0;
7888 target_terminal::inferior ();
7890 strcpy (buf, rs->last_sent_step ? "s" : "c");
7896 warning (_("Invalid remote reply: %s"), buf);
7900 if (status->kind == TARGET_WAITKIND_NO_RESUMED)
7901 return minus_one_ptid;
7902 else if (status->kind == TARGET_WAITKIND_IGNORE)
7904 /* Nothing interesting happened. If we're doing a non-blocking
7905 poll, we're done. Otherwise, go back to waiting. */
7906 if (options & TARGET_WNOHANG)
7907 return minus_one_ptid;
7911 else if (status->kind != TARGET_WAITKIND_EXITED
7912 && status->kind != TARGET_WAITKIND_SIGNALLED)
7914 if (event_ptid != null_ptid)
7915 record_currthread (rs, event_ptid);
7917 event_ptid = inferior_ptid;
7920 /* A process exit. Invalidate our notion of current thread. */
7921 record_currthread (rs, minus_one_ptid);
7926 /* Wait until the remote machine stops, then return, storing status in
7927 STATUS just as `wait' would. */
7930 remote_target::wait (ptid_t ptid, struct target_waitstatus *status, int options)
7934 if (target_is_non_stop_p ())
7935 event_ptid = wait_ns (ptid, status, options);
7937 event_ptid = wait_as (ptid, status, options);
7939 if (target_is_async_p ())
7941 remote_state *rs = get_remote_state ();
7943 /* If there are are events left in the queue tell the event loop
7945 if (!rs->stop_reply_queue.empty ())
7946 mark_async_event_handler (rs->remote_async_inferior_event_token);
7952 /* Fetch a single register using a 'p' packet. */
7955 remote_target::fetch_register_using_p (struct regcache *regcache,
7958 struct gdbarch *gdbarch = regcache->arch ();
7959 struct remote_state *rs = get_remote_state ();
7961 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
7964 if (packet_support (PACKET_p) == PACKET_DISABLE)
7967 if (reg->pnum == -1)
7972 p += hexnumstr (p, reg->pnum);
7975 getpkt (&rs->buf, &rs->buf_size, 0);
7979 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
7983 case PACKET_UNKNOWN:
7986 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
7987 gdbarch_register_name (regcache->arch (),
7992 /* If this register is unfetchable, tell the regcache. */
7995 regcache->raw_supply (reg->regnum, NULL);
7999 /* Otherwise, parse and supply the value. */
8005 error (_("fetch_register_using_p: early buf termination"));
8007 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
8010 regcache->raw_supply (reg->regnum, regp);
8014 /* Fetch the registers included in the target's 'g' packet. */
8017 remote_target::send_g_packet ()
8019 struct remote_state *rs = get_remote_state ();
8022 xsnprintf (rs->buf, get_remote_packet_size (), "g");
8024 getpkt (&rs->buf, &rs->buf_size, 0);
8025 if (packet_check_result (rs->buf) == PACKET_ERROR)
8026 error (_("Could not read registers; remote failure reply '%s'"),
8029 /* We can get out of synch in various cases. If the first character
8030 in the buffer is not a hex character, assume that has happened
8031 and try to fetch another packet to read. */
8032 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
8033 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
8034 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
8035 && rs->buf[0] != 'x') /* New: unavailable register value. */
8038 fprintf_unfiltered (gdb_stdlog,
8039 "Bad register packet; fetching a new packet\n");
8040 getpkt (&rs->buf, &rs->buf_size, 0);
8043 buf_len = strlen (rs->buf);
8045 /* Sanity check the received packet. */
8046 if (buf_len % 2 != 0)
8047 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
8053 remote_target::process_g_packet (struct regcache *regcache)
8055 struct gdbarch *gdbarch = regcache->arch ();
8056 struct remote_state *rs = get_remote_state ();
8057 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8062 buf_len = strlen (rs->buf);
8064 /* Further sanity checks, with knowledge of the architecture. */
8065 if (buf_len > 2 * rsa->sizeof_g_packet)
8066 error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
8067 "bytes): %s"), rsa->sizeof_g_packet, buf_len / 2, rs->buf);
8069 /* Save the size of the packet sent to us by the target. It is used
8070 as a heuristic when determining the max size of packets that the
8071 target can safely receive. */
8072 if (rsa->actual_register_packet_size == 0)
8073 rsa->actual_register_packet_size = buf_len;
8075 /* If this is smaller than we guessed the 'g' packet would be,
8076 update our records. A 'g' reply that doesn't include a register's
8077 value implies either that the register is not available, or that
8078 the 'p' packet must be used. */
8079 if (buf_len < 2 * rsa->sizeof_g_packet)
8081 long sizeof_g_packet = buf_len / 2;
8083 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8085 long offset = rsa->regs[i].offset;
8086 long reg_size = register_size (gdbarch, i);
8088 if (rsa->regs[i].pnum == -1)
8091 if (offset >= sizeof_g_packet)
8092 rsa->regs[i].in_g_packet = 0;
8093 else if (offset + reg_size > sizeof_g_packet)
8094 error (_("Truncated register %d in remote 'g' packet"), i);
8096 rsa->regs[i].in_g_packet = 1;
8099 /* Looks valid enough, we can assume this is the correct length
8100 for a 'g' packet. It's important not to adjust
8101 rsa->sizeof_g_packet if we have truncated registers otherwise
8102 this "if" won't be run the next time the method is called
8103 with a packet of the same size and one of the internal errors
8104 below will trigger instead. */
8105 rsa->sizeof_g_packet = sizeof_g_packet;
8108 regs = (char *) alloca (rsa->sizeof_g_packet);
8110 /* Unimplemented registers read as all bits zero. */
8111 memset (regs, 0, rsa->sizeof_g_packet);
8113 /* Reply describes registers byte by byte, each byte encoded as two
8114 hex characters. Suck them all up, then supply them to the
8115 register cacheing/storage mechanism. */
8118 for (i = 0; i < rsa->sizeof_g_packet; i++)
8120 if (p[0] == 0 || p[1] == 0)
8121 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
8122 internal_error (__FILE__, __LINE__,
8123 _("unexpected end of 'g' packet reply"));
8125 if (p[0] == 'x' && p[1] == 'x')
8126 regs[i] = 0; /* 'x' */
8128 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
8132 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8134 struct packet_reg *r = &rsa->regs[i];
8135 long reg_size = register_size (gdbarch, i);
8139 if ((r->offset + reg_size) * 2 > strlen (rs->buf))
8140 /* This shouldn't happen - we adjusted in_g_packet above. */
8141 internal_error (__FILE__, __LINE__,
8142 _("unexpected end of 'g' packet reply"));
8143 else if (rs->buf[r->offset * 2] == 'x')
8145 gdb_assert (r->offset * 2 < strlen (rs->buf));
8146 /* The register isn't available, mark it as such (at
8147 the same time setting the value to zero). */
8148 regcache->raw_supply (r->regnum, NULL);
8151 regcache->raw_supply (r->regnum, regs + r->offset);
8157 remote_target::fetch_registers_using_g (struct regcache *regcache)
8160 process_g_packet (regcache);
8163 /* Make the remote selected traceframe match GDB's selected
8167 remote_target::set_remote_traceframe ()
8170 struct remote_state *rs = get_remote_state ();
8172 if (rs->remote_traceframe_number == get_traceframe_number ())
8175 /* Avoid recursion, remote_trace_find calls us again. */
8176 rs->remote_traceframe_number = get_traceframe_number ();
8178 newnum = target_trace_find (tfind_number,
8179 get_traceframe_number (), 0, 0, NULL);
8181 /* Should not happen. If it does, all bets are off. */
8182 if (newnum != get_traceframe_number ())
8183 warning (_("could not set remote traceframe"));
8187 remote_target::fetch_registers (struct regcache *regcache, int regnum)
8189 struct gdbarch *gdbarch = regcache->arch ();
8190 struct remote_state *rs = get_remote_state ();
8191 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8194 set_remote_traceframe ();
8195 set_general_thread (regcache->ptid ());
8199 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8201 gdb_assert (reg != NULL);
8203 /* If this register might be in the 'g' packet, try that first -
8204 we are likely to read more than one register. If this is the
8205 first 'g' packet, we might be overly optimistic about its
8206 contents, so fall back to 'p'. */
8207 if (reg->in_g_packet)
8209 fetch_registers_using_g (regcache);
8210 if (reg->in_g_packet)
8214 if (fetch_register_using_p (regcache, reg))
8217 /* This register is not available. */
8218 regcache->raw_supply (reg->regnum, NULL);
8223 fetch_registers_using_g (regcache);
8225 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8226 if (!rsa->regs[i].in_g_packet)
8227 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
8229 /* This register is not available. */
8230 regcache->raw_supply (i, NULL);
8234 /* Prepare to store registers. Since we may send them all (using a
8235 'G' request), we have to read out the ones we don't want to change
8239 remote_target::prepare_to_store (struct regcache *regcache)
8241 struct remote_state *rs = get_remote_state ();
8242 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
8245 /* Make sure the entire registers array is valid. */
8246 switch (packet_support (PACKET_P))
8248 case PACKET_DISABLE:
8249 case PACKET_SUPPORT_UNKNOWN:
8250 /* Make sure all the necessary registers are cached. */
8251 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8252 if (rsa->regs[i].in_g_packet)
8253 regcache->raw_update (rsa->regs[i].regnum);
8260 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
8261 packet was not recognized. */
8264 remote_target::store_register_using_P (const struct regcache *regcache,
8267 struct gdbarch *gdbarch = regcache->arch ();
8268 struct remote_state *rs = get_remote_state ();
8269 /* Try storing a single register. */
8270 char *buf = rs->buf;
8271 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
8274 if (packet_support (PACKET_P) == PACKET_DISABLE)
8277 if (reg->pnum == -1)
8280 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
8281 p = buf + strlen (buf);
8282 regcache->raw_collect (reg->regnum, regp);
8283 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
8285 getpkt (&rs->buf, &rs->buf_size, 0);
8287 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
8292 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
8293 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
8294 case PACKET_UNKNOWN:
8297 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8301 /* Store register REGNUM, or all registers if REGNUM == -1, from the
8302 contents of the register cache buffer. FIXME: ignores errors. */
8305 remote_target::store_registers_using_G (const struct regcache *regcache)
8307 struct remote_state *rs = get_remote_state ();
8308 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
8312 /* Extract all the registers in the regcache copying them into a
8317 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
8318 memset (regs, 0, rsa->sizeof_g_packet);
8319 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8321 struct packet_reg *r = &rsa->regs[i];
8324 regcache->raw_collect (r->regnum, regs + r->offset);
8328 /* Command describes registers byte by byte,
8329 each byte encoded as two hex characters. */
8332 bin2hex (regs, p, rsa->sizeof_g_packet);
8334 getpkt (&rs->buf, &rs->buf_size, 0);
8335 if (packet_check_result (rs->buf) == PACKET_ERROR)
8336 error (_("Could not write registers; remote failure reply '%s'"),
8340 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
8341 of the register cache buffer. FIXME: ignores errors. */
8344 remote_target::store_registers (struct regcache *regcache, int regnum)
8346 struct gdbarch *gdbarch = regcache->arch ();
8347 struct remote_state *rs = get_remote_state ();
8348 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8351 set_remote_traceframe ();
8352 set_general_thread (regcache->ptid ());
8356 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8358 gdb_assert (reg != NULL);
8360 /* Always prefer to store registers using the 'P' packet if
8361 possible; we often change only a small number of registers.
8362 Sometimes we change a larger number; we'd need help from a
8363 higher layer to know to use 'G'. */
8364 if (store_register_using_P (regcache, reg))
8367 /* For now, don't complain if we have no way to write the
8368 register. GDB loses track of unavailable registers too
8369 easily. Some day, this may be an error. We don't have
8370 any way to read the register, either... */
8371 if (!reg->in_g_packet)
8374 store_registers_using_G (regcache);
8378 store_registers_using_G (regcache);
8380 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8381 if (!rsa->regs[i].in_g_packet)
8382 if (!store_register_using_P (regcache, &rsa->regs[i]))
8383 /* See above for why we do not issue an error here. */
8388 /* Return the number of hex digits in num. */
8391 hexnumlen (ULONGEST num)
8395 for (i = 0; num != 0; i++)
8398 return std::max (i, 1);
8401 /* Set BUF to the minimum number of hex digits representing NUM. */
8404 hexnumstr (char *buf, ULONGEST num)
8406 int len = hexnumlen (num);
8408 return hexnumnstr (buf, num, len);
8412 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
8415 hexnumnstr (char *buf, ULONGEST num, int width)
8421 for (i = width - 1; i >= 0; i--)
8423 buf[i] = "0123456789abcdef"[(num & 0xf)];
8430 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
8433 remote_address_masked (CORE_ADDR addr)
8435 unsigned int address_size = remote_address_size;
8437 /* If "remoteaddresssize" was not set, default to target address size. */
8439 address_size = gdbarch_addr_bit (target_gdbarch ());
8441 if (address_size > 0
8442 && address_size < (sizeof (ULONGEST) * 8))
8444 /* Only create a mask when that mask can safely be constructed
8445 in a ULONGEST variable. */
8448 mask = (mask << address_size) - 1;
8454 /* Determine whether the remote target supports binary downloading.
8455 This is accomplished by sending a no-op memory write of zero length
8456 to the target at the specified address. It does not suffice to send
8457 the whole packet, since many stubs strip the eighth bit and
8458 subsequently compute a wrong checksum, which causes real havoc with
8461 NOTE: This can still lose if the serial line is not eight-bit
8462 clean. In cases like this, the user should clear "remote
8466 remote_target::check_binary_download (CORE_ADDR addr)
8468 struct remote_state *rs = get_remote_state ();
8470 switch (packet_support (PACKET_X))
8472 case PACKET_DISABLE:
8476 case PACKET_SUPPORT_UNKNOWN:
8482 p += hexnumstr (p, (ULONGEST) addr);
8484 p += hexnumstr (p, (ULONGEST) 0);
8488 putpkt_binary (rs->buf, (int) (p - rs->buf));
8489 getpkt (&rs->buf, &rs->buf_size, 0);
8491 if (rs->buf[0] == '\0')
8494 fprintf_unfiltered (gdb_stdlog,
8495 "binary downloading NOT "
8496 "supported by target\n");
8497 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
8502 fprintf_unfiltered (gdb_stdlog,
8503 "binary downloading supported by target\n");
8504 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
8511 /* Helper function to resize the payload in order to try to get a good
8512 alignment. We try to write an amount of data such that the next write will
8513 start on an address aligned on REMOTE_ALIGN_WRITES. */
8516 align_for_efficient_write (int todo, CORE_ADDR memaddr)
8518 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
8521 /* Write memory data directly to the remote machine.
8522 This does not inform the data cache; the data cache uses this.
8523 HEADER is the starting part of the packet.
8524 MEMADDR is the address in the remote memory space.
8525 MYADDR is the address of the buffer in our space.
8526 LEN_UNITS is the number of addressable units to write.
8527 UNIT_SIZE is the length in bytes of an addressable unit.
8528 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
8529 should send data as binary ('X'), or hex-encoded ('M').
8531 The function creates packet of the form
8532 <HEADER><ADDRESS>,<LENGTH>:<DATA>
8534 where encoding of <DATA> is terminated by PACKET_FORMAT.
8536 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
8539 Return the transferred status, error or OK (an
8540 'enum target_xfer_status' value). Save the number of addressable units
8541 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
8543 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
8544 exchange between gdb and the stub could look like (?? in place of the
8550 -> $M1000,3:eeeeffffeeee#??
8554 <- eeeeffffeeeedddd */
8557 remote_target::remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
8558 const gdb_byte *myaddr,
8561 ULONGEST *xfered_len_units,
8562 char packet_format, int use_length)
8564 struct remote_state *rs = get_remote_state ();
8570 int payload_capacity_bytes;
8571 int payload_length_bytes;
8573 if (packet_format != 'X' && packet_format != 'M')
8574 internal_error (__FILE__, __LINE__,
8575 _("remote_write_bytes_aux: bad packet format"));
8578 return TARGET_XFER_EOF;
8580 payload_capacity_bytes = get_memory_write_packet_size ();
8582 /* The packet buffer will be large enough for the payload;
8583 get_memory_packet_size ensures this. */
8586 /* Compute the size of the actual payload by subtracting out the
8587 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
8589 payload_capacity_bytes -= strlen ("$,:#NN");
8591 /* The comma won't be used. */
8592 payload_capacity_bytes += 1;
8593 payload_capacity_bytes -= strlen (header);
8594 payload_capacity_bytes -= hexnumlen (memaddr);
8596 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
8598 strcat (rs->buf, header);
8599 p = rs->buf + strlen (header);
8601 /* Compute a best guess of the number of bytes actually transfered. */
8602 if (packet_format == 'X')
8604 /* Best guess at number of bytes that will fit. */
8605 todo_units = std::min (len_units,
8606 (ULONGEST) payload_capacity_bytes / unit_size);
8608 payload_capacity_bytes -= hexnumlen (todo_units);
8609 todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
8613 /* Number of bytes that will fit. */
8615 = std::min (len_units,
8616 (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
8618 payload_capacity_bytes -= hexnumlen (todo_units);
8619 todo_units = std::min (todo_units,
8620 (payload_capacity_bytes / unit_size) / 2);
8623 if (todo_units <= 0)
8624 internal_error (__FILE__, __LINE__,
8625 _("minimum packet size too small to write data"));
8627 /* If we already need another packet, then try to align the end
8628 of this packet to a useful boundary. */
8629 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
8630 todo_units = align_for_efficient_write (todo_units, memaddr);
8632 /* Append "<memaddr>". */
8633 memaddr = remote_address_masked (memaddr);
8634 p += hexnumstr (p, (ULONGEST) memaddr);
8641 /* Append the length and retain its location and size. It may need to be
8642 adjusted once the packet body has been created. */
8644 plenlen = hexnumstr (p, (ULONGEST) todo_units);
8652 /* Append the packet body. */
8653 if (packet_format == 'X')
8655 /* Binary mode. Send target system values byte by byte, in
8656 increasing byte addresses. Only escape certain critical
8658 payload_length_bytes =
8659 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
8660 &units_written, payload_capacity_bytes);
8662 /* If not all TODO units fit, then we'll need another packet. Make
8663 a second try to keep the end of the packet aligned. Don't do
8664 this if the packet is tiny. */
8665 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
8669 new_todo_units = align_for_efficient_write (units_written, memaddr);
8671 if (new_todo_units != units_written)
8672 payload_length_bytes =
8673 remote_escape_output (myaddr, new_todo_units, unit_size,
8674 (gdb_byte *) p, &units_written,
8675 payload_capacity_bytes);
8678 p += payload_length_bytes;
8679 if (use_length && units_written < todo_units)
8681 /* Escape chars have filled up the buffer prematurely,
8682 and we have actually sent fewer units than planned.
8683 Fix-up the length field of the packet. Use the same
8684 number of characters as before. */
8685 plen += hexnumnstr (plen, (ULONGEST) units_written,
8687 *plen = ':'; /* overwrite \0 from hexnumnstr() */
8692 /* Normal mode: Send target system values byte by byte, in
8693 increasing byte addresses. Each byte is encoded as a two hex
8695 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
8696 units_written = todo_units;
8699 putpkt_binary (rs->buf, (int) (p - rs->buf));
8700 getpkt (&rs->buf, &rs->buf_size, 0);
8702 if (rs->buf[0] == 'E')
8703 return TARGET_XFER_E_IO;
8705 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
8706 send fewer units than we'd planned. */
8707 *xfered_len_units = (ULONGEST) units_written;
8708 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
8711 /* Write memory data directly to the remote machine.
8712 This does not inform the data cache; the data cache uses this.
8713 MEMADDR is the address in the remote memory space.
8714 MYADDR is the address of the buffer in our space.
8715 LEN is the number of bytes.
8717 Return the transferred status, error or OK (an
8718 'enum target_xfer_status' value). Save the number of bytes
8719 transferred in *XFERED_LEN. Only transfer a single packet. */
8722 remote_target::remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr,
8723 ULONGEST len, int unit_size,
8724 ULONGEST *xfered_len)
8726 const char *packet_format = NULL;
8728 /* Check whether the target supports binary download. */
8729 check_binary_download (memaddr);
8731 switch (packet_support (PACKET_X))
8734 packet_format = "X";
8736 case PACKET_DISABLE:
8737 packet_format = "M";
8739 case PACKET_SUPPORT_UNKNOWN:
8740 internal_error (__FILE__, __LINE__,
8741 _("remote_write_bytes: bad internal state"));
8743 internal_error (__FILE__, __LINE__, _("bad switch"));
8746 return remote_write_bytes_aux (packet_format,
8747 memaddr, myaddr, len, unit_size, xfered_len,
8748 packet_format[0], 1);
8751 /* Read memory data directly from the remote machine.
8752 This does not use the data cache; the data cache uses this.
8753 MEMADDR is the address in the remote memory space.
8754 MYADDR is the address of the buffer in our space.
8755 LEN_UNITS is the number of addressable memory units to read..
8756 UNIT_SIZE is the length in bytes of an addressable unit.
8758 Return the transferred status, error or OK (an
8759 'enum target_xfer_status' value). Save the number of bytes
8760 transferred in *XFERED_LEN_UNITS.
8762 See the comment of remote_write_bytes_aux for an example of
8763 memory read/write exchange between gdb and the stub. */
8766 remote_target::remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
8768 int unit_size, ULONGEST *xfered_len_units)
8770 struct remote_state *rs = get_remote_state ();
8771 int buf_size_bytes; /* Max size of packet output buffer. */
8776 buf_size_bytes = get_memory_read_packet_size ();
8777 /* The packet buffer will be large enough for the payload;
8778 get_memory_packet_size ensures this. */
8780 /* Number of units that will fit. */
8781 todo_units = std::min (len_units,
8782 (ULONGEST) (buf_size_bytes / unit_size) / 2);
8784 /* Construct "m"<memaddr>","<len>". */
8785 memaddr = remote_address_masked (memaddr);
8788 p += hexnumstr (p, (ULONGEST) memaddr);
8790 p += hexnumstr (p, (ULONGEST) todo_units);
8793 getpkt (&rs->buf, &rs->buf_size, 0);
8794 if (rs->buf[0] == 'E'
8795 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
8796 && rs->buf[3] == '\0')
8797 return TARGET_XFER_E_IO;
8798 /* Reply describes memory byte by byte, each byte encoded as two hex
8801 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
8802 /* Return what we have. Let higher layers handle partial reads. */
8803 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
8804 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
8807 /* Using the set of read-only target sections of remote, read live
8810 For interface/parameters/return description see target.h,
8814 remote_target::remote_xfer_live_readonly_partial (gdb_byte *readbuf,
8818 ULONGEST *xfered_len)
8820 struct target_section *secp;
8821 struct target_section_table *table;
8823 secp = target_section_by_addr (this, memaddr);
8825 && (bfd_get_section_flags (secp->the_bfd_section->owner,
8826 secp->the_bfd_section)
8829 struct target_section *p;
8830 ULONGEST memend = memaddr + len;
8832 table = target_get_section_table (this);
8834 for (p = table->sections; p < table->sections_end; p++)
8836 if (memaddr >= p->addr)
8838 if (memend <= p->endaddr)
8840 /* Entire transfer is within this section. */
8841 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
8844 else if (memaddr >= p->endaddr)
8846 /* This section ends before the transfer starts. */
8851 /* This section overlaps the transfer. Just do half. */
8852 len = p->endaddr - memaddr;
8853 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
8860 return TARGET_XFER_EOF;
8863 /* Similar to remote_read_bytes_1, but it reads from the remote stub
8864 first if the requested memory is unavailable in traceframe.
8865 Otherwise, fall back to remote_read_bytes_1. */
8868 remote_target::remote_read_bytes (CORE_ADDR memaddr,
8869 gdb_byte *myaddr, ULONGEST len, int unit_size,
8870 ULONGEST *xfered_len)
8873 return TARGET_XFER_EOF;
8875 if (get_traceframe_number () != -1)
8877 std::vector<mem_range> available;
8879 /* If we fail to get the set of available memory, then the
8880 target does not support querying traceframe info, and so we
8881 attempt reading from the traceframe anyway (assuming the
8882 target implements the old QTro packet then). */
8883 if (traceframe_available_memory (&available, memaddr, len))
8885 if (available.empty () || available[0].start != memaddr)
8887 enum target_xfer_status res;
8889 /* Don't read into the traceframe's available
8891 if (!available.empty ())
8893 LONGEST oldlen = len;
8895 len = available[0].start - memaddr;
8896 gdb_assert (len <= oldlen);
8899 /* This goes through the topmost target again. */
8900 res = remote_xfer_live_readonly_partial (myaddr, memaddr,
8901 len, unit_size, xfered_len);
8902 if (res == TARGET_XFER_OK)
8903 return TARGET_XFER_OK;
8906 /* No use trying further, we know some memory starting
8907 at MEMADDR isn't available. */
8909 return (*xfered_len != 0) ?
8910 TARGET_XFER_UNAVAILABLE : TARGET_XFER_EOF;
8914 /* Don't try to read more than how much is available, in
8915 case the target implements the deprecated QTro packet to
8916 cater for older GDBs (the target's knowledge of read-only
8917 sections may be outdated by now). */
8918 len = available[0].length;
8922 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
8927 /* Sends a packet with content determined by the printf format string
8928 FORMAT and the remaining arguments, then gets the reply. Returns
8929 whether the packet was a success, a failure, or unknown. */
8932 remote_target::remote_send_printf (const char *format, ...)
8934 struct remote_state *rs = get_remote_state ();
8935 int max_size = get_remote_packet_size ();
8938 va_start (ap, format);
8941 int size = vsnprintf (rs->buf, max_size, format, ap);
8945 if (size >= max_size)
8946 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
8948 if (putpkt (rs->buf) < 0)
8949 error (_("Communication problem with target."));
8952 getpkt (&rs->buf, &rs->buf_size, 0);
8954 return packet_check_result (rs->buf);
8957 /* Flash writing can take quite some time. We'll set
8958 effectively infinite timeout for flash operations.
8959 In future, we'll need to decide on a better approach. */
8960 static const int remote_flash_timeout = 1000;
8963 remote_target::flash_erase (ULONGEST address, LONGEST length)
8965 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
8966 enum packet_result ret;
8967 scoped_restore restore_timeout
8968 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8970 ret = remote_send_printf ("vFlashErase:%s,%s",
8971 phex (address, addr_size),
8975 case PACKET_UNKNOWN:
8976 error (_("Remote target does not support flash erase"));
8978 error (_("Error erasing flash with vFlashErase packet"));
8985 remote_target::remote_flash_write (ULONGEST address,
8986 ULONGEST length, ULONGEST *xfered_len,
8987 const gdb_byte *data)
8989 scoped_restore restore_timeout
8990 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8991 return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
8996 remote_target::flash_done ()
9000 scoped_restore restore_timeout
9001 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9003 ret = remote_send_printf ("vFlashDone");
9007 case PACKET_UNKNOWN:
9008 error (_("Remote target does not support vFlashDone"));
9010 error (_("Error finishing flash operation"));
9017 remote_target::files_info ()
9019 puts_filtered ("Debugging a target over a serial line.\n");
9022 /* Stuff for dealing with the packets which are part of this protocol.
9023 See comment at top of file for details. */
9025 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
9026 error to higher layers. Called when a serial error is detected.
9027 The exception message is STRING, followed by a colon and a blank,
9028 the system error message for errno at function entry and final dot
9029 for output compatibility with throw_perror_with_name. */
9032 unpush_and_perror (const char *string)
9034 int saved_errno = errno;
9036 remote_unpush_target ();
9037 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
9038 safe_strerror (saved_errno));
9041 /* Read a single character from the remote end. The current quit
9042 handler is overridden to avoid quitting in the middle of packet
9043 sequence, as that would break communication with the remote server.
9044 See remote_serial_quit_handler for more detail. */
9047 remote_target::readchar (int timeout)
9050 struct remote_state *rs = get_remote_state ();
9053 scoped_restore restore_quit_target
9054 = make_scoped_restore (&curr_quit_handler_target, this);
9055 scoped_restore restore_quit
9056 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9058 rs->got_ctrlc_during_io = 0;
9060 ch = serial_readchar (rs->remote_desc, timeout);
9062 if (rs->got_ctrlc_during_io)
9069 switch ((enum serial_rc) ch)
9072 remote_unpush_target ();
9073 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
9076 unpush_and_perror (_("Remote communication error. "
9077 "Target disconnected."));
9079 case SERIAL_TIMEOUT:
9085 /* Wrapper for serial_write that closes the target and throws if
9086 writing fails. The current quit handler is overridden to avoid
9087 quitting in the middle of packet sequence, as that would break
9088 communication with the remote server. See
9089 remote_serial_quit_handler for more detail. */
9092 remote_target::remote_serial_write (const char *str, int len)
9094 struct remote_state *rs = get_remote_state ();
9096 scoped_restore restore_quit_target
9097 = make_scoped_restore (&curr_quit_handler_target, this);
9098 scoped_restore restore_quit
9099 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9101 rs->got_ctrlc_during_io = 0;
9103 if (serial_write (rs->remote_desc, str, len))
9105 unpush_and_perror (_("Remote communication error. "
9106 "Target disconnected."));
9109 if (rs->got_ctrlc_during_io)
9113 /* Return a string representing an escaped version of BUF, of len N.
9114 E.g. \n is converted to \\n, \t to \\t, etc. */
9117 escape_buffer (const char *buf, int n)
9121 stb.putstrn (buf, n, '\\');
9122 return std::move (stb.string ());
9125 /* Display a null-terminated packet on stdout, for debugging, using C
9129 print_packet (const char *buf)
9131 puts_filtered ("\"");
9132 fputstr_filtered (buf, '"', gdb_stdout);
9133 puts_filtered ("\"");
9137 remote_target::putpkt (const char *buf)
9139 return putpkt_binary (buf, strlen (buf));
9142 /* Wrapper around remote_target::putpkt to avoid exporting
9146 putpkt (remote_target *remote, const char *buf)
9148 return remote->putpkt (buf);
9151 /* Send a packet to the remote machine, with error checking. The data
9152 of the packet is in BUF. The string in BUF can be at most
9153 get_remote_packet_size () - 5 to account for the $, # and checksum,
9154 and for a possible /0 if we are debugging (remote_debug) and want
9155 to print the sent packet as a string. */
9158 remote_target::putpkt_binary (const char *buf, int cnt)
9160 struct remote_state *rs = get_remote_state ();
9162 unsigned char csum = 0;
9163 gdb::def_vector<char> data (cnt + 6);
9164 char *buf2 = data.data ();
9170 /* Catch cases like trying to read memory or listing threads while
9171 we're waiting for a stop reply. The remote server wouldn't be
9172 ready to handle this request, so we'd hang and timeout. We don't
9173 have to worry about this in synchronous mode, because in that
9174 case it's not possible to issue a command while the target is
9175 running. This is not a problem in non-stop mode, because in that
9176 case, the stub is always ready to process serial input. */
9177 if (!target_is_non_stop_p ()
9178 && target_is_async_p ()
9179 && rs->waiting_for_stop_reply)
9181 error (_("Cannot execute this command while the target is running.\n"
9182 "Use the \"interrupt\" command to stop the target\n"
9183 "and then try again."));
9186 /* We're sending out a new packet. Make sure we don't look at a
9187 stale cached response. */
9188 rs->cached_wait_status = 0;
9190 /* Copy the packet into buffer BUF2, encapsulating it
9191 and giving it a checksum. */
9196 for (i = 0; i < cnt; i++)
9202 *p++ = tohex ((csum >> 4) & 0xf);
9203 *p++ = tohex (csum & 0xf);
9205 /* Send it over and over until we get a positive ack. */
9209 int started_error_output = 0;
9215 int len = (int) (p - buf2);
9218 = escape_buffer (buf2, std::min (len, REMOTE_DEBUG_MAX_CHAR));
9220 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s", str.c_str ());
9222 if (len > REMOTE_DEBUG_MAX_CHAR)
9223 fprintf_unfiltered (gdb_stdlog, "[%d bytes omitted]",
9224 len - REMOTE_DEBUG_MAX_CHAR);
9226 fprintf_unfiltered (gdb_stdlog, "...");
9228 gdb_flush (gdb_stdlog);
9230 remote_serial_write (buf2, p - buf2);
9232 /* If this is a no acks version of the remote protocol, send the
9233 packet and move on. */
9237 /* Read until either a timeout occurs (-2) or '+' is read.
9238 Handle any notification that arrives in the mean time. */
9241 ch = readchar (remote_timeout);
9249 case SERIAL_TIMEOUT:
9252 if (started_error_output)
9254 putchar_unfiltered ('\n');
9255 started_error_output = 0;
9264 fprintf_unfiltered (gdb_stdlog, "Ack\n");
9268 fprintf_unfiltered (gdb_stdlog, "Nak\n");
9270 case SERIAL_TIMEOUT:
9274 break; /* Retransmit buffer. */
9278 fprintf_unfiltered (gdb_stdlog,
9279 "Packet instead of Ack, ignoring it\n");
9280 /* It's probably an old response sent because an ACK
9281 was lost. Gobble up the packet and ack it so it
9282 doesn't get retransmitted when we resend this
9285 remote_serial_write ("+", 1);
9286 continue; /* Now, go look for +. */
9293 /* If we got a notification, handle it, and go back to looking
9295 /* We've found the start of a notification. Now
9296 collect the data. */
9297 val = read_frame (&rs->buf, &rs->buf_size);
9302 std::string str = escape_buffer (rs->buf, val);
9304 fprintf_unfiltered (gdb_stdlog,
9305 " Notification received: %s\n",
9308 handle_notification (rs->notif_state, rs->buf);
9309 /* We're in sync now, rewait for the ack. */
9316 if (!started_error_output)
9318 started_error_output = 1;
9319 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
9321 fputc_unfiltered (ch & 0177, gdb_stdlog);
9322 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
9331 if (!started_error_output)
9333 started_error_output = 1;
9334 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
9336 fputc_unfiltered (ch & 0177, gdb_stdlog);
9340 break; /* Here to retransmit. */
9344 /* This is wrong. If doing a long backtrace, the user should be
9345 able to get out next time we call QUIT, without anything as
9346 violent as interrupt_query. If we want to provide a way out of
9347 here without getting to the next QUIT, it should be based on
9348 hitting ^C twice as in remote_wait. */
9360 /* Come here after finding the start of a frame when we expected an
9361 ack. Do our best to discard the rest of this packet. */
9364 remote_target::skip_frame ()
9370 c = readchar (remote_timeout);
9373 case SERIAL_TIMEOUT:
9374 /* Nothing we can do. */
9377 /* Discard the two bytes of checksum and stop. */
9378 c = readchar (remote_timeout);
9380 c = readchar (remote_timeout);
9383 case '*': /* Run length encoding. */
9384 /* Discard the repeat count. */
9385 c = readchar (remote_timeout);
9390 /* A regular character. */
9396 /* Come here after finding the start of the frame. Collect the rest
9397 into *BUF, verifying the checksum, length, and handling run-length
9398 compression. NUL terminate the buffer. If there is not enough room,
9399 expand *BUF using xrealloc.
9401 Returns -1 on error, number of characters in buffer (ignoring the
9402 trailing NULL) on success. (could be extended to return one of the
9403 SERIAL status indications). */
9406 remote_target::read_frame (char **buf_p, long *sizeof_buf)
9412 struct remote_state *rs = get_remote_state ();
9419 c = readchar (remote_timeout);
9422 case SERIAL_TIMEOUT:
9424 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
9428 fputs_filtered ("Saw new packet start in middle of old one\n",
9430 return -1; /* Start a new packet, count retries. */
9433 unsigned char pktcsum;
9439 check_0 = readchar (remote_timeout);
9441 check_1 = readchar (remote_timeout);
9443 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
9446 fputs_filtered ("Timeout in checksum, retrying\n",
9450 else if (check_0 < 0 || check_1 < 0)
9453 fputs_filtered ("Communication error in checksum\n",
9458 /* Don't recompute the checksum; with no ack packets we
9459 don't have any way to indicate a packet retransmission
9464 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
9465 if (csum == pktcsum)
9470 std::string str = escape_buffer (buf, bc);
9472 fprintf_unfiltered (gdb_stdlog,
9473 "Bad checksum, sentsum=0x%x, "
9474 "csum=0x%x, buf=%s\n",
9475 pktcsum, csum, str.c_str ());
9477 /* Number of characters in buffer ignoring trailing
9481 case '*': /* Run length encoding. */
9486 c = readchar (remote_timeout);
9488 repeat = c - ' ' + 3; /* Compute repeat count. */
9490 /* The character before ``*'' is repeated. */
9492 if (repeat > 0 && repeat <= 255 && bc > 0)
9494 if (bc + repeat - 1 >= *sizeof_buf - 1)
9496 /* Make some more room in the buffer. */
9497 *sizeof_buf += repeat;
9498 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
9502 memset (&buf[bc], buf[bc - 1], repeat);
9508 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
9512 if (bc >= *sizeof_buf - 1)
9514 /* Make some more room in the buffer. */
9516 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
9527 /* Read a packet from the remote machine, with error checking, and
9528 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
9529 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
9530 rather than timing out; this is used (in synchronous mode) to wait
9531 for a target that is is executing user code to stop. */
9532 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
9533 don't have to change all the calls to getpkt to deal with the
9534 return value, because at the moment I don't know what the right
9535 thing to do it for those. */
9538 remote_target::getpkt (char **buf, long *sizeof_buf, int forever)
9540 getpkt_sane (buf, sizeof_buf, forever);
9544 /* Read a packet from the remote machine, with error checking, and
9545 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
9546 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
9547 rather than timing out; this is used (in synchronous mode) to wait
9548 for a target that is is executing user code to stop. If FOREVER ==
9549 0, this function is allowed to time out gracefully and return an
9550 indication of this to the caller. Otherwise return the number of
9551 bytes read. If EXPECTING_NOTIF, consider receiving a notification
9552 enough reason to return to the caller. *IS_NOTIF is an output
9553 boolean that indicates whether *BUF holds a notification or not
9554 (a regular packet). */
9557 remote_target::getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf,
9558 int forever, int expecting_notif,
9561 struct remote_state *rs = get_remote_state ();
9567 /* We're reading a new response. Make sure we don't look at a
9568 previously cached response. */
9569 rs->cached_wait_status = 0;
9571 strcpy (*buf, "timeout");
9574 timeout = watchdog > 0 ? watchdog : -1;
9575 else if (expecting_notif)
9576 timeout = 0; /* There should already be a char in the buffer. If
9579 timeout = remote_timeout;
9583 /* Process any number of notifications, and then return when
9587 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
9589 for (tries = 1; tries <= MAX_TRIES; tries++)
9591 /* This can loop forever if the remote side sends us
9592 characters continuously, but if it pauses, we'll get
9593 SERIAL_TIMEOUT from readchar because of timeout. Then
9594 we'll count that as a retry.
9596 Note that even when forever is set, we will only wait
9597 forever prior to the start of a packet. After that, we
9598 expect characters to arrive at a brisk pace. They should
9599 show up within remote_timeout intervals. */
9601 c = readchar (timeout);
9602 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
9604 if (c == SERIAL_TIMEOUT)
9606 if (expecting_notif)
9607 return -1; /* Don't complain, it's normal to not get
9608 anything in this case. */
9610 if (forever) /* Watchdog went off? Kill the target. */
9612 remote_unpush_target ();
9613 throw_error (TARGET_CLOSE_ERROR,
9614 _("Watchdog timeout has expired. "
9615 "Target detached."));
9618 fputs_filtered ("Timed out.\n", gdb_stdlog);
9622 /* We've found the start of a packet or notification.
9623 Now collect the data. */
9624 val = read_frame (buf, sizeof_buf);
9629 remote_serial_write ("-", 1);
9632 if (tries > MAX_TRIES)
9634 /* We have tried hard enough, and just can't receive the
9635 packet/notification. Give up. */
9636 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
9638 /* Skip the ack char if we're in no-ack mode. */
9639 if (!rs->noack_mode)
9640 remote_serial_write ("+", 1);
9644 /* If we got an ordinary packet, return that to our caller. */
9650 = escape_buffer (*buf,
9651 std::min (val, REMOTE_DEBUG_MAX_CHAR));
9653 fprintf_unfiltered (gdb_stdlog, "Packet received: %s",
9656 if (val > REMOTE_DEBUG_MAX_CHAR)
9657 fprintf_unfiltered (gdb_stdlog, "[%d bytes omitted]",
9658 val - REMOTE_DEBUG_MAX_CHAR);
9660 fprintf_unfiltered (gdb_stdlog, "\n");
9663 /* Skip the ack char if we're in no-ack mode. */
9664 if (!rs->noack_mode)
9665 remote_serial_write ("+", 1);
9666 if (is_notif != NULL)
9671 /* If we got a notification, handle it, and go back to looking
9675 gdb_assert (c == '%');
9679 std::string str = escape_buffer (*buf, val);
9681 fprintf_unfiltered (gdb_stdlog,
9682 " Notification received: %s\n",
9685 if (is_notif != NULL)
9688 handle_notification (rs->notif_state, *buf);
9690 /* Notifications require no acknowledgement. */
9692 if (expecting_notif)
9699 remote_target::getpkt_sane (char **buf, long *sizeof_buf, int forever)
9701 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
9705 remote_target::getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
9708 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
9712 /* Kill any new fork children of process PID that haven't been
9713 processed by follow_fork. */
9716 remote_target::kill_new_fork_children (int pid)
9718 remote_state *rs = get_remote_state ();
9719 struct thread_info *thread;
9720 struct notif_client *notif = ¬if_client_stop;
9722 /* Kill the fork child threads of any threads in process PID
9723 that are stopped at a fork event. */
9724 ALL_NON_EXITED_THREADS (thread)
9726 struct target_waitstatus *ws = &thread->pending_follow;
9728 if (is_pending_fork_parent (ws, pid, thread->ptid))
9730 int child_pid = ws->value.related_pid.pid ();
9733 res = remote_vkill (child_pid);
9735 error (_("Can't kill fork child process %d"), child_pid);
9739 /* Check for any pending fork events (not reported or processed yet)
9740 in process PID and kill those fork child threads as well. */
9741 remote_notif_get_pending_events (notif);
9742 for (auto &event : rs->stop_reply_queue)
9743 if (is_pending_fork_parent (&event->ws, pid, event->ptid))
9745 int child_pid = event->ws.value.related_pid.pid ();
9748 res = remote_vkill (child_pid);
9750 error (_("Can't kill fork child process %d"), child_pid);
9755 /* Target hook to kill the current inferior. */
9758 remote_target::kill ()
9761 int pid = inferior_ptid.pid ();
9762 struct remote_state *rs = get_remote_state ();
9764 if (packet_support (PACKET_vKill) != PACKET_DISABLE)
9766 /* If we're stopped while forking and we haven't followed yet,
9767 kill the child task. We need to do this before killing the
9768 parent task because if this is a vfork then the parent will
9770 kill_new_fork_children (pid);
9772 res = remote_vkill (pid);
9775 target_mourn_inferior (inferior_ptid);
9780 /* If we are in 'target remote' mode and we are killing the only
9781 inferior, then we will tell gdbserver to exit and unpush the
9783 if (res == -1 && !remote_multi_process_p (rs)
9784 && number_of_live_inferiors () == 1)
9788 /* We've killed the remote end, we get to mourn it. If we are
9789 not in extended mode, mourning the inferior also unpushes
9790 remote_ops from the target stack, which closes the remote
9792 target_mourn_inferior (inferior_ptid);
9797 error (_("Can't kill process"));
9800 /* Send a kill request to the target using the 'vKill' packet. */
9803 remote_target::remote_vkill (int pid)
9805 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
9808 remote_state *rs = get_remote_state ();
9810 /* Tell the remote target to detach. */
9811 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
9813 getpkt (&rs->buf, &rs->buf_size, 0);
9815 switch (packet_ok (rs->buf,
9816 &remote_protocol_packets[PACKET_vKill]))
9822 case PACKET_UNKNOWN:
9825 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
9829 /* Send a kill request to the target using the 'k' packet. */
9832 remote_target::remote_kill_k ()
9834 /* Catch errors so the user can quit from gdb even when we
9835 aren't on speaking terms with the remote system. */
9840 CATCH (ex, RETURN_MASK_ERROR)
9842 if (ex.error == TARGET_CLOSE_ERROR)
9844 /* If we got an (EOF) error that caused the target
9845 to go away, then we're done, that's what we wanted.
9846 "k" is susceptible to cause a premature EOF, given
9847 that the remote server isn't actually required to
9848 reply to "k", and it can happen that it doesn't
9849 even get to reply ACK to the "k". */
9853 /* Otherwise, something went wrong. We didn't actually kill
9854 the target. Just propagate the exception, and let the
9855 user or higher layers decide what to do. */
9856 throw_exception (ex);
9862 remote_target::mourn_inferior ()
9864 struct remote_state *rs = get_remote_state ();
9866 /* We're no longer interested in notification events of an inferior
9867 that exited or was killed/detached. */
9868 discard_pending_stop_replies (current_inferior ());
9870 /* In 'target remote' mode with one inferior, we close the connection. */
9871 if (!rs->extended && number_of_live_inferiors () <= 1)
9873 unpush_target (this);
9875 /* remote_close takes care of doing most of the clean up. */
9876 generic_mourn_inferior ();
9880 /* In case we got here due to an error, but we're going to stay
9882 rs->waiting_for_stop_reply = 0;
9884 /* If the current general thread belonged to the process we just
9885 detached from or has exited, the remote side current general
9886 thread becomes undefined. Considering a case like this:
9888 - We just got here due to a detach.
9889 - The process that we're detaching from happens to immediately
9890 report a global breakpoint being hit in non-stop mode, in the
9891 same thread we had selected before.
9892 - GDB attaches to this process again.
9893 - This event happens to be the next event we handle.
9895 GDB would consider that the current general thread didn't need to
9896 be set on the stub side (with Hg), since for all it knew,
9897 GENERAL_THREAD hadn't changed.
9899 Notice that although in all-stop mode, the remote server always
9900 sets the current thread to the thread reporting the stop event,
9901 that doesn't happen in non-stop mode; in non-stop, the stub *must
9902 not* change the current thread when reporting a breakpoint hit,
9903 due to the decoupling of event reporting and event handling.
9905 To keep things simple, we always invalidate our notion of the
9907 record_currthread (rs, minus_one_ptid);
9909 /* Call common code to mark the inferior as not running. */
9910 generic_mourn_inferior ();
9912 if (!have_inferiors ())
9914 if (!remote_multi_process_p (rs))
9916 /* Check whether the target is running now - some remote stubs
9917 automatically restart after kill. */
9919 getpkt (&rs->buf, &rs->buf_size, 0);
9921 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
9923 /* Assume that the target has been restarted. Set
9924 inferior_ptid so that bits of core GDB realizes
9925 there's something here, e.g., so that the user can
9926 say "kill" again. */
9927 inferior_ptid = magic_null_ptid;
9934 extended_remote_target::supports_disable_randomization ()
9936 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
9940 remote_target::extended_remote_disable_randomization (int val)
9942 struct remote_state *rs = get_remote_state ();
9945 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
9948 reply = remote_get_noisy_reply ();
9950 error (_("Target does not support QDisableRandomization."));
9951 if (strcmp (reply, "OK") != 0)
9952 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
9956 remote_target::extended_remote_run (const std::string &args)
9958 struct remote_state *rs = get_remote_state ();
9960 const char *remote_exec_file = get_remote_exec_file ();
9962 /* If the user has disabled vRun support, or we have detected that
9963 support is not available, do not try it. */
9964 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
9967 strcpy (rs->buf, "vRun;");
9968 len = strlen (rs->buf);
9970 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
9971 error (_("Remote file name too long for run packet"));
9972 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
9973 strlen (remote_exec_file));
9979 gdb_argv argv (args.c_str ());
9980 for (i = 0; argv[i] != NULL; i++)
9982 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
9983 error (_("Argument list too long for run packet"));
9984 rs->buf[len++] = ';';
9985 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
9990 rs->buf[len++] = '\0';
9993 getpkt (&rs->buf, &rs->buf_size, 0);
9995 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
9998 /* We have a wait response. All is well. */
10000 case PACKET_UNKNOWN:
10003 if (remote_exec_file[0] == '\0')
10004 error (_("Running the default executable on the remote target failed; "
10005 "try \"set remote exec-file\"?"));
10007 error (_("Running \"%s\" on the remote target failed"),
10010 gdb_assert_not_reached (_("bad switch"));
10014 /* Helper function to send set/unset environment packets. ACTION is
10015 either "set" or "unset". PACKET is either "QEnvironmentHexEncoded"
10016 or "QEnvironmentUnsetVariable". VALUE is the variable to be
10020 remote_target::send_environment_packet (const char *action,
10021 const char *packet,
10024 remote_state *rs = get_remote_state ();
10026 /* Convert the environment variable to an hex string, which
10027 is the best format to be transmitted over the wire. */
10028 std::string encoded_value = bin2hex ((const gdb_byte *) value,
10031 xsnprintf (rs->buf, get_remote_packet_size (),
10032 "%s:%s", packet, encoded_value.c_str ());
10035 getpkt (&rs->buf, &rs->buf_size, 0);
10036 if (strcmp (rs->buf, "OK") != 0)
10037 warning (_("Unable to %s environment variable '%s' on remote."),
10041 /* Helper function to handle the QEnvironment* packets. */
10044 remote_target::extended_remote_environment_support ()
10046 remote_state *rs = get_remote_state ();
10048 if (packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
10050 putpkt ("QEnvironmentReset");
10051 getpkt (&rs->buf, &rs->buf_size, 0);
10052 if (strcmp (rs->buf, "OK") != 0)
10053 warning (_("Unable to reset environment on remote."));
10056 gdb_environ *e = ¤t_inferior ()->environment;
10058 if (packet_support (PACKET_QEnvironmentHexEncoded) != PACKET_DISABLE)
10059 for (const std::string &el : e->user_set_env ())
10060 send_environment_packet ("set", "QEnvironmentHexEncoded",
10063 if (packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
10064 for (const std::string &el : e->user_unset_env ())
10065 send_environment_packet ("unset", "QEnvironmentUnset", el.c_str ());
10068 /* Helper function to set the current working directory for the
10069 inferior in the remote target. */
10072 remote_target::extended_remote_set_inferior_cwd ()
10074 if (packet_support (PACKET_QSetWorkingDir) != PACKET_DISABLE)
10076 const char *inferior_cwd = get_inferior_cwd ();
10077 remote_state *rs = get_remote_state ();
10079 if (inferior_cwd != NULL)
10081 std::string hexpath = bin2hex ((const gdb_byte *) inferior_cwd,
10082 strlen (inferior_cwd));
10084 xsnprintf (rs->buf, get_remote_packet_size (),
10085 "QSetWorkingDir:%s", hexpath.c_str ());
10089 /* An empty inferior_cwd means that the user wants us to
10090 reset the remote server's inferior's cwd. */
10091 xsnprintf (rs->buf, get_remote_packet_size (),
10092 "QSetWorkingDir:");
10096 getpkt (&rs->buf, &rs->buf_size, 0);
10097 if (packet_ok (rs->buf,
10098 &remote_protocol_packets[PACKET_QSetWorkingDir])
10101 Remote replied unexpectedly while setting the inferior's working\n\
10108 /* In the extended protocol we want to be able to do things like
10109 "run" and have them basically work as expected. So we need
10110 a special create_inferior function. We support changing the
10111 executable file and the command line arguments, but not the
10115 extended_remote_target::create_inferior (const char *exec_file,
10116 const std::string &args,
10117 char **env, int from_tty)
10121 struct remote_state *rs = get_remote_state ();
10122 const char *remote_exec_file = get_remote_exec_file ();
10124 /* If running asynchronously, register the target file descriptor
10125 with the event loop. */
10126 if (target_can_async_p ())
10129 /* Disable address space randomization if requested (and supported). */
10130 if (supports_disable_randomization ())
10131 extended_remote_disable_randomization (disable_randomization);
10133 /* If startup-with-shell is on, we inform gdbserver to start the
10134 remote inferior using a shell. */
10135 if (packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
10137 xsnprintf (rs->buf, get_remote_packet_size (),
10138 "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
10140 getpkt (&rs->buf, &rs->buf_size, 0);
10141 if (strcmp (rs->buf, "OK") != 0)
10143 Remote replied unexpectedly while setting startup-with-shell: %s"),
10147 extended_remote_environment_support ();
10149 extended_remote_set_inferior_cwd ();
10151 /* Now restart the remote server. */
10152 run_worked = extended_remote_run (args) != -1;
10155 /* vRun was not supported. Fail if we need it to do what the
10157 if (remote_exec_file[0])
10158 error (_("Remote target does not support \"set remote exec-file\""));
10159 if (!args.empty ())
10160 error (_("Remote target does not support \"set args\" or run ARGS"));
10162 /* Fall back to "R". */
10163 extended_remote_restart ();
10166 if (!have_inferiors ())
10168 /* Clean up from the last time we ran, before we mark the target
10169 running again. This will mark breakpoints uninserted, and
10170 get_offsets may insert breakpoints. */
10171 init_thread_list ();
10172 init_wait_for_inferior ();
10175 /* vRun's success return is a stop reply. */
10176 stop_reply = run_worked ? rs->buf : NULL;
10177 add_current_inferior_and_thread (stop_reply);
10179 /* Get updated offsets, if the stub uses qOffsets. */
10184 /* Given a location's target info BP_TGT and the packet buffer BUF, output
10185 the list of conditions (in agent expression bytecode format), if any, the
10186 target needs to evaluate. The output is placed into the packet buffer
10187 started from BUF and ended at BUF_END. */
10190 remote_add_target_side_condition (struct gdbarch *gdbarch,
10191 struct bp_target_info *bp_tgt, char *buf,
10194 if (bp_tgt->conditions.empty ())
10197 buf += strlen (buf);
10198 xsnprintf (buf, buf_end - buf, "%s", ";");
10201 /* Send conditions to the target. */
10202 for (agent_expr *aexpr : bp_tgt->conditions)
10204 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
10205 buf += strlen (buf);
10206 for (int i = 0; i < aexpr->len; ++i)
10207 buf = pack_hex_byte (buf, aexpr->buf[i]);
10214 remote_add_target_side_commands (struct gdbarch *gdbarch,
10215 struct bp_target_info *bp_tgt, char *buf)
10217 if (bp_tgt->tcommands.empty ())
10220 buf += strlen (buf);
10222 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
10223 buf += strlen (buf);
10225 /* Concatenate all the agent expressions that are commands into the
10227 for (agent_expr *aexpr : bp_tgt->tcommands)
10229 sprintf (buf, "X%x,", aexpr->len);
10230 buf += strlen (buf);
10231 for (int i = 0; i < aexpr->len; ++i)
10232 buf = pack_hex_byte (buf, aexpr->buf[i]);
10237 /* Insert a breakpoint. On targets that have software breakpoint
10238 support, we ask the remote target to do the work; on targets
10239 which don't, we insert a traditional memory breakpoint. */
10242 remote_target::insert_breakpoint (struct gdbarch *gdbarch,
10243 struct bp_target_info *bp_tgt)
10245 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
10246 If it succeeds, then set the support to PACKET_ENABLE. If it
10247 fails, and the user has explicitly requested the Z support then
10248 report an error, otherwise, mark it disabled and go on. */
10250 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
10252 CORE_ADDR addr = bp_tgt->reqstd_address;
10253 struct remote_state *rs;
10256 /* Make sure the remote is pointing at the right process, if
10258 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10259 set_general_process ();
10261 rs = get_remote_state ();
10263 endbuf = rs->buf + get_remote_packet_size ();
10268 addr = (ULONGEST) remote_address_masked (addr);
10269 p += hexnumstr (p, addr);
10270 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10272 if (supports_evaluation_of_breakpoint_conditions ())
10273 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10275 if (can_run_breakpoint_commands ())
10276 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10279 getpkt (&rs->buf, &rs->buf_size, 0);
10281 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
10287 case PACKET_UNKNOWN:
10292 /* If this breakpoint has target-side commands but this stub doesn't
10293 support Z0 packets, throw error. */
10294 if (!bp_tgt->tcommands.empty ())
10295 throw_error (NOT_SUPPORTED_ERROR, _("\
10296 Target doesn't support breakpoints that have target side commands."));
10298 return memory_insert_breakpoint (this, gdbarch, bp_tgt);
10302 remote_target::remove_breakpoint (struct gdbarch *gdbarch,
10303 struct bp_target_info *bp_tgt,
10304 enum remove_bp_reason reason)
10306 CORE_ADDR addr = bp_tgt->placed_address;
10307 struct remote_state *rs = get_remote_state ();
10309 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
10312 char *endbuf = rs->buf + get_remote_packet_size ();
10314 /* Make sure the remote is pointing at the right process, if
10316 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10317 set_general_process ();
10323 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
10324 p += hexnumstr (p, addr);
10325 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10328 getpkt (&rs->buf, &rs->buf_size, 0);
10330 return (rs->buf[0] == 'E');
10333 return memory_remove_breakpoint (this, gdbarch, bp_tgt, reason);
10336 static enum Z_packet_type
10337 watchpoint_to_Z_packet (int type)
10342 return Z_PACKET_WRITE_WP;
10345 return Z_PACKET_READ_WP;
10348 return Z_PACKET_ACCESS_WP;
10351 internal_error (__FILE__, __LINE__,
10352 _("hw_bp_to_z: bad watchpoint type %d"), type);
10357 remote_target::insert_watchpoint (CORE_ADDR addr, int len,
10358 enum target_hw_bp_type type, struct expression *cond)
10360 struct remote_state *rs = get_remote_state ();
10361 char *endbuf = rs->buf + get_remote_packet_size ();
10363 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10365 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
10368 /* Make sure the remote is pointing at the right process, if
10370 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10371 set_general_process ();
10373 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
10374 p = strchr (rs->buf, '\0');
10375 addr = remote_address_masked (addr);
10376 p += hexnumstr (p, (ULONGEST) addr);
10377 xsnprintf (p, endbuf - p, ",%x", len);
10380 getpkt (&rs->buf, &rs->buf_size, 0);
10382 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
10386 case PACKET_UNKNOWN:
10391 internal_error (__FILE__, __LINE__,
10392 _("remote_insert_watchpoint: reached end of function"));
10396 remote_target::watchpoint_addr_within_range (CORE_ADDR addr,
10397 CORE_ADDR start, int length)
10399 CORE_ADDR diff = remote_address_masked (addr - start);
10401 return diff < length;
10406 remote_target::remove_watchpoint (CORE_ADDR addr, int len,
10407 enum target_hw_bp_type type, struct expression *cond)
10409 struct remote_state *rs = get_remote_state ();
10410 char *endbuf = rs->buf + get_remote_packet_size ();
10412 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10414 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
10417 /* Make sure the remote is pointing at the right process, if
10419 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10420 set_general_process ();
10422 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
10423 p = strchr (rs->buf, '\0');
10424 addr = remote_address_masked (addr);
10425 p += hexnumstr (p, (ULONGEST) addr);
10426 xsnprintf (p, endbuf - p, ",%x", len);
10428 getpkt (&rs->buf, &rs->buf_size, 0);
10430 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
10433 case PACKET_UNKNOWN:
10438 internal_error (__FILE__, __LINE__,
10439 _("remote_remove_watchpoint: reached end of function"));
10443 int remote_hw_watchpoint_limit = -1;
10444 int remote_hw_watchpoint_length_limit = -1;
10445 int remote_hw_breakpoint_limit = -1;
10448 remote_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
10450 if (remote_hw_watchpoint_length_limit == 0)
10452 else if (remote_hw_watchpoint_length_limit < 0)
10454 else if (len <= remote_hw_watchpoint_length_limit)
10461 remote_target::can_use_hw_breakpoint (enum bptype type, int cnt, int ot)
10463 if (type == bp_hardware_breakpoint)
10465 if (remote_hw_breakpoint_limit == 0)
10467 else if (remote_hw_breakpoint_limit < 0)
10469 else if (cnt <= remote_hw_breakpoint_limit)
10474 if (remote_hw_watchpoint_limit == 0)
10476 else if (remote_hw_watchpoint_limit < 0)
10480 else if (cnt <= remote_hw_watchpoint_limit)
10486 /* The to_stopped_by_sw_breakpoint method of target remote. */
10489 remote_target::stopped_by_sw_breakpoint ()
10491 struct thread_info *thread = inferior_thread ();
10493 return (thread->priv != NULL
10494 && (get_remote_thread_info (thread)->stop_reason
10495 == TARGET_STOPPED_BY_SW_BREAKPOINT));
10498 /* The to_supports_stopped_by_sw_breakpoint method of target
10502 remote_target::supports_stopped_by_sw_breakpoint ()
10504 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
10507 /* The to_stopped_by_hw_breakpoint method of target remote. */
10510 remote_target::stopped_by_hw_breakpoint ()
10512 struct thread_info *thread = inferior_thread ();
10514 return (thread->priv != NULL
10515 && (get_remote_thread_info (thread)->stop_reason
10516 == TARGET_STOPPED_BY_HW_BREAKPOINT));
10519 /* The to_supports_stopped_by_hw_breakpoint method of target
10523 remote_target::supports_stopped_by_hw_breakpoint ()
10525 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
10529 remote_target::stopped_by_watchpoint ()
10531 struct thread_info *thread = inferior_thread ();
10533 return (thread->priv != NULL
10534 && (get_remote_thread_info (thread)->stop_reason
10535 == TARGET_STOPPED_BY_WATCHPOINT));
10539 remote_target::stopped_data_address (CORE_ADDR *addr_p)
10541 struct thread_info *thread = inferior_thread ();
10543 if (thread->priv != NULL
10544 && (get_remote_thread_info (thread)->stop_reason
10545 == TARGET_STOPPED_BY_WATCHPOINT))
10547 *addr_p = get_remote_thread_info (thread)->watch_data_address;
10556 remote_target::insert_hw_breakpoint (struct gdbarch *gdbarch,
10557 struct bp_target_info *bp_tgt)
10559 CORE_ADDR addr = bp_tgt->reqstd_address;
10560 struct remote_state *rs;
10564 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10567 /* Make sure the remote is pointing at the right process, if
10569 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10570 set_general_process ();
10572 rs = get_remote_state ();
10574 endbuf = rs->buf + get_remote_packet_size ();
10580 addr = remote_address_masked (addr);
10581 p += hexnumstr (p, (ULONGEST) addr);
10582 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
10584 if (supports_evaluation_of_breakpoint_conditions ())
10585 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10587 if (can_run_breakpoint_commands ())
10588 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10591 getpkt (&rs->buf, &rs->buf_size, 0);
10593 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10596 if (rs->buf[1] == '.')
10598 message = strchr (rs->buf + 2, '.');
10600 error (_("Remote failure reply: %s"), message + 1);
10603 case PACKET_UNKNOWN:
10608 internal_error (__FILE__, __LINE__,
10609 _("remote_insert_hw_breakpoint: reached end of function"));
10614 remote_target::remove_hw_breakpoint (struct gdbarch *gdbarch,
10615 struct bp_target_info *bp_tgt)
10618 struct remote_state *rs = get_remote_state ();
10620 char *endbuf = rs->buf + get_remote_packet_size ();
10622 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10625 /* Make sure the remote is pointing at the right process, if
10627 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10628 set_general_process ();
10634 addr = remote_address_masked (bp_tgt->placed_address);
10635 p += hexnumstr (p, (ULONGEST) addr);
10636 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
10639 getpkt (&rs->buf, &rs->buf_size, 0);
10641 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10644 case PACKET_UNKNOWN:
10649 internal_error (__FILE__, __LINE__,
10650 _("remote_remove_hw_breakpoint: reached end of function"));
10653 /* Verify memory using the "qCRC:" request. */
10656 remote_target::verify_memory (const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
10658 struct remote_state *rs = get_remote_state ();
10659 unsigned long host_crc, target_crc;
10662 /* It doesn't make sense to use qCRC if the remote target is
10663 connected but not running. */
10664 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
10666 enum packet_result result;
10668 /* Make sure the remote is pointing at the right process. */
10669 set_general_process ();
10671 /* FIXME: assumes lma can fit into long. */
10672 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
10673 (long) lma, (long) size);
10676 /* Be clever; compute the host_crc before waiting for target
10678 host_crc = xcrc32 (data, size, 0xffffffff);
10680 getpkt (&rs->buf, &rs->buf_size, 0);
10682 result = packet_ok (rs->buf,
10683 &remote_protocol_packets[PACKET_qCRC]);
10684 if (result == PACKET_ERROR)
10686 else if (result == PACKET_OK)
10688 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
10689 target_crc = target_crc * 16 + fromhex (*tmp);
10691 return (host_crc == target_crc);
10695 return simple_verify_memory (this, data, lma, size);
10698 /* compare-sections command
10700 With no arguments, compares each loadable section in the exec bfd
10701 with the same memory range on the target, and reports mismatches.
10702 Useful for verifying the image on the target against the exec file. */
10705 compare_sections_command (const char *args, int from_tty)
10708 const char *sectname;
10709 bfd_size_type size;
10712 int mismatched = 0;
10717 error (_("command cannot be used without an exec file"));
10719 if (args != NULL && strcmp (args, "-r") == 0)
10725 for (s = exec_bfd->sections; s; s = s->next)
10727 if (!(s->flags & SEC_LOAD))
10728 continue; /* Skip non-loadable section. */
10730 if (read_only && (s->flags & SEC_READONLY) == 0)
10731 continue; /* Skip writeable sections */
10733 size = bfd_get_section_size (s);
10735 continue; /* Skip zero-length section. */
10737 sectname = bfd_get_section_name (exec_bfd, s);
10738 if (args && strcmp (args, sectname) != 0)
10739 continue; /* Not the section selected by user. */
10741 matched = 1; /* Do this section. */
10744 gdb::byte_vector sectdata (size);
10745 bfd_get_section_contents (exec_bfd, s, sectdata.data (), 0, size);
10747 res = target_verify_memory (sectdata.data (), lma, size);
10750 error (_("target memory fault, section %s, range %s -- %s"), sectname,
10751 paddress (target_gdbarch (), lma),
10752 paddress (target_gdbarch (), lma + size));
10754 printf_filtered ("Section %s, range %s -- %s: ", sectname,
10755 paddress (target_gdbarch (), lma),
10756 paddress (target_gdbarch (), lma + size));
10758 printf_filtered ("matched.\n");
10761 printf_filtered ("MIS-MATCHED!\n");
10765 if (mismatched > 0)
10766 warning (_("One or more sections of the target image does not match\n\
10767 the loaded file\n"));
10768 if (args && !matched)
10769 printf_filtered (_("No loaded section named '%s'.\n"), args);
10772 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
10773 into remote target. The number of bytes written to the remote
10774 target is returned, or -1 for error. */
10777 remote_target::remote_write_qxfer (const char *object_name,
10778 const char *annex, const gdb_byte *writebuf,
10779 ULONGEST offset, LONGEST len,
10780 ULONGEST *xfered_len,
10781 struct packet_config *packet)
10785 struct remote_state *rs = get_remote_state ();
10786 int max_size = get_memory_write_packet_size ();
10788 if (packet_config_support (packet) == PACKET_DISABLE)
10789 return TARGET_XFER_E_IO;
10791 /* Insert header. */
10792 i = snprintf (rs->buf, max_size,
10793 "qXfer:%s:write:%s:%s:",
10794 object_name, annex ? annex : "",
10795 phex_nz (offset, sizeof offset));
10796 max_size -= (i + 1);
10798 /* Escape as much data as fits into rs->buf. */
10799 buf_len = remote_escape_output
10800 (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
10802 if (putpkt_binary (rs->buf, i + buf_len) < 0
10803 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10804 || packet_ok (rs->buf, packet) != PACKET_OK)
10805 return TARGET_XFER_E_IO;
10807 unpack_varlen_hex (rs->buf, &n);
10810 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
10813 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
10814 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
10815 number of bytes read is returned, or 0 for EOF, or -1 for error.
10816 The number of bytes read may be less than LEN without indicating an
10817 EOF. PACKET is checked and updated to indicate whether the remote
10818 target supports this object. */
10821 remote_target::remote_read_qxfer (const char *object_name,
10823 gdb_byte *readbuf, ULONGEST offset,
10825 ULONGEST *xfered_len,
10826 struct packet_config *packet)
10828 struct remote_state *rs = get_remote_state ();
10829 LONGEST i, n, packet_len;
10831 if (packet_config_support (packet) == PACKET_DISABLE)
10832 return TARGET_XFER_E_IO;
10834 /* Check whether we've cached an end-of-object packet that matches
10836 if (rs->finished_object)
10838 if (strcmp (object_name, rs->finished_object) == 0
10839 && strcmp (annex ? annex : "", rs->finished_annex) == 0
10840 && offset == rs->finished_offset)
10841 return TARGET_XFER_EOF;
10844 /* Otherwise, we're now reading something different. Discard
10846 xfree (rs->finished_object);
10847 xfree (rs->finished_annex);
10848 rs->finished_object = NULL;
10849 rs->finished_annex = NULL;
10852 /* Request only enough to fit in a single packet. The actual data
10853 may not, since we don't know how much of it will need to be escaped;
10854 the target is free to respond with slightly less data. We subtract
10855 five to account for the response type and the protocol frame. */
10856 n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
10857 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
10858 object_name, annex ? annex : "",
10859 phex_nz (offset, sizeof offset),
10860 phex_nz (n, sizeof n));
10861 i = putpkt (rs->buf);
10863 return TARGET_XFER_E_IO;
10866 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10867 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
10868 return TARGET_XFER_E_IO;
10870 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
10871 error (_("Unknown remote qXfer reply: %s"), rs->buf);
10873 /* 'm' means there is (or at least might be) more data after this
10874 batch. That does not make sense unless there's at least one byte
10875 of data in this reply. */
10876 if (rs->buf[0] == 'm' && packet_len == 1)
10877 error (_("Remote qXfer reply contained no data."));
10879 /* Got some data. */
10880 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
10881 packet_len - 1, readbuf, n);
10883 /* 'l' is an EOF marker, possibly including a final block of data,
10884 or possibly empty. If we have the final block of a non-empty
10885 object, record this fact to bypass a subsequent partial read. */
10886 if (rs->buf[0] == 'l' && offset + i > 0)
10888 rs->finished_object = xstrdup (object_name);
10889 rs->finished_annex = xstrdup (annex ? annex : "");
10890 rs->finished_offset = offset + i;
10894 return TARGET_XFER_EOF;
10898 return TARGET_XFER_OK;
10902 enum target_xfer_status
10903 remote_target::xfer_partial (enum target_object object,
10904 const char *annex, gdb_byte *readbuf,
10905 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
10906 ULONGEST *xfered_len)
10908 struct remote_state *rs;
10912 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
10914 set_remote_traceframe ();
10915 set_general_thread (inferior_ptid);
10917 rs = get_remote_state ();
10919 /* Handle memory using the standard memory routines. */
10920 if (object == TARGET_OBJECT_MEMORY)
10922 /* If the remote target is connected but not running, we should
10923 pass this request down to a lower stratum (e.g. the executable
10925 if (!target_has_execution)
10926 return TARGET_XFER_EOF;
10928 if (writebuf != NULL)
10929 return remote_write_bytes (offset, writebuf, len, unit_size,
10932 return remote_read_bytes (offset, readbuf, len, unit_size,
10936 /* Handle SPU memory using qxfer packets. */
10937 if (object == TARGET_OBJECT_SPU)
10940 return remote_read_qxfer ("spu", annex, readbuf, offset, len,
10941 xfered_len, &remote_protocol_packets
10942 [PACKET_qXfer_spu_read]);
10944 return remote_write_qxfer ("spu", annex, writebuf, offset, len,
10945 xfered_len, &remote_protocol_packets
10946 [PACKET_qXfer_spu_write]);
10949 /* Handle extra signal info using qxfer packets. */
10950 if (object == TARGET_OBJECT_SIGNAL_INFO)
10953 return remote_read_qxfer ("siginfo", annex, readbuf, offset, len,
10954 xfered_len, &remote_protocol_packets
10955 [PACKET_qXfer_siginfo_read]);
10957 return remote_write_qxfer ("siginfo", annex,
10958 writebuf, offset, len, xfered_len,
10959 &remote_protocol_packets
10960 [PACKET_qXfer_siginfo_write]);
10963 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
10966 return remote_read_qxfer ("statictrace", annex,
10967 readbuf, offset, len, xfered_len,
10968 &remote_protocol_packets
10969 [PACKET_qXfer_statictrace_read]);
10971 return TARGET_XFER_E_IO;
10974 /* Only handle flash writes. */
10975 if (writebuf != NULL)
10979 case TARGET_OBJECT_FLASH:
10980 return remote_flash_write (offset, len, xfered_len,
10984 return TARGET_XFER_E_IO;
10988 /* Map pre-existing objects onto letters. DO NOT do this for new
10989 objects!!! Instead specify new query packets. */
10992 case TARGET_OBJECT_AVR:
10996 case TARGET_OBJECT_AUXV:
10997 gdb_assert (annex == NULL);
10998 return remote_read_qxfer ("auxv", annex, readbuf, offset, len,
11000 &remote_protocol_packets[PACKET_qXfer_auxv]);
11002 case TARGET_OBJECT_AVAILABLE_FEATURES:
11003 return remote_read_qxfer
11004 ("features", annex, readbuf, offset, len, xfered_len,
11005 &remote_protocol_packets[PACKET_qXfer_features]);
11007 case TARGET_OBJECT_LIBRARIES:
11008 return remote_read_qxfer
11009 ("libraries", annex, readbuf, offset, len, xfered_len,
11010 &remote_protocol_packets[PACKET_qXfer_libraries]);
11012 case TARGET_OBJECT_LIBRARIES_SVR4:
11013 return remote_read_qxfer
11014 ("libraries-svr4", annex, readbuf, offset, len, xfered_len,
11015 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
11017 case TARGET_OBJECT_MEMORY_MAP:
11018 gdb_assert (annex == NULL);
11019 return remote_read_qxfer ("memory-map", annex, readbuf, offset, len,
11021 &remote_protocol_packets[PACKET_qXfer_memory_map]);
11023 case TARGET_OBJECT_OSDATA:
11024 /* Should only get here if we're connected. */
11025 gdb_assert (rs->remote_desc);
11026 return remote_read_qxfer
11027 ("osdata", annex, readbuf, offset, len, xfered_len,
11028 &remote_protocol_packets[PACKET_qXfer_osdata]);
11030 case TARGET_OBJECT_THREADS:
11031 gdb_assert (annex == NULL);
11032 return remote_read_qxfer ("threads", annex, readbuf, offset, len,
11034 &remote_protocol_packets[PACKET_qXfer_threads]);
11036 case TARGET_OBJECT_TRACEFRAME_INFO:
11037 gdb_assert (annex == NULL);
11038 return remote_read_qxfer
11039 ("traceframe-info", annex, readbuf, offset, len, xfered_len,
11040 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
11042 case TARGET_OBJECT_FDPIC:
11043 return remote_read_qxfer ("fdpic", annex, readbuf, offset, len,
11045 &remote_protocol_packets[PACKET_qXfer_fdpic]);
11047 case TARGET_OBJECT_OPENVMS_UIB:
11048 return remote_read_qxfer ("uib", annex, readbuf, offset, len,
11050 &remote_protocol_packets[PACKET_qXfer_uib]);
11052 case TARGET_OBJECT_BTRACE:
11053 return remote_read_qxfer ("btrace", annex, readbuf, offset, len,
11055 &remote_protocol_packets[PACKET_qXfer_btrace]);
11057 case TARGET_OBJECT_BTRACE_CONF:
11058 return remote_read_qxfer ("btrace-conf", annex, readbuf, offset,
11060 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
11062 case TARGET_OBJECT_EXEC_FILE:
11063 return remote_read_qxfer ("exec-file", annex, readbuf, offset,
11065 &remote_protocol_packets[PACKET_qXfer_exec_file]);
11068 return TARGET_XFER_E_IO;
11071 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
11072 large enough let the caller deal with it. */
11073 if (len < get_remote_packet_size ())
11074 return TARGET_XFER_E_IO;
11075 len = get_remote_packet_size ();
11077 /* Except for querying the minimum buffer size, target must be open. */
11078 if (!rs->remote_desc)
11079 error (_("remote query is only available after target open"));
11081 gdb_assert (annex != NULL);
11082 gdb_assert (readbuf != NULL);
11086 *p2++ = query_type;
11088 /* We used one buffer char for the remote protocol q command and
11089 another for the query type. As the remote protocol encapsulation
11090 uses 4 chars plus one extra in case we are debugging
11091 (remote_debug), we have PBUFZIZ - 7 left to pack the query
11094 while (annex[i] && (i < (get_remote_packet_size () - 8)))
11096 /* Bad caller may have sent forbidden characters. */
11097 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
11102 gdb_assert (annex[i] == '\0');
11104 i = putpkt (rs->buf);
11106 return TARGET_XFER_E_IO;
11108 getpkt (&rs->buf, &rs->buf_size, 0);
11109 strcpy ((char *) readbuf, rs->buf);
11111 *xfered_len = strlen ((char *) readbuf);
11112 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
11115 /* Implementation of to_get_memory_xfer_limit. */
11118 remote_target::get_memory_xfer_limit ()
11120 return get_memory_write_packet_size ();
11124 remote_target::search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
11125 const gdb_byte *pattern, ULONGEST pattern_len,
11126 CORE_ADDR *found_addrp)
11128 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
11129 struct remote_state *rs = get_remote_state ();
11130 int max_size = get_memory_write_packet_size ();
11131 struct packet_config *packet =
11132 &remote_protocol_packets[PACKET_qSearch_memory];
11133 /* Number of packet bytes used to encode the pattern;
11134 this could be more than PATTERN_LEN due to escape characters. */
11135 int escaped_pattern_len;
11136 /* Amount of pattern that was encodable in the packet. */
11137 int used_pattern_len;
11140 ULONGEST found_addr;
11142 /* Don't go to the target if we don't have to. This is done before
11143 checking packet_config_support to avoid the possibility that a
11144 success for this edge case means the facility works in
11146 if (pattern_len > search_space_len)
11148 if (pattern_len == 0)
11150 *found_addrp = start_addr;
11154 /* If we already know the packet isn't supported, fall back to the simple
11155 way of searching memory. */
11157 if (packet_config_support (packet) == PACKET_DISABLE)
11159 /* Target doesn't provided special support, fall back and use the
11160 standard support (copy memory and do the search here). */
11161 return simple_search_memory (this, start_addr, search_space_len,
11162 pattern, pattern_len, found_addrp);
11165 /* Make sure the remote is pointing at the right process. */
11166 set_general_process ();
11168 /* Insert header. */
11169 i = snprintf (rs->buf, max_size,
11170 "qSearch:memory:%s;%s;",
11171 phex_nz (start_addr, addr_size),
11172 phex_nz (search_space_len, sizeof (search_space_len)));
11173 max_size -= (i + 1);
11175 /* Escape as much data as fits into rs->buf. */
11176 escaped_pattern_len =
11177 remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
11178 &used_pattern_len, max_size);
11180 /* Bail if the pattern is too large. */
11181 if (used_pattern_len != pattern_len)
11182 error (_("Pattern is too large to transmit to remote target."));
11184 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
11185 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
11186 || packet_ok (rs->buf, packet) != PACKET_OK)
11188 /* The request may not have worked because the command is not
11189 supported. If so, fall back to the simple way. */
11190 if (packet_config_support (packet) == PACKET_DISABLE)
11192 return simple_search_memory (this, start_addr, search_space_len,
11193 pattern, pattern_len, found_addrp);
11198 if (rs->buf[0] == '0')
11200 else if (rs->buf[0] == '1')
11203 if (rs->buf[1] != ',')
11204 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
11205 unpack_varlen_hex (rs->buf + 2, &found_addr);
11206 *found_addrp = found_addr;
11209 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
11215 remote_target::rcmd (const char *command, struct ui_file *outbuf)
11217 struct remote_state *rs = get_remote_state ();
11220 if (!rs->remote_desc)
11221 error (_("remote rcmd is only available after target open"));
11223 /* Send a NULL command across as an empty command. */
11224 if (command == NULL)
11227 /* The query prefix. */
11228 strcpy (rs->buf, "qRcmd,");
11229 p = strchr (rs->buf, '\0');
11231 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
11232 > get_remote_packet_size ())
11233 error (_("\"monitor\" command ``%s'' is too long."), command);
11235 /* Encode the actual command. */
11236 bin2hex ((const gdb_byte *) command, p, strlen (command));
11238 if (putpkt (rs->buf) < 0)
11239 error (_("Communication problem with target."));
11241 /* get/display the response */
11246 /* XXX - see also remote_get_noisy_reply(). */
11247 QUIT; /* Allow user to bail out with ^C. */
11249 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
11251 /* Timeout. Continue to (try to) read responses.
11252 This is better than stopping with an error, assuming the stub
11253 is still executing the (long) monitor command.
11254 If needed, the user can interrupt gdb using C-c, obtaining
11255 an effect similar to stop on timeout. */
11259 if (buf[0] == '\0')
11260 error (_("Target does not support this command."));
11261 if (buf[0] == 'O' && buf[1] != 'K')
11263 remote_console_output (buf + 1); /* 'O' message from stub. */
11266 if (strcmp (buf, "OK") == 0)
11268 if (strlen (buf) == 3 && buf[0] == 'E'
11269 && isdigit (buf[1]) && isdigit (buf[2]))
11271 error (_("Protocol error with Rcmd"));
11273 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
11275 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
11277 fputc_unfiltered (c, outbuf);
11283 std::vector<mem_region>
11284 remote_target::memory_map ()
11286 std::vector<mem_region> result;
11287 gdb::optional<gdb::char_vector> text
11288 = target_read_stralloc (current_top_target (), TARGET_OBJECT_MEMORY_MAP, NULL);
11291 result = parse_memory_map (text->data ());
11297 packet_command (const char *args, int from_tty)
11299 remote_target *remote = get_current_remote_target ();
11301 if (remote == nullptr)
11302 error (_("command can only be used with remote target"));
11304 remote->packet_command (args, from_tty);
11308 remote_target::packet_command (const char *args, int from_tty)
11311 error (_("remote-packet command requires packet text as argument"));
11313 puts_filtered ("sending: ");
11314 print_packet (args);
11315 puts_filtered ("\n");
11318 remote_state *rs = get_remote_state ();
11320 getpkt (&rs->buf, &rs->buf_size, 0);
11321 puts_filtered ("received: ");
11322 print_packet (rs->buf);
11323 puts_filtered ("\n");
11327 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
11329 static void display_thread_info (struct gdb_ext_thread_info *info);
11331 static void threadset_test_cmd (char *cmd, int tty);
11333 static void threadalive_test (char *cmd, int tty);
11335 static void threadlist_test_cmd (char *cmd, int tty);
11337 int get_and_display_threadinfo (threadref *ref);
11339 static void threadinfo_test_cmd (char *cmd, int tty);
11341 static int thread_display_step (threadref *ref, void *context);
11343 static void threadlist_update_test_cmd (char *cmd, int tty);
11345 static void init_remote_threadtests (void);
11347 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
11350 threadset_test_cmd (const char *cmd, int tty)
11352 int sample_thread = SAMPLE_THREAD;
11354 printf_filtered (_("Remote threadset test\n"));
11355 set_general_thread (sample_thread);
11360 threadalive_test (const char *cmd, int tty)
11362 int sample_thread = SAMPLE_THREAD;
11363 int pid = inferior_ptid.pid ();
11364 ptid_t ptid = ptid_t (pid, sample_thread, 0);
11366 if (remote_thread_alive (ptid))
11367 printf_filtered ("PASS: Thread alive test\n");
11369 printf_filtered ("FAIL: Thread alive test\n");
11372 void output_threadid (char *title, threadref *ref);
11375 output_threadid (char *title, threadref *ref)
11379 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
11381 printf_filtered ("%s %s\n", title, (&hexid[0]));
11385 threadlist_test_cmd (const char *cmd, int tty)
11388 threadref nextthread;
11389 int done, result_count;
11390 threadref threadlist[3];
11392 printf_filtered ("Remote Threadlist test\n");
11393 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
11394 &result_count, &threadlist[0]))
11395 printf_filtered ("FAIL: threadlist test\n");
11398 threadref *scan = threadlist;
11399 threadref *limit = scan + result_count;
11401 while (scan < limit)
11402 output_threadid (" thread ", scan++);
11407 display_thread_info (struct gdb_ext_thread_info *info)
11409 output_threadid ("Threadid: ", &info->threadid);
11410 printf_filtered ("Name: %s\n ", info->shortname);
11411 printf_filtered ("State: %s\n", info->display);
11412 printf_filtered ("other: %s\n\n", info->more_display);
11416 get_and_display_threadinfo (threadref *ref)
11420 struct gdb_ext_thread_info threadinfo;
11422 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
11423 | TAG_MOREDISPLAY | TAG_DISPLAY;
11424 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
11425 display_thread_info (&threadinfo);
11430 threadinfo_test_cmd (const char *cmd, int tty)
11432 int athread = SAMPLE_THREAD;
11436 int_to_threadref (&thread, athread);
11437 printf_filtered ("Remote Threadinfo test\n");
11438 if (!get_and_display_threadinfo (&thread))
11439 printf_filtered ("FAIL cannot get thread info\n");
11443 thread_display_step (threadref *ref, void *context)
11445 /* output_threadid(" threadstep ",ref); *//* simple test */
11446 return get_and_display_threadinfo (ref);
11450 threadlist_update_test_cmd (const char *cmd, int tty)
11452 printf_filtered ("Remote Threadlist update test\n");
11453 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
11457 init_remote_threadtests (void)
11459 add_com ("tlist", class_obscure, threadlist_test_cmd,
11460 _("Fetch and print the remote list of "
11461 "thread identifiers, one pkt only"));
11462 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
11463 _("Fetch and display info about one thread"));
11464 add_com ("tset", class_obscure, threadset_test_cmd,
11465 _("Test setting to a different thread"));
11466 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
11467 _("Iterate through updating all remote thread info"));
11468 add_com ("talive", class_obscure, threadalive_test,
11469 _(" Remote thread alive test "));
11474 /* Convert a thread ID to a string. Returns the string in a static
11478 remote_target::pid_to_str (ptid_t ptid)
11480 static char buf[64];
11481 struct remote_state *rs = get_remote_state ();
11483 if (ptid == null_ptid)
11484 return normal_pid_to_str (ptid);
11485 else if (ptid.is_pid ())
11487 /* Printing an inferior target id. */
11489 /* When multi-process extensions are off, there's no way in the
11490 remote protocol to know the remote process id, if there's any
11491 at all. There's one exception --- when we're connected with
11492 target extended-remote, and we manually attached to a process
11493 with "attach PID". We don't record anywhere a flag that
11494 allows us to distinguish that case from the case of
11495 connecting with extended-remote and the stub already being
11496 attached to a process, and reporting yes to qAttached, hence
11497 no smart special casing here. */
11498 if (!remote_multi_process_p (rs))
11500 xsnprintf (buf, sizeof buf, "Remote target");
11504 return normal_pid_to_str (ptid);
11508 if (magic_null_ptid == ptid)
11509 xsnprintf (buf, sizeof buf, "Thread <main>");
11510 else if (remote_multi_process_p (rs))
11511 if (ptid.lwp () == 0)
11512 return normal_pid_to_str (ptid);
11514 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
11515 ptid.pid (), ptid.lwp ());
11517 xsnprintf (buf, sizeof buf, "Thread %ld",
11523 /* Get the address of the thread local variable in OBJFILE which is
11524 stored at OFFSET within the thread local storage for thread PTID. */
11527 remote_target::get_thread_local_address (ptid_t ptid, CORE_ADDR lm,
11530 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
11532 struct remote_state *rs = get_remote_state ();
11534 char *endp = rs->buf + get_remote_packet_size ();
11535 enum packet_result result;
11537 strcpy (p, "qGetTLSAddr:");
11539 p = write_ptid (p, endp, ptid);
11541 p += hexnumstr (p, offset);
11543 p += hexnumstr (p, lm);
11547 getpkt (&rs->buf, &rs->buf_size, 0);
11548 result = packet_ok (rs->buf,
11549 &remote_protocol_packets[PACKET_qGetTLSAddr]);
11550 if (result == PACKET_OK)
11554 unpack_varlen_hex (rs->buf, &addr);
11557 else if (result == PACKET_UNKNOWN)
11558 throw_error (TLS_GENERIC_ERROR,
11559 _("Remote target doesn't support qGetTLSAddr packet"));
11561 throw_error (TLS_GENERIC_ERROR,
11562 _("Remote target failed to process qGetTLSAddr request"));
11565 throw_error (TLS_GENERIC_ERROR,
11566 _("TLS not supported or disabled on this target"));
11571 /* Provide thread local base, i.e. Thread Information Block address.
11572 Returns 1 if ptid is found and thread_local_base is non zero. */
11575 remote_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
11577 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
11579 struct remote_state *rs = get_remote_state ();
11581 char *endp = rs->buf + get_remote_packet_size ();
11582 enum packet_result result;
11584 strcpy (p, "qGetTIBAddr:");
11586 p = write_ptid (p, endp, ptid);
11590 getpkt (&rs->buf, &rs->buf_size, 0);
11591 result = packet_ok (rs->buf,
11592 &remote_protocol_packets[PACKET_qGetTIBAddr]);
11593 if (result == PACKET_OK)
11596 unpack_varlen_hex (rs->buf, &val);
11598 *addr = (CORE_ADDR) val;
11601 else if (result == PACKET_UNKNOWN)
11602 error (_("Remote target doesn't support qGetTIBAddr packet"));
11604 error (_("Remote target failed to process qGetTIBAddr request"));
11607 error (_("qGetTIBAddr not supported or disabled on this target"));
11612 /* Support for inferring a target description based on the current
11613 architecture and the size of a 'g' packet. While the 'g' packet
11614 can have any size (since optional registers can be left off the
11615 end), some sizes are easily recognizable given knowledge of the
11616 approximate architecture. */
11618 struct remote_g_packet_guess
11621 const struct target_desc *tdesc;
11623 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
11624 DEF_VEC_O(remote_g_packet_guess_s);
11626 struct remote_g_packet_data
11628 VEC(remote_g_packet_guess_s) *guesses;
11631 static struct gdbarch_data *remote_g_packet_data_handle;
11634 remote_g_packet_data_init (struct obstack *obstack)
11636 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
11640 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
11641 const struct target_desc *tdesc)
11643 struct remote_g_packet_data *data
11644 = ((struct remote_g_packet_data *)
11645 gdbarch_data (gdbarch, remote_g_packet_data_handle));
11646 struct remote_g_packet_guess new_guess, *guess;
11649 gdb_assert (tdesc != NULL);
11652 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
11654 if (guess->bytes == bytes)
11655 internal_error (__FILE__, __LINE__,
11656 _("Duplicate g packet description added for size %d"),
11659 new_guess.bytes = bytes;
11660 new_guess.tdesc = tdesc;
11661 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
11664 /* Return 1 if remote_read_description would do anything on this target
11665 and architecture, 0 otherwise. */
11668 remote_read_description_p (struct target_ops *target)
11670 struct remote_g_packet_data *data
11671 = ((struct remote_g_packet_data *)
11672 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
11674 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
11680 const struct target_desc *
11681 remote_target::read_description ()
11683 struct remote_g_packet_data *data
11684 = ((struct remote_g_packet_data *)
11685 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
11687 /* Do not try this during initial connection, when we do not know
11688 whether there is a running but stopped thread. */
11689 if (!target_has_execution || inferior_ptid == null_ptid)
11690 return beneath ()->read_description ();
11692 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
11694 struct remote_g_packet_guess *guess;
11696 int bytes = send_g_packet ();
11699 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
11701 if (guess->bytes == bytes)
11702 return guess->tdesc;
11704 /* We discard the g packet. A minor optimization would be to
11705 hold on to it, and fill the register cache once we have selected
11706 an architecture, but it's too tricky to do safely. */
11709 return beneath ()->read_description ();
11712 /* Remote file transfer support. This is host-initiated I/O, not
11713 target-initiated; for target-initiated, see remote-fileio.c. */
11715 /* If *LEFT is at least the length of STRING, copy STRING to
11716 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11717 decrease *LEFT. Otherwise raise an error. */
11720 remote_buffer_add_string (char **buffer, int *left, const char *string)
11722 int len = strlen (string);
11725 error (_("Packet too long for target."));
11727 memcpy (*buffer, string, len);
11731 /* NUL-terminate the buffer as a convenience, if there is
11737 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
11738 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11739 decrease *LEFT. Otherwise raise an error. */
11742 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
11745 if (2 * len > *left)
11746 error (_("Packet too long for target."));
11748 bin2hex (bytes, *buffer, len);
11749 *buffer += 2 * len;
11752 /* NUL-terminate the buffer as a convenience, if there is
11758 /* If *LEFT is large enough, convert VALUE to hex and add it to
11759 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11760 decrease *LEFT. Otherwise raise an error. */
11763 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
11765 int len = hexnumlen (value);
11768 error (_("Packet too long for target."));
11770 hexnumstr (*buffer, value);
11774 /* NUL-terminate the buffer as a convenience, if there is
11780 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
11781 value, *REMOTE_ERRNO to the remote error number or zero if none
11782 was included, and *ATTACHMENT to point to the start of the annex
11783 if any. The length of the packet isn't needed here; there may
11784 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
11786 Return 0 if the packet could be parsed, -1 if it could not. If
11787 -1 is returned, the other variables may not be initialized. */
11790 remote_hostio_parse_result (char *buffer, int *retcode,
11791 int *remote_errno, char **attachment)
11796 *attachment = NULL;
11798 if (buffer[0] != 'F')
11802 *retcode = strtol (&buffer[1], &p, 16);
11803 if (errno != 0 || p == &buffer[1])
11806 /* Check for ",errno". */
11810 *remote_errno = strtol (p + 1, &p2, 16);
11811 if (errno != 0 || p + 1 == p2)
11816 /* Check for ";attachment". If there is no attachment, the
11817 packet should end here. */
11820 *attachment = p + 1;
11823 else if (*p == '\0')
11829 /* Send a prepared I/O packet to the target and read its response.
11830 The prepared packet is in the global RS->BUF before this function
11831 is called, and the answer is there when we return.
11833 COMMAND_BYTES is the length of the request to send, which may include
11834 binary data. WHICH_PACKET is the packet configuration to check
11835 before attempting a packet. If an error occurs, *REMOTE_ERRNO
11836 is set to the error number and -1 is returned. Otherwise the value
11837 returned by the function is returned.
11839 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
11840 attachment is expected; an error will be reported if there's a
11841 mismatch. If one is found, *ATTACHMENT will be set to point into
11842 the packet buffer and *ATTACHMENT_LEN will be set to the
11843 attachment's length. */
11846 remote_target::remote_hostio_send_command (int command_bytes, int which_packet,
11847 int *remote_errno, char **attachment,
11848 int *attachment_len)
11850 struct remote_state *rs = get_remote_state ();
11851 int ret, bytes_read;
11852 char *attachment_tmp;
11854 if (packet_support (which_packet) == PACKET_DISABLE)
11856 *remote_errno = FILEIO_ENOSYS;
11860 putpkt_binary (rs->buf, command_bytes);
11861 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
11863 /* If it timed out, something is wrong. Don't try to parse the
11865 if (bytes_read < 0)
11867 *remote_errno = FILEIO_EINVAL;
11871 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
11874 *remote_errno = FILEIO_EINVAL;
11876 case PACKET_UNKNOWN:
11877 *remote_errno = FILEIO_ENOSYS;
11883 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
11886 *remote_errno = FILEIO_EINVAL;
11890 /* Make sure we saw an attachment if and only if we expected one. */
11891 if ((attachment_tmp == NULL && attachment != NULL)
11892 || (attachment_tmp != NULL && attachment == NULL))
11894 *remote_errno = FILEIO_EINVAL;
11898 /* If an attachment was found, it must point into the packet buffer;
11899 work out how many bytes there were. */
11900 if (attachment_tmp != NULL)
11902 *attachment = attachment_tmp;
11903 *attachment_len = bytes_read - (*attachment - rs->buf);
11909 /* See declaration.h. */
11912 readahead_cache::invalidate ()
11917 /* See declaration.h. */
11920 readahead_cache::invalidate_fd (int fd)
11922 if (this->fd == fd)
11926 /* Set the filesystem remote_hostio functions that take FILENAME
11927 arguments will use. Return 0 on success, or -1 if an error
11928 occurs (and set *REMOTE_ERRNO). */
11931 remote_target::remote_hostio_set_filesystem (struct inferior *inf,
11934 struct remote_state *rs = get_remote_state ();
11935 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
11937 int left = get_remote_packet_size () - 1;
11941 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11944 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
11947 remote_buffer_add_string (&p, &left, "vFile:setfs:");
11949 xsnprintf (arg, sizeof (arg), "%x", required_pid);
11950 remote_buffer_add_string (&p, &left, arg);
11952 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
11953 remote_errno, NULL, NULL);
11955 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11959 rs->fs_pid = required_pid;
11964 /* Implementation of to_fileio_open. */
11967 remote_target::remote_hostio_open (inferior *inf, const char *filename,
11968 int flags, int mode, int warn_if_slow,
11971 struct remote_state *rs = get_remote_state ();
11973 int left = get_remote_packet_size () - 1;
11977 static int warning_issued = 0;
11979 printf_unfiltered (_("Reading %s from remote target...\n"),
11982 if (!warning_issued)
11984 warning (_("File transfers from remote targets can be slow."
11985 " Use \"set sysroot\" to access files locally"
11987 warning_issued = 1;
11991 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11994 remote_buffer_add_string (&p, &left, "vFile:open:");
11996 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11997 strlen (filename));
11998 remote_buffer_add_string (&p, &left, ",");
12000 remote_buffer_add_int (&p, &left, flags);
12001 remote_buffer_add_string (&p, &left, ",");
12003 remote_buffer_add_int (&p, &left, mode);
12005 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
12006 remote_errno, NULL, NULL);
12010 remote_target::fileio_open (struct inferior *inf, const char *filename,
12011 int flags, int mode, int warn_if_slow,
12014 return remote_hostio_open (inf, filename, flags, mode, warn_if_slow,
12018 /* Implementation of to_fileio_pwrite. */
12021 remote_target::remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
12022 ULONGEST offset, int *remote_errno)
12024 struct remote_state *rs = get_remote_state ();
12026 int left = get_remote_packet_size ();
12029 rs->readahead_cache.invalidate_fd (fd);
12031 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
12033 remote_buffer_add_int (&p, &left, fd);
12034 remote_buffer_add_string (&p, &left, ",");
12036 remote_buffer_add_int (&p, &left, offset);
12037 remote_buffer_add_string (&p, &left, ",");
12039 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
12040 get_remote_packet_size () - (p - rs->buf));
12042 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
12043 remote_errno, NULL, NULL);
12047 remote_target::fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
12048 ULONGEST offset, int *remote_errno)
12050 return remote_hostio_pwrite (fd, write_buf, len, offset, remote_errno);
12053 /* Helper for the implementation of to_fileio_pread. Read the file
12054 from the remote side with vFile:pread. */
12057 remote_target::remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
12058 ULONGEST offset, int *remote_errno)
12060 struct remote_state *rs = get_remote_state ();
12063 int left = get_remote_packet_size ();
12064 int ret, attachment_len;
12067 remote_buffer_add_string (&p, &left, "vFile:pread:");
12069 remote_buffer_add_int (&p, &left, fd);
12070 remote_buffer_add_string (&p, &left, ",");
12072 remote_buffer_add_int (&p, &left, len);
12073 remote_buffer_add_string (&p, &left, ",");
12075 remote_buffer_add_int (&p, &left, offset);
12077 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
12078 remote_errno, &attachment,
12084 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12086 if (read_len != ret)
12087 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
12092 /* See declaration.h. */
12095 readahead_cache::pread (int fd, gdb_byte *read_buf, size_t len,
12099 && this->offset <= offset
12100 && offset < this->offset + this->bufsize)
12102 ULONGEST max = this->offset + this->bufsize;
12104 if (offset + len > max)
12105 len = max - offset;
12107 memcpy (read_buf, this->buf + offset - this->offset, len);
12114 /* Implementation of to_fileio_pread. */
12117 remote_target::remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
12118 ULONGEST offset, int *remote_errno)
12121 struct remote_state *rs = get_remote_state ();
12122 readahead_cache *cache = &rs->readahead_cache;
12124 ret = cache->pread (fd, read_buf, len, offset);
12127 cache->hit_count++;
12130 fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
12131 pulongest (cache->hit_count));
12135 cache->miss_count++;
12137 fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
12138 pulongest (cache->miss_count));
12141 cache->offset = offset;
12142 cache->bufsize = get_remote_packet_size ();
12143 cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
12145 ret = remote_hostio_pread_vFile (cache->fd, cache->buf, cache->bufsize,
12146 cache->offset, remote_errno);
12149 cache->invalidate_fd (fd);
12153 cache->bufsize = ret;
12154 return cache->pread (fd, read_buf, len, offset);
12158 remote_target::fileio_pread (int fd, gdb_byte *read_buf, int len,
12159 ULONGEST offset, int *remote_errno)
12161 return remote_hostio_pread (fd, read_buf, len, offset, remote_errno);
12164 /* Implementation of to_fileio_close. */
12167 remote_target::remote_hostio_close (int fd, int *remote_errno)
12169 struct remote_state *rs = get_remote_state ();
12171 int left = get_remote_packet_size () - 1;
12173 rs->readahead_cache.invalidate_fd (fd);
12175 remote_buffer_add_string (&p, &left, "vFile:close:");
12177 remote_buffer_add_int (&p, &left, fd);
12179 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
12180 remote_errno, NULL, NULL);
12184 remote_target::fileio_close (int fd, int *remote_errno)
12186 return remote_hostio_close (fd, remote_errno);
12189 /* Implementation of to_fileio_unlink. */
12192 remote_target::remote_hostio_unlink (inferior *inf, const char *filename,
12195 struct remote_state *rs = get_remote_state ();
12197 int left = get_remote_packet_size () - 1;
12199 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12202 remote_buffer_add_string (&p, &left, "vFile:unlink:");
12204 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12205 strlen (filename));
12207 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
12208 remote_errno, NULL, NULL);
12212 remote_target::fileio_unlink (struct inferior *inf, const char *filename,
12215 return remote_hostio_unlink (inf, filename, remote_errno);
12218 /* Implementation of to_fileio_readlink. */
12220 gdb::optional<std::string>
12221 remote_target::fileio_readlink (struct inferior *inf, const char *filename,
12224 struct remote_state *rs = get_remote_state ();
12227 int left = get_remote_packet_size ();
12228 int len, attachment_len;
12231 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12234 remote_buffer_add_string (&p, &left, "vFile:readlink:");
12236 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12237 strlen (filename));
12239 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
12240 remote_errno, &attachment,
12246 std::string ret (len, '\0');
12248 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12249 (gdb_byte *) &ret[0], len);
12250 if (read_len != len)
12251 error (_("Readlink returned %d, but %d bytes."), len, read_len);
12256 /* Implementation of to_fileio_fstat. */
12259 remote_target::fileio_fstat (int fd, struct stat *st, int *remote_errno)
12261 struct remote_state *rs = get_remote_state ();
12263 int left = get_remote_packet_size ();
12264 int attachment_len, ret;
12266 struct fio_stat fst;
12269 remote_buffer_add_string (&p, &left, "vFile:fstat:");
12271 remote_buffer_add_int (&p, &left, fd);
12273 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
12274 remote_errno, &attachment,
12278 if (*remote_errno != FILEIO_ENOSYS)
12281 /* Strictly we should return -1, ENOSYS here, but when
12282 "set sysroot remote:" was implemented in August 2008
12283 BFD's need for a stat function was sidestepped with
12284 this hack. This was not remedied until March 2015
12285 so we retain the previous behavior to avoid breaking
12288 Note that the memset is a March 2015 addition; older
12289 GDBs set st_size *and nothing else* so the structure
12290 would have garbage in all other fields. This might
12291 break something but retaining the previous behavior
12292 here would be just too wrong. */
12294 memset (st, 0, sizeof (struct stat));
12295 st->st_size = INT_MAX;
12299 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12300 (gdb_byte *) &fst, sizeof (fst));
12302 if (read_len != ret)
12303 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
12305 if (read_len != sizeof (fst))
12306 error (_("vFile:fstat returned %d bytes, but expecting %d."),
12307 read_len, (int) sizeof (fst));
12309 remote_fileio_to_host_stat (&fst, st);
12314 /* Implementation of to_filesystem_is_local. */
12317 remote_target::filesystem_is_local ()
12319 /* Valgrind GDB presents itself as a remote target but works
12320 on the local filesystem: it does not implement remote get
12321 and users are not expected to set a sysroot. To handle
12322 this case we treat the remote filesystem as local if the
12323 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
12324 does not support vFile:open. */
12325 if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
12327 enum packet_support ps = packet_support (PACKET_vFile_open);
12329 if (ps == PACKET_SUPPORT_UNKNOWN)
12331 int fd, remote_errno;
12333 /* Try opening a file to probe support. The supplied
12334 filename is irrelevant, we only care about whether
12335 the stub recognizes the packet or not. */
12336 fd = remote_hostio_open (NULL, "just probing",
12337 FILEIO_O_RDONLY, 0700, 0,
12341 remote_hostio_close (fd, &remote_errno);
12343 ps = packet_support (PACKET_vFile_open);
12346 if (ps == PACKET_DISABLE)
12348 static int warning_issued = 0;
12350 if (!warning_issued)
12352 warning (_("remote target does not support file"
12353 " transfer, attempting to access files"
12354 " from local filesystem."));
12355 warning_issued = 1;
12366 remote_fileio_errno_to_host (int errnum)
12372 case FILEIO_ENOENT:
12380 case FILEIO_EACCES:
12382 case FILEIO_EFAULT:
12386 case FILEIO_EEXIST:
12388 case FILEIO_ENODEV:
12390 case FILEIO_ENOTDIR:
12392 case FILEIO_EISDIR:
12394 case FILEIO_EINVAL:
12396 case FILEIO_ENFILE:
12398 case FILEIO_EMFILE:
12402 case FILEIO_ENOSPC:
12404 case FILEIO_ESPIPE:
12408 case FILEIO_ENOSYS:
12410 case FILEIO_ENAMETOOLONG:
12411 return ENAMETOOLONG;
12417 remote_hostio_error (int errnum)
12419 int host_error = remote_fileio_errno_to_host (errnum);
12421 if (host_error == -1)
12422 error (_("Unknown remote I/O error %d"), errnum);
12424 error (_("Remote I/O error: %s"), safe_strerror (host_error));
12427 /* A RAII wrapper around a remote file descriptor. */
12429 class scoped_remote_fd
12432 scoped_remote_fd (remote_target *remote, int fd)
12433 : m_remote (remote), m_fd (fd)
12437 ~scoped_remote_fd ()
12444 m_remote->remote_hostio_close (m_fd, &remote_errno);
12448 /* Swallow exception before it escapes the dtor. If
12449 something goes wrong, likely the connection is gone,
12450 and there's nothing else that can be done. */
12455 DISABLE_COPY_AND_ASSIGN (scoped_remote_fd);
12457 /* Release ownership of the file descriptor, and return it. */
12458 int release () noexcept
12465 /* Return the owned file descriptor. */
12466 int get () const noexcept
12472 /* The remote target. */
12473 remote_target *m_remote;
12475 /* The owned remote I/O file descriptor. */
12480 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
12482 remote_target *remote = get_current_remote_target ();
12484 if (remote == nullptr)
12485 error (_("command can only be used with remote target"));
12487 remote->remote_file_put (local_file, remote_file, from_tty);
12491 remote_target::remote_file_put (const char *local_file, const char *remote_file,
12494 int retcode, remote_errno, bytes, io_size;
12495 int bytes_in_buffer;
12499 gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
12501 perror_with_name (local_file);
12503 scoped_remote_fd fd
12504 (this, remote_hostio_open (NULL,
12505 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
12507 0700, 0, &remote_errno));
12508 if (fd.get () == -1)
12509 remote_hostio_error (remote_errno);
12511 /* Send up to this many bytes at once. They won't all fit in the
12512 remote packet limit, so we'll transfer slightly fewer. */
12513 io_size = get_remote_packet_size ();
12514 gdb::byte_vector buffer (io_size);
12516 bytes_in_buffer = 0;
12519 while (bytes_in_buffer || !saw_eof)
12523 bytes = fread (buffer.data () + bytes_in_buffer, 1,
12524 io_size - bytes_in_buffer,
12528 if (ferror (file.get ()))
12529 error (_("Error reading %s."), local_file);
12532 /* EOF. Unless there is something still in the
12533 buffer from the last iteration, we are done. */
12535 if (bytes_in_buffer == 0)
12543 bytes += bytes_in_buffer;
12544 bytes_in_buffer = 0;
12546 retcode = remote_hostio_pwrite (fd.get (), buffer.data (), bytes,
12547 offset, &remote_errno);
12550 remote_hostio_error (remote_errno);
12551 else if (retcode == 0)
12552 error (_("Remote write of %d bytes returned 0!"), bytes);
12553 else if (retcode < bytes)
12555 /* Short write. Save the rest of the read data for the next
12557 bytes_in_buffer = bytes - retcode;
12558 memmove (buffer.data (), buffer.data () + retcode, bytes_in_buffer);
12564 if (remote_hostio_close (fd.release (), &remote_errno))
12565 remote_hostio_error (remote_errno);
12568 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
12572 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
12574 remote_target *remote = get_current_remote_target ();
12576 if (remote == nullptr)
12577 error (_("command can only be used with remote target"));
12579 remote->remote_file_get (remote_file, local_file, from_tty);
12583 remote_target::remote_file_get (const char *remote_file, const char *local_file,
12586 int remote_errno, bytes, io_size;
12589 scoped_remote_fd fd
12590 (this, remote_hostio_open (NULL,
12591 remote_file, FILEIO_O_RDONLY, 0, 0,
12593 if (fd.get () == -1)
12594 remote_hostio_error (remote_errno);
12596 gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
12598 perror_with_name (local_file);
12600 /* Send up to this many bytes at once. They won't all fit in the
12601 remote packet limit, so we'll transfer slightly fewer. */
12602 io_size = get_remote_packet_size ();
12603 gdb::byte_vector buffer (io_size);
12608 bytes = remote_hostio_pread (fd.get (), buffer.data (), io_size, offset,
12611 /* Success, but no bytes, means end-of-file. */
12614 remote_hostio_error (remote_errno);
12618 bytes = fwrite (buffer.data (), 1, bytes, file.get ());
12620 perror_with_name (local_file);
12623 if (remote_hostio_close (fd.release (), &remote_errno))
12624 remote_hostio_error (remote_errno);
12627 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
12631 remote_file_delete (const char *remote_file, int from_tty)
12633 remote_target *remote = get_current_remote_target ();
12635 if (remote == nullptr)
12636 error (_("command can only be used with remote target"));
12638 remote->remote_file_delete (remote_file, from_tty);
12642 remote_target::remote_file_delete (const char *remote_file, int from_tty)
12644 int retcode, remote_errno;
12646 retcode = remote_hostio_unlink (NULL, remote_file, &remote_errno);
12648 remote_hostio_error (remote_errno);
12651 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
12655 remote_put_command (const char *args, int from_tty)
12658 error_no_arg (_("file to put"));
12660 gdb_argv argv (args);
12661 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12662 error (_("Invalid parameters to remote put"));
12664 remote_file_put (argv[0], argv[1], from_tty);
12668 remote_get_command (const char *args, int from_tty)
12671 error_no_arg (_("file to get"));
12673 gdb_argv argv (args);
12674 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12675 error (_("Invalid parameters to remote get"));
12677 remote_file_get (argv[0], argv[1], from_tty);
12681 remote_delete_command (const char *args, int from_tty)
12684 error_no_arg (_("file to delete"));
12686 gdb_argv argv (args);
12687 if (argv[0] == NULL || argv[1] != NULL)
12688 error (_("Invalid parameters to remote delete"));
12690 remote_file_delete (argv[0], from_tty);
12694 remote_command (const char *args, int from_tty)
12696 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
12700 remote_target::can_execute_reverse ()
12702 if (packet_support (PACKET_bs) == PACKET_ENABLE
12703 || packet_support (PACKET_bc) == PACKET_ENABLE)
12710 remote_target::supports_non_stop ()
12716 remote_target::supports_disable_randomization ()
12718 /* Only supported in extended mode. */
12723 remote_target::supports_multi_process ()
12725 struct remote_state *rs = get_remote_state ();
12727 return remote_multi_process_p (rs);
12731 remote_supports_cond_tracepoints ()
12733 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
12737 remote_target::supports_evaluation_of_breakpoint_conditions ()
12739 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
12743 remote_supports_fast_tracepoints ()
12745 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
12749 remote_supports_static_tracepoints ()
12751 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
12755 remote_supports_install_in_trace ()
12757 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
12761 remote_target::supports_enable_disable_tracepoint ()
12763 return (packet_support (PACKET_EnableDisableTracepoints_feature)
12768 remote_target::supports_string_tracing ()
12770 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
12774 remote_target::can_run_breakpoint_commands ()
12776 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
12780 remote_target::trace_init ()
12782 struct remote_state *rs = get_remote_state ();
12785 remote_get_noisy_reply ();
12786 if (strcmp (rs->buf, "OK") != 0)
12787 error (_("Target does not support this command."));
12790 /* Recursive routine to walk through command list including loops, and
12791 download packets for each command. */
12794 remote_target::remote_download_command_source (int num, ULONGEST addr,
12795 struct command_line *cmds)
12797 struct remote_state *rs = get_remote_state ();
12798 struct command_line *cmd;
12800 for (cmd = cmds; cmd; cmd = cmd->next)
12802 QUIT; /* Allow user to bail out with ^C. */
12803 strcpy (rs->buf, "QTDPsrc:");
12804 encode_source_string (num, addr, "cmd", cmd->line,
12805 rs->buf + strlen (rs->buf),
12806 rs->buf_size - strlen (rs->buf));
12808 remote_get_noisy_reply ();
12809 if (strcmp (rs->buf, "OK"))
12810 warning (_("Target does not support source download."));
12812 if (cmd->control_type == while_control
12813 || cmd->control_type == while_stepping_control)
12815 remote_download_command_source (num, addr, cmd->body_list_0.get ());
12817 QUIT; /* Allow user to bail out with ^C. */
12818 strcpy (rs->buf, "QTDPsrc:");
12819 encode_source_string (num, addr, "cmd", "end",
12820 rs->buf + strlen (rs->buf),
12821 rs->buf_size - strlen (rs->buf));
12823 remote_get_noisy_reply ();
12824 if (strcmp (rs->buf, "OK"))
12825 warning (_("Target does not support source download."));
12831 remote_target::download_tracepoint (struct bp_location *loc)
12835 std::vector<std::string> tdp_actions;
12836 std::vector<std::string> stepping_actions;
12838 struct breakpoint *b = loc->owner;
12839 struct tracepoint *t = (struct tracepoint *) b;
12840 struct remote_state *rs = get_remote_state ();
12842 const char *err_msg = _("Tracepoint packet too large for target.");
12845 /* We use a buffer other than rs->buf because we'll build strings
12846 across multiple statements, and other statements in between could
12848 gdb::char_vector buf (get_remote_packet_size ());
12850 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
12852 tpaddr = loc->address;
12853 sprintf_vma (addrbuf, tpaddr);
12854 ret = snprintf (buf.data (), buf.size (), "QTDP:%x:%s:%c:%lx:%x",
12855 b->number, addrbuf, /* address */
12856 (b->enable_state == bp_enabled ? 'E' : 'D'),
12857 t->step_count, t->pass_count);
12859 if (ret < 0 || ret >= buf.size ())
12860 error ("%s", err_msg);
12862 /* Fast tracepoints are mostly handled by the target, but we can
12863 tell the target how big of an instruction block should be moved
12865 if (b->type == bp_fast_tracepoint)
12867 /* Only test for support at download time; we may not know
12868 target capabilities at definition time. */
12869 if (remote_supports_fast_tracepoints ())
12871 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
12874 size_left = buf.size () - strlen (buf.data ());
12875 ret = snprintf (buf.data () + strlen (buf.data ()),
12877 gdb_insn_length (loc->gdbarch, tpaddr));
12879 if (ret < 0 || ret >= size_left)
12880 error ("%s", err_msg);
12883 /* If it passed validation at definition but fails now,
12884 something is very wrong. */
12885 internal_error (__FILE__, __LINE__,
12886 _("Fast tracepoint not "
12887 "valid during download"));
12890 /* Fast tracepoints are functionally identical to regular
12891 tracepoints, so don't take lack of support as a reason to
12892 give up on the trace run. */
12893 warning (_("Target does not support fast tracepoints, "
12894 "downloading %d as regular tracepoint"), b->number);
12896 else if (b->type == bp_static_tracepoint)
12898 /* Only test for support at download time; we may not know
12899 target capabilities at definition time. */
12900 if (remote_supports_static_tracepoints ())
12902 struct static_tracepoint_marker marker;
12904 if (target_static_tracepoint_marker_at (tpaddr, &marker))
12906 size_left = buf.size () - strlen (buf.data ());
12907 ret = snprintf (buf.data () + strlen (buf.data ()),
12910 if (ret < 0 || ret >= size_left)
12911 error ("%s", err_msg);
12914 error (_("Static tracepoint not valid during download"));
12917 /* Fast tracepoints are functionally identical to regular
12918 tracepoints, so don't take lack of support as a reason
12919 to give up on the trace run. */
12920 error (_("Target does not support static tracepoints"));
12922 /* If the tracepoint has a conditional, make it into an agent
12923 expression and append to the definition. */
12926 /* Only test support at download time, we may not know target
12927 capabilities at definition time. */
12928 if (remote_supports_cond_tracepoints ())
12930 agent_expr_up aexpr = gen_eval_for_expr (tpaddr,
12933 size_left = buf.size () - strlen (buf.data ());
12935 ret = snprintf (buf.data () + strlen (buf.data ()),
12936 size_left, ":X%x,", aexpr->len);
12938 if (ret < 0 || ret >= size_left)
12939 error ("%s", err_msg);
12941 size_left = buf.size () - strlen (buf.data ());
12943 /* Two bytes to encode each aexpr byte, plus the terminating
12945 if (aexpr->len * 2 + 1 > size_left)
12946 error ("%s", err_msg);
12948 pkt = buf.data () + strlen (buf.data ());
12950 for (int ndx = 0; ndx < aexpr->len; ++ndx)
12951 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
12955 warning (_("Target does not support conditional tracepoints, "
12956 "ignoring tp %d cond"), b->number);
12959 if (b->commands || *default_collect)
12961 size_left = buf.size () - strlen (buf.data ());
12963 ret = snprintf (buf.data () + strlen (buf.data ()),
12966 if (ret < 0 || ret >= size_left)
12967 error ("%s", err_msg);
12970 putpkt (buf.data ());
12971 remote_get_noisy_reply ();
12972 if (strcmp (rs->buf, "OK"))
12973 error (_("Target does not support tracepoints."));
12975 /* do_single_steps (t); */
12976 for (auto action_it = tdp_actions.begin ();
12977 action_it != tdp_actions.end (); action_it++)
12979 QUIT; /* Allow user to bail out with ^C. */
12981 bool has_more = ((action_it + 1) != tdp_actions.end ()
12982 || !stepping_actions.empty ());
12984 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%c",
12985 b->number, addrbuf, /* address */
12986 action_it->c_str (),
12987 has_more ? '-' : 0);
12989 if (ret < 0 || ret >= buf.size ())
12990 error ("%s", err_msg);
12992 putpkt (buf.data ());
12993 remote_get_noisy_reply ();
12994 if (strcmp (rs->buf, "OK"))
12995 error (_("Error on target while setting tracepoints."));
12998 for (auto action_it = stepping_actions.begin ();
12999 action_it != stepping_actions.end (); action_it++)
13001 QUIT; /* Allow user to bail out with ^C. */
13003 bool is_first = action_it == stepping_actions.begin ();
13004 bool has_more = (action_it + 1) != stepping_actions.end ();
13006 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%s%s",
13007 b->number, addrbuf, /* address */
13008 is_first ? "S" : "",
13009 action_it->c_str (),
13010 has_more ? "-" : "");
13012 if (ret < 0 || ret >= buf.size ())
13013 error ("%s", err_msg);
13015 putpkt (buf.data ());
13016 remote_get_noisy_reply ();
13017 if (strcmp (rs->buf, "OK"))
13018 error (_("Error on target while setting tracepoints."));
13021 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
13023 if (b->location != NULL)
13025 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13027 if (ret < 0 || ret >= buf.size ())
13028 error ("%s", err_msg);
13030 encode_source_string (b->number, loc->address, "at",
13031 event_location_to_string (b->location.get ()),
13032 buf.data () + strlen (buf.data ()),
13033 buf.size () - strlen (buf.data ()));
13034 putpkt (buf.data ());
13035 remote_get_noisy_reply ();
13036 if (strcmp (rs->buf, "OK"))
13037 warning (_("Target does not support source download."));
13039 if (b->cond_string)
13041 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13043 if (ret < 0 || ret >= buf.size ())
13044 error ("%s", err_msg);
13046 encode_source_string (b->number, loc->address,
13047 "cond", b->cond_string,
13048 buf.data () + strlen (buf.data ()),
13049 buf.size () - strlen (buf.data ()));
13050 putpkt (buf.data ());
13051 remote_get_noisy_reply ();
13052 if (strcmp (rs->buf, "OK"))
13053 warning (_("Target does not support source download."));
13055 remote_download_command_source (b->number, loc->address,
13056 breakpoint_commands (b));
13061 remote_target::can_download_tracepoint ()
13063 struct remote_state *rs = get_remote_state ();
13064 struct trace_status *ts;
13067 /* Don't try to install tracepoints until we've relocated our
13068 symbols, and fetched and merged the target's tracepoint list with
13070 if (rs->starting_up)
13073 ts = current_trace_status ();
13074 status = get_trace_status (ts);
13076 if (status == -1 || !ts->running_known || !ts->running)
13079 /* If we are in a tracing experiment, but remote stub doesn't support
13080 installing tracepoint in trace, we have to return. */
13081 if (!remote_supports_install_in_trace ())
13089 remote_target::download_trace_state_variable (const trace_state_variable &tsv)
13091 struct remote_state *rs = get_remote_state ();
13094 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
13095 tsv.number, phex ((ULONGEST) tsv.initial_value, 8),
13097 p = rs->buf + strlen (rs->buf);
13098 if ((p - rs->buf) + tsv.name.length () * 2 >= get_remote_packet_size ())
13099 error (_("Trace state variable name too long for tsv definition packet"));
13100 p += 2 * bin2hex ((gdb_byte *) (tsv.name.data ()), p, tsv.name.length ());
13103 remote_get_noisy_reply ();
13104 if (*rs->buf == '\0')
13105 error (_("Target does not support this command."));
13106 if (strcmp (rs->buf, "OK") != 0)
13107 error (_("Error on target while downloading trace state variable."));
13111 remote_target::enable_tracepoint (struct bp_location *location)
13113 struct remote_state *rs = get_remote_state ();
13116 sprintf_vma (addr_buf, location->address);
13117 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
13118 location->owner->number, addr_buf);
13120 remote_get_noisy_reply ();
13121 if (*rs->buf == '\0')
13122 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
13123 if (strcmp (rs->buf, "OK") != 0)
13124 error (_("Error on target while enabling tracepoint."));
13128 remote_target::disable_tracepoint (struct bp_location *location)
13130 struct remote_state *rs = get_remote_state ();
13133 sprintf_vma (addr_buf, location->address);
13134 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
13135 location->owner->number, addr_buf);
13137 remote_get_noisy_reply ();
13138 if (*rs->buf == '\0')
13139 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
13140 if (strcmp (rs->buf, "OK") != 0)
13141 error (_("Error on target while disabling tracepoint."));
13145 remote_target::trace_set_readonly_regions ()
13149 bfd_size_type size;
13155 return; /* No information to give. */
13157 struct remote_state *rs = get_remote_state ();
13159 strcpy (rs->buf, "QTro");
13160 offset = strlen (rs->buf);
13161 for (s = exec_bfd->sections; s; s = s->next)
13163 char tmp1[40], tmp2[40];
13166 if ((s->flags & SEC_LOAD) == 0 ||
13167 /* (s->flags & SEC_CODE) == 0 || */
13168 (s->flags & SEC_READONLY) == 0)
13172 vma = bfd_get_section_vma (abfd, s);
13173 size = bfd_get_section_size (s);
13174 sprintf_vma (tmp1, vma);
13175 sprintf_vma (tmp2, vma + size);
13176 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
13177 if (offset + sec_length + 1 > rs->buf_size)
13179 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
13181 Too many sections for read-only sections definition packet."));
13184 xsnprintf (rs->buf + offset, rs->buf_size - offset, ":%s,%s",
13186 offset += sec_length;
13191 getpkt (&rs->buf, &rs->buf_size, 0);
13196 remote_target::trace_start ()
13198 struct remote_state *rs = get_remote_state ();
13200 putpkt ("QTStart");
13201 remote_get_noisy_reply ();
13202 if (*rs->buf == '\0')
13203 error (_("Target does not support this command."));
13204 if (strcmp (rs->buf, "OK") != 0)
13205 error (_("Bogus reply from target: %s"), rs->buf);
13209 remote_target::get_trace_status (struct trace_status *ts)
13211 /* Initialize it just to avoid a GCC false warning. */
13213 /* FIXME we need to get register block size some other way. */
13214 extern int trace_regblock_size;
13215 enum packet_result result;
13216 struct remote_state *rs = get_remote_state ();
13218 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
13221 trace_regblock_size
13222 = rs->get_remote_arch_state (target_gdbarch ())->sizeof_g_packet;
13224 putpkt ("qTStatus");
13228 p = remote_get_noisy_reply ();
13230 CATCH (ex, RETURN_MASK_ERROR)
13232 if (ex.error != TARGET_CLOSE_ERROR)
13234 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
13237 throw_exception (ex);
13241 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
13243 /* If the remote target doesn't do tracing, flag it. */
13244 if (result == PACKET_UNKNOWN)
13247 /* We're working with a live target. */
13248 ts->filename = NULL;
13251 error (_("Bogus trace status reply from target: %s"), rs->buf);
13253 /* Function 'parse_trace_status' sets default value of each field of
13254 'ts' at first, so we don't have to do it here. */
13255 parse_trace_status (p, ts);
13257 return ts->running;
13261 remote_target::get_tracepoint_status (struct breakpoint *bp,
13262 struct uploaded_tp *utp)
13264 struct remote_state *rs = get_remote_state ();
13266 struct bp_location *loc;
13267 struct tracepoint *tp = (struct tracepoint *) bp;
13268 size_t size = get_remote_packet_size ();
13273 tp->traceframe_usage = 0;
13274 for (loc = tp->loc; loc; loc = loc->next)
13276 /* If the tracepoint was never downloaded, don't go asking for
13278 if (tp->number_on_target == 0)
13280 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
13281 phex_nz (loc->address, 0));
13283 reply = remote_get_noisy_reply ();
13284 if (reply && *reply)
13287 parse_tracepoint_status (reply + 1, bp, utp);
13293 utp->hit_count = 0;
13294 utp->traceframe_usage = 0;
13295 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
13296 phex_nz (utp->addr, 0));
13298 reply = remote_get_noisy_reply ();
13299 if (reply && *reply)
13302 parse_tracepoint_status (reply + 1, bp, utp);
13308 remote_target::trace_stop ()
13310 struct remote_state *rs = get_remote_state ();
13313 remote_get_noisy_reply ();
13314 if (*rs->buf == '\0')
13315 error (_("Target does not support this command."));
13316 if (strcmp (rs->buf, "OK") != 0)
13317 error (_("Bogus reply from target: %s"), rs->buf);
13321 remote_target::trace_find (enum trace_find_type type, int num,
13322 CORE_ADDR addr1, CORE_ADDR addr2,
13325 struct remote_state *rs = get_remote_state ();
13326 char *endbuf = rs->buf + get_remote_packet_size ();
13328 int target_frameno = -1, target_tracept = -1;
13330 /* Lookups other than by absolute frame number depend on the current
13331 trace selected, so make sure it is correct on the remote end
13333 if (type != tfind_number)
13334 set_remote_traceframe ();
13337 strcpy (p, "QTFrame:");
13338 p = strchr (p, '\0');
13342 xsnprintf (p, endbuf - p, "%x", num);
13345 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
13348 xsnprintf (p, endbuf - p, "tdp:%x", num);
13351 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
13352 phex_nz (addr2, 0));
13354 case tfind_outside:
13355 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
13356 phex_nz (addr2, 0));
13359 error (_("Unknown trace find type %d"), type);
13363 reply = remote_get_noisy_reply ();
13364 if (*reply == '\0')
13365 error (_("Target does not support this command."));
13367 while (reply && *reply)
13372 target_frameno = (int) strtol (p, &reply, 16);
13374 error (_("Unable to parse trace frame number"));
13375 /* Don't update our remote traceframe number cache on failure
13376 to select a remote traceframe. */
13377 if (target_frameno == -1)
13382 target_tracept = (int) strtol (p, &reply, 16);
13384 error (_("Unable to parse tracepoint number"));
13386 case 'O': /* "OK"? */
13387 if (reply[1] == 'K' && reply[2] == '\0')
13390 error (_("Bogus reply from target: %s"), reply);
13393 error (_("Bogus reply from target: %s"), reply);
13396 *tpp = target_tracept;
13398 rs->remote_traceframe_number = target_frameno;
13399 return target_frameno;
13403 remote_target::get_trace_state_variable_value (int tsvnum, LONGEST *val)
13405 struct remote_state *rs = get_remote_state ();
13409 set_remote_traceframe ();
13411 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
13413 reply = remote_get_noisy_reply ();
13414 if (reply && *reply)
13418 unpack_varlen_hex (reply + 1, &uval);
13419 *val = (LONGEST) uval;
13427 remote_target::save_trace_data (const char *filename)
13429 struct remote_state *rs = get_remote_state ();
13433 strcpy (p, "QTSave:");
13435 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
13436 error (_("Remote file name too long for trace save packet"));
13437 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
13440 reply = remote_get_noisy_reply ();
13441 if (*reply == '\0')
13442 error (_("Target does not support this command."));
13443 if (strcmp (reply, "OK") != 0)
13444 error (_("Bogus reply from target: %s"), reply);
13448 /* This is basically a memory transfer, but needs to be its own packet
13449 because we don't know how the target actually organizes its trace
13450 memory, plus we want to be able to ask for as much as possible, but
13451 not be unhappy if we don't get as much as we ask for. */
13454 remote_target::get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
13456 struct remote_state *rs = get_remote_state ();
13462 strcpy (p, "qTBuffer:");
13464 p += hexnumstr (p, offset);
13466 p += hexnumstr (p, len);
13470 reply = remote_get_noisy_reply ();
13471 if (reply && *reply)
13473 /* 'l' by itself means we're at the end of the buffer and
13474 there is nothing more to get. */
13478 /* Convert the reply into binary. Limit the number of bytes to
13479 convert according to our passed-in buffer size, rather than
13480 what was returned in the packet; if the target is
13481 unexpectedly generous and gives us a bigger reply than we
13482 asked for, we don't want to crash. */
13483 rslt = hex2bin (reply, buf, len);
13487 /* Something went wrong, flag as an error. */
13492 remote_target::set_disconnected_tracing (int val)
13494 struct remote_state *rs = get_remote_state ();
13496 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
13500 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
13502 reply = remote_get_noisy_reply ();
13503 if (*reply == '\0')
13504 error (_("Target does not support this command."));
13505 if (strcmp (reply, "OK") != 0)
13506 error (_("Bogus reply from target: %s"), reply);
13509 warning (_("Target does not support disconnected tracing."));
13513 remote_target::core_of_thread (ptid_t ptid)
13515 struct thread_info *info = find_thread_ptid (ptid);
13517 if (info != NULL && info->priv != NULL)
13518 return get_remote_thread_info (info)->core;
13524 remote_target::set_circular_trace_buffer (int val)
13526 struct remote_state *rs = get_remote_state ();
13529 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
13531 reply = remote_get_noisy_reply ();
13532 if (*reply == '\0')
13533 error (_("Target does not support this command."));
13534 if (strcmp (reply, "OK") != 0)
13535 error (_("Bogus reply from target: %s"), reply);
13539 remote_target::traceframe_info ()
13541 gdb::optional<gdb::char_vector> text
13542 = target_read_stralloc (current_top_target (), TARGET_OBJECT_TRACEFRAME_INFO,
13545 return parse_traceframe_info (text->data ());
13550 /* Handle the qTMinFTPILen packet. Returns the minimum length of
13551 instruction on which a fast tracepoint may be placed. Returns -1
13552 if the packet is not supported, and 0 if the minimum instruction
13553 length is unknown. */
13556 remote_target::get_min_fast_tracepoint_insn_len ()
13558 struct remote_state *rs = get_remote_state ();
13561 /* If we're not debugging a process yet, the IPA can't be
13563 if (!target_has_execution)
13566 /* Make sure the remote is pointing at the right process. */
13567 set_general_process ();
13569 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
13571 reply = remote_get_noisy_reply ();
13572 if (*reply == '\0')
13576 ULONGEST min_insn_len;
13578 unpack_varlen_hex (reply, &min_insn_len);
13580 return (int) min_insn_len;
13585 remote_target::set_trace_buffer_size (LONGEST val)
13587 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
13589 struct remote_state *rs = get_remote_state ();
13590 char *buf = rs->buf;
13591 char *endbuf = rs->buf + get_remote_packet_size ();
13592 enum packet_result result;
13594 gdb_assert (val >= 0 || val == -1);
13595 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
13596 /* Send -1 as literal "-1" to avoid host size dependency. */
13600 buf += hexnumstr (buf, (ULONGEST) -val);
13603 buf += hexnumstr (buf, (ULONGEST) val);
13606 remote_get_noisy_reply ();
13607 result = packet_ok (rs->buf,
13608 &remote_protocol_packets[PACKET_QTBuffer_size]);
13610 if (result != PACKET_OK)
13611 warning (_("Bogus reply from target: %s"), rs->buf);
13616 remote_target::set_trace_notes (const char *user, const char *notes,
13617 const char *stop_notes)
13619 struct remote_state *rs = get_remote_state ();
13621 char *buf = rs->buf;
13622 char *endbuf = rs->buf + get_remote_packet_size ();
13625 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
13628 buf += xsnprintf (buf, endbuf - buf, "user:");
13629 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
13635 buf += xsnprintf (buf, endbuf - buf, "notes:");
13636 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
13642 buf += xsnprintf (buf, endbuf - buf, "tstop:");
13643 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
13647 /* Ensure the buffer is terminated. */
13651 reply = remote_get_noisy_reply ();
13652 if (*reply == '\0')
13655 if (strcmp (reply, "OK") != 0)
13656 error (_("Bogus reply from target: %s"), reply);
13662 remote_target::use_agent (bool use)
13664 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
13666 struct remote_state *rs = get_remote_state ();
13668 /* If the stub supports QAgent. */
13669 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
13671 getpkt (&rs->buf, &rs->buf_size, 0);
13673 if (strcmp (rs->buf, "OK") == 0)
13684 remote_target::can_use_agent ()
13686 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
13689 struct btrace_target_info
13691 /* The ptid of the traced thread. */
13694 /* The obtained branch trace configuration. */
13695 struct btrace_config conf;
13698 /* Reset our idea of our target's btrace configuration. */
13701 remote_btrace_reset (remote_state *rs)
13703 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
13706 /* Synchronize the configuration with the target. */
13709 remote_target::btrace_sync_conf (const btrace_config *conf)
13711 struct packet_config *packet;
13712 struct remote_state *rs;
13713 char *buf, *pos, *endbuf;
13715 rs = get_remote_state ();
13717 endbuf = buf + get_remote_packet_size ();
13719 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
13720 if (packet_config_support (packet) == PACKET_ENABLE
13721 && conf->bts.size != rs->btrace_config.bts.size)
13724 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13728 getpkt (&buf, &rs->buf_size, 0);
13730 if (packet_ok (buf, packet) == PACKET_ERROR)
13732 if (buf[0] == 'E' && buf[1] == '.')
13733 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
13735 error (_("Failed to configure the BTS buffer size."));
13738 rs->btrace_config.bts.size = conf->bts.size;
13741 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
13742 if (packet_config_support (packet) == PACKET_ENABLE
13743 && conf->pt.size != rs->btrace_config.pt.size)
13746 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13750 getpkt (&buf, &rs->buf_size, 0);
13752 if (packet_ok (buf, packet) == PACKET_ERROR)
13754 if (buf[0] == 'E' && buf[1] == '.')
13755 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
13757 error (_("Failed to configure the trace buffer size."));
13760 rs->btrace_config.pt.size = conf->pt.size;
13764 /* Read the current thread's btrace configuration from the target and
13765 store it into CONF. */
13768 btrace_read_config (struct btrace_config *conf)
13770 gdb::optional<gdb::char_vector> xml
13771 = target_read_stralloc (current_top_target (), TARGET_OBJECT_BTRACE_CONF, "");
13773 parse_xml_btrace_conf (conf, xml->data ());
13776 /* Maybe reopen target btrace. */
13779 remote_target::remote_btrace_maybe_reopen ()
13781 struct remote_state *rs = get_remote_state ();
13782 struct thread_info *tp;
13783 int btrace_target_pushed = 0;
13784 #if !defined (HAVE_LIBIPT)
13788 scoped_restore_current_thread restore_thread;
13790 ALL_NON_EXITED_THREADS (tp)
13792 set_general_thread (tp->ptid);
13794 memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
13795 btrace_read_config (&rs->btrace_config);
13797 if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
13800 #if !defined (HAVE_LIBIPT)
13801 if (rs->btrace_config.format == BTRACE_FORMAT_PT)
13806 warning (_("Target is recording using Intel Processor Trace "
13807 "but support was disabled at compile time."));
13812 #endif /* !defined (HAVE_LIBIPT) */
13814 /* Push target, once, but before anything else happens. This way our
13815 changes to the threads will be cleaned up by unpushing the target
13816 in case btrace_read_config () throws. */
13817 if (!btrace_target_pushed)
13819 btrace_target_pushed = 1;
13820 record_btrace_push_target ();
13821 printf_filtered (_("Target is recording using %s.\n"),
13822 btrace_format_string (rs->btrace_config.format));
13825 tp->btrace.target = XCNEW (struct btrace_target_info);
13826 tp->btrace.target->ptid = tp->ptid;
13827 tp->btrace.target->conf = rs->btrace_config;
13831 /* Enable branch tracing. */
13833 struct btrace_target_info *
13834 remote_target::enable_btrace (ptid_t ptid, const struct btrace_config *conf)
13836 struct btrace_target_info *tinfo = NULL;
13837 struct packet_config *packet = NULL;
13838 struct remote_state *rs = get_remote_state ();
13839 char *buf = rs->buf;
13840 char *endbuf = rs->buf + get_remote_packet_size ();
13842 switch (conf->format)
13844 case BTRACE_FORMAT_BTS:
13845 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
13848 case BTRACE_FORMAT_PT:
13849 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
13853 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
13854 error (_("Target does not support branch tracing."));
13856 btrace_sync_conf (conf);
13858 set_general_thread (ptid);
13860 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13862 getpkt (&rs->buf, &rs->buf_size, 0);
13864 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13866 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13867 error (_("Could not enable branch tracing for %s: %s"),
13868 target_pid_to_str (ptid), rs->buf + 2);
13870 error (_("Could not enable branch tracing for %s."),
13871 target_pid_to_str (ptid));
13874 tinfo = XCNEW (struct btrace_target_info);
13875 tinfo->ptid = ptid;
13877 /* If we fail to read the configuration, we lose some information, but the
13878 tracing itself is not impacted. */
13881 btrace_read_config (&tinfo->conf);
13883 CATCH (err, RETURN_MASK_ERROR)
13885 if (err.message != NULL)
13886 warning ("%s", err.message);
13893 /* Disable branch tracing. */
13896 remote_target::disable_btrace (struct btrace_target_info *tinfo)
13898 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
13899 struct remote_state *rs = get_remote_state ();
13900 char *buf = rs->buf;
13901 char *endbuf = rs->buf + get_remote_packet_size ();
13903 if (packet_config_support (packet) != PACKET_ENABLE)
13904 error (_("Target does not support branch tracing."));
13906 set_general_thread (tinfo->ptid);
13908 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13910 getpkt (&rs->buf, &rs->buf_size, 0);
13912 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13914 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13915 error (_("Could not disable branch tracing for %s: %s"),
13916 target_pid_to_str (tinfo->ptid), rs->buf + 2);
13918 error (_("Could not disable branch tracing for %s."),
13919 target_pid_to_str (tinfo->ptid));
13925 /* Teardown branch tracing. */
13928 remote_target::teardown_btrace (struct btrace_target_info *tinfo)
13930 /* We must not talk to the target during teardown. */
13934 /* Read the branch trace. */
13937 remote_target::read_btrace (struct btrace_data *btrace,
13938 struct btrace_target_info *tinfo,
13939 enum btrace_read_type type)
13941 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
13944 if (packet_config_support (packet) != PACKET_ENABLE)
13945 error (_("Target does not support branch tracing."));
13947 #if !defined(HAVE_LIBEXPAT)
13948 error (_("Cannot process branch tracing result. XML parsing not supported."));
13953 case BTRACE_READ_ALL:
13956 case BTRACE_READ_NEW:
13959 case BTRACE_READ_DELTA:
13963 internal_error (__FILE__, __LINE__,
13964 _("Bad branch tracing read type: %u."),
13965 (unsigned int) type);
13968 gdb::optional<gdb::char_vector> xml
13969 = target_read_stralloc (current_top_target (), TARGET_OBJECT_BTRACE, annex);
13971 return BTRACE_ERR_UNKNOWN;
13973 parse_xml_btrace (btrace, xml->data ());
13975 return BTRACE_ERR_NONE;
13978 const struct btrace_config *
13979 remote_target::btrace_conf (const struct btrace_target_info *tinfo)
13981 return &tinfo->conf;
13985 remote_target::augmented_libraries_svr4_read ()
13987 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
13991 /* Implementation of to_load. */
13994 remote_target::load (const char *name, int from_tty)
13996 generic_load (name, from_tty);
13999 /* Accepts an integer PID; returns a string representing a file that
14000 can be opened on the remote side to get the symbols for the child
14001 process. Returns NULL if the operation is not supported. */
14004 remote_target::pid_to_exec_file (int pid)
14006 static gdb::optional<gdb::char_vector> filename;
14007 struct inferior *inf;
14008 char *annex = NULL;
14010 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
14013 inf = find_inferior_pid (pid);
14015 internal_error (__FILE__, __LINE__,
14016 _("not currently attached to process %d"), pid);
14018 if (!inf->fake_pid_p)
14020 const int annex_size = 9;
14022 annex = (char *) alloca (annex_size);
14023 xsnprintf (annex, annex_size, "%x", pid);
14026 filename = target_read_stralloc (current_top_target (),
14027 TARGET_OBJECT_EXEC_FILE, annex);
14029 return filename ? filename->data () : nullptr;
14032 /* Implement the to_can_do_single_step target_ops method. */
14035 remote_target::can_do_single_step ()
14037 /* We can only tell whether target supports single step or not by
14038 supported s and S vCont actions if the stub supports vContSupported
14039 feature. If the stub doesn't support vContSupported feature,
14040 we have conservatively to think target doesn't supports single
14042 if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
14044 struct remote_state *rs = get_remote_state ();
14046 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
14047 remote_vcont_probe ();
14049 return rs->supports_vCont.s && rs->supports_vCont.S;
14055 /* Implementation of the to_execution_direction method for the remote
14058 enum exec_direction_kind
14059 remote_target::execution_direction ()
14061 struct remote_state *rs = get_remote_state ();
14063 return rs->last_resume_exec_dir;
14066 /* Return pointer to the thread_info struct which corresponds to
14067 THREAD_HANDLE (having length HANDLE_LEN). */
14070 remote_target::thread_handle_to_thread_info (const gdb_byte *thread_handle,
14074 struct thread_info *tp;
14076 ALL_NON_EXITED_THREADS (tp)
14078 remote_thread_info *priv = get_remote_thread_info (tp);
14080 if (tp->inf == inf && priv != NULL)
14082 if (handle_len != priv->thread_handle.size ())
14083 error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
14084 handle_len, priv->thread_handle.size ());
14085 if (memcmp (thread_handle, priv->thread_handle.data (),
14095 remote_target::can_async_p ()
14097 struct remote_state *rs = get_remote_state ();
14099 /* We don't go async if the user has explicitly prevented it with the
14100 "maint set target-async" command. */
14101 if (!target_async_permitted)
14104 /* We're async whenever the serial device is. */
14105 return serial_can_async_p (rs->remote_desc);
14109 remote_target::is_async_p ()
14111 struct remote_state *rs = get_remote_state ();
14113 if (!target_async_permitted)
14114 /* We only enable async when the user specifically asks for it. */
14117 /* We're async whenever the serial device is. */
14118 return serial_is_async_p (rs->remote_desc);
14121 /* Pass the SERIAL event on and up to the client. One day this code
14122 will be able to delay notifying the client of an event until the
14123 point where an entire packet has been received. */
14125 static serial_event_ftype remote_async_serial_handler;
14128 remote_async_serial_handler (struct serial *scb, void *context)
14130 /* Don't propogate error information up to the client. Instead let
14131 the client find out about the error by querying the target. */
14132 inferior_event_handler (INF_REG_EVENT, NULL);
14136 remote_async_inferior_event_handler (gdb_client_data data)
14138 inferior_event_handler (INF_REG_EVENT, data);
14142 remote_target::async (int enable)
14144 struct remote_state *rs = get_remote_state ();
14148 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
14150 /* If there are pending events in the stop reply queue tell the
14151 event loop to process them. */
14152 if (!rs->stop_reply_queue.empty ())
14153 mark_async_event_handler (rs->remote_async_inferior_event_token);
14154 /* For simplicity, below we clear the pending events token
14155 without remembering whether it is marked, so here we always
14156 mark it. If there's actually no pending notification to
14157 process, this ends up being a no-op (other than a spurious
14158 event-loop wakeup). */
14159 if (target_is_non_stop_p ())
14160 mark_async_event_handler (rs->notif_state->get_pending_events_token);
14164 serial_async (rs->remote_desc, NULL, NULL);
14165 /* If the core is disabling async, it doesn't want to be
14166 disturbed with target events. Clear all async event sources
14168 clear_async_event_handler (rs->remote_async_inferior_event_token);
14169 if (target_is_non_stop_p ())
14170 clear_async_event_handler (rs->notif_state->get_pending_events_token);
14174 /* Implementation of the to_thread_events method. */
14177 remote_target::thread_events (int enable)
14179 struct remote_state *rs = get_remote_state ();
14180 size_t size = get_remote_packet_size ();
14182 if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
14185 xsnprintf (rs->buf, size, "QThreadEvents:%x", enable ? 1 : 0);
14187 getpkt (&rs->buf, &rs->buf_size, 0);
14189 switch (packet_ok (rs->buf,
14190 &remote_protocol_packets[PACKET_QThreadEvents]))
14193 if (strcmp (rs->buf, "OK") != 0)
14194 error (_("Remote refused setting thread events: %s"), rs->buf);
14197 warning (_("Remote failure reply: %s"), rs->buf);
14199 case PACKET_UNKNOWN:
14205 set_remote_cmd (const char *args, int from_tty)
14207 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
14211 show_remote_cmd (const char *args, int from_tty)
14213 /* We can't just use cmd_show_list here, because we want to skip
14214 the redundant "show remote Z-packet" and the legacy aliases. */
14215 struct cmd_list_element *list = remote_show_cmdlist;
14216 struct ui_out *uiout = current_uiout;
14218 ui_out_emit_tuple tuple_emitter (uiout, "showlist");
14219 for (; list != NULL; list = list->next)
14220 if (strcmp (list->name, "Z-packet") == 0)
14222 else if (list->type == not_set_cmd)
14223 /* Alias commands are exactly like the original, except they
14224 don't have the normal type. */
14228 ui_out_emit_tuple option_emitter (uiout, "option");
14230 uiout->field_string ("name", list->name);
14231 uiout->text (": ");
14232 if (list->type == show_cmd)
14233 do_show_command (NULL, from_tty, list);
14235 cmd_func (list, NULL, from_tty);
14240 /* Function to be called whenever a new objfile (shlib) is detected. */
14242 remote_new_objfile (struct objfile *objfile)
14244 remote_target *remote = get_current_remote_target ();
14246 if (remote != NULL) /* Have a remote connection. */
14247 remote->remote_check_symbols ();
14250 /* Pull all the tracepoints defined on the target and create local
14251 data structures representing them. We don't want to create real
14252 tracepoints yet, we don't want to mess up the user's existing
14256 remote_target::upload_tracepoints (struct uploaded_tp **utpp)
14258 struct remote_state *rs = get_remote_state ();
14261 /* Ask for a first packet of tracepoint definition. */
14263 getpkt (&rs->buf, &rs->buf_size, 0);
14265 while (*p && *p != 'l')
14267 parse_tracepoint_definition (p, utpp);
14268 /* Ask for another packet of tracepoint definition. */
14270 getpkt (&rs->buf, &rs->buf_size, 0);
14277 remote_target::upload_trace_state_variables (struct uploaded_tsv **utsvp)
14279 struct remote_state *rs = get_remote_state ();
14282 /* Ask for a first packet of variable definition. */
14284 getpkt (&rs->buf, &rs->buf_size, 0);
14286 while (*p && *p != 'l')
14288 parse_tsv_definition (p, utsvp);
14289 /* Ask for another packet of variable definition. */
14291 getpkt (&rs->buf, &rs->buf_size, 0);
14297 /* The "set/show range-stepping" show hook. */
14300 show_range_stepping (struct ui_file *file, int from_tty,
14301 struct cmd_list_element *c,
14304 fprintf_filtered (file,
14305 _("Debugger's willingness to use range stepping "
14306 "is %s.\n"), value);
14309 /* Return true if the vCont;r action is supported by the remote
14313 remote_target::vcont_r_supported ()
14315 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
14316 remote_vcont_probe ();
14318 return (packet_support (PACKET_vCont) == PACKET_ENABLE
14319 && get_remote_state ()->supports_vCont.r);
14322 /* The "set/show range-stepping" set hook. */
14325 set_range_stepping (const char *ignore_args, int from_tty,
14326 struct cmd_list_element *c)
14328 /* When enabling, check whether range stepping is actually supported
14329 by the target, and warn if not. */
14330 if (use_range_stepping)
14332 remote_target *remote = get_current_remote_target ();
14334 || !remote->vcont_r_supported ())
14335 warning (_("Range stepping is not supported by the current target"));
14340 _initialize_remote (void)
14342 struct cmd_list_element *cmd;
14343 const char *cmd_name;
14345 /* architecture specific data */
14346 remote_g_packet_data_handle =
14347 gdbarch_data_register_pre_init (remote_g_packet_data_init);
14350 = register_program_space_data_with_cleanup (NULL,
14351 remote_pspace_data_cleanup);
14353 add_target (remote_target_info, remote_target::open);
14354 add_target (extended_remote_target_info, extended_remote_target::open);
14356 /* Hook into new objfile notification. */
14357 gdb::observers::new_objfile.attach (remote_new_objfile);
14360 init_remote_threadtests ();
14363 /* set/show remote ... */
14365 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
14366 Remote protocol specific variables\n\
14367 Configure various remote-protocol specific variables such as\n\
14368 the packets being used"),
14369 &remote_set_cmdlist, "set remote ",
14370 0 /* allow-unknown */, &setlist);
14371 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
14372 Remote protocol specific variables\n\
14373 Configure various remote-protocol specific variables such as\n\
14374 the packets being used"),
14375 &remote_show_cmdlist, "show remote ",
14376 0 /* allow-unknown */, &showlist);
14378 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
14379 Compare section data on target to the exec file.\n\
14380 Argument is a single section name (default: all loaded sections).\n\
14381 To compare only read-only loaded sections, specify the -r option."),
14384 add_cmd ("packet", class_maintenance, packet_command, _("\
14385 Send an arbitrary packet to a remote target.\n\
14386 maintenance packet TEXT\n\
14387 If GDB is talking to an inferior via the GDB serial protocol, then\n\
14388 this command sends the string TEXT to the inferior, and displays the\n\
14389 response packet. GDB supplies the initial `$' character, and the\n\
14390 terminating `#' character and checksum."),
14393 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
14394 Set whether to send break if interrupted."), _("\
14395 Show whether to send break if interrupted."), _("\
14396 If set, a break, instead of a cntrl-c, is sent to the remote target."),
14397 set_remotebreak, show_remotebreak,
14398 &setlist, &showlist);
14399 cmd_name = "remotebreak";
14400 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
14401 deprecate_cmd (cmd, "set remote interrupt-sequence");
14402 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
14403 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
14404 deprecate_cmd (cmd, "show remote interrupt-sequence");
14406 add_setshow_enum_cmd ("interrupt-sequence", class_support,
14407 interrupt_sequence_modes, &interrupt_sequence_mode,
14409 Set interrupt sequence to remote target."), _("\
14410 Show interrupt sequence to remote target."), _("\
14411 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
14412 NULL, show_interrupt_sequence,
14413 &remote_set_cmdlist,
14414 &remote_show_cmdlist);
14416 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
14417 &interrupt_on_connect, _("\
14418 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
14419 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
14420 If set, interrupt sequence is sent to remote target."),
14422 &remote_set_cmdlist, &remote_show_cmdlist);
14424 /* Install commands for configuring memory read/write packets. */
14426 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
14427 Set the maximum number of bytes per memory write packet (deprecated)."),
14429 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
14430 Show the maximum number of bytes per memory write packet (deprecated)."),
14432 add_cmd ("memory-write-packet-size", no_class,
14433 set_memory_write_packet_size, _("\
14434 Set the maximum number of bytes per memory-write packet.\n\
14435 Specify the number of bytes in a packet or 0 (zero) for the\n\
14436 default packet size. The actual limit is further reduced\n\
14437 dependent on the target. Specify ``fixed'' to disable the\n\
14438 further restriction and ``limit'' to enable that restriction."),
14439 &remote_set_cmdlist);
14440 add_cmd ("memory-read-packet-size", no_class,
14441 set_memory_read_packet_size, _("\
14442 Set the maximum number of bytes per memory-read packet.\n\
14443 Specify the number of bytes in a packet or 0 (zero) for the\n\
14444 default packet size. The actual limit is further reduced\n\
14445 dependent on the target. Specify ``fixed'' to disable the\n\
14446 further restriction and ``limit'' to enable that restriction."),
14447 &remote_set_cmdlist);
14448 add_cmd ("memory-write-packet-size", no_class,
14449 show_memory_write_packet_size,
14450 _("Show the maximum number of bytes per memory-write packet."),
14451 &remote_show_cmdlist);
14452 add_cmd ("memory-read-packet-size", no_class,
14453 show_memory_read_packet_size,
14454 _("Show the maximum number of bytes per memory-read packet."),
14455 &remote_show_cmdlist);
14457 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-limit", no_class,
14458 &remote_hw_watchpoint_limit, _("\
14459 Set the maximum number of target hardware watchpoints."), _("\
14460 Show the maximum number of target hardware watchpoints."), _("\
14461 Specify \"unlimited\" for unlimited hardware watchpoints."),
14462 NULL, show_hardware_watchpoint_limit,
14463 &remote_set_cmdlist,
14464 &remote_show_cmdlist);
14465 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-length-limit",
14467 &remote_hw_watchpoint_length_limit, _("\
14468 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
14469 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
14470 Specify \"unlimited\" to allow watchpoints of unlimited size."),
14471 NULL, show_hardware_watchpoint_length_limit,
14472 &remote_set_cmdlist, &remote_show_cmdlist);
14473 add_setshow_zuinteger_unlimited_cmd ("hardware-breakpoint-limit", no_class,
14474 &remote_hw_breakpoint_limit, _("\
14475 Set the maximum number of target hardware breakpoints."), _("\
14476 Show the maximum number of target hardware breakpoints."), _("\
14477 Specify \"unlimited\" for unlimited hardware breakpoints."),
14478 NULL, show_hardware_breakpoint_limit,
14479 &remote_set_cmdlist, &remote_show_cmdlist);
14481 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
14482 &remote_address_size, _("\
14483 Set the maximum size of the address (in bits) in a memory packet."), _("\
14484 Show the maximum size of the address (in bits) in a memory packet."), NULL,
14486 NULL, /* FIXME: i18n: */
14487 &setlist, &showlist);
14489 init_all_packet_configs ();
14491 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
14492 "X", "binary-download", 1);
14494 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
14495 "vCont", "verbose-resume", 0);
14497 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
14498 "QPassSignals", "pass-signals", 0);
14500 add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
14501 "QCatchSyscalls", "catch-syscalls", 0);
14503 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
14504 "QProgramSignals", "program-signals", 0);
14506 add_packet_config_cmd (&remote_protocol_packets[PACKET_QSetWorkingDir],
14507 "QSetWorkingDir", "set-working-dir", 0);
14509 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartupWithShell],
14510 "QStartupWithShell", "startup-with-shell", 0);
14512 add_packet_config_cmd (&remote_protocol_packets
14513 [PACKET_QEnvironmentHexEncoded],
14514 "QEnvironmentHexEncoded", "environment-hex-encoded",
14517 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentReset],
14518 "QEnvironmentReset", "environment-reset",
14521 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentUnset],
14522 "QEnvironmentUnset", "environment-unset",
14525 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
14526 "qSymbol", "symbol-lookup", 0);
14528 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
14529 "P", "set-register", 1);
14531 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
14532 "p", "fetch-register", 1);
14534 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
14535 "Z0", "software-breakpoint", 0);
14537 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
14538 "Z1", "hardware-breakpoint", 0);
14540 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
14541 "Z2", "write-watchpoint", 0);
14543 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
14544 "Z3", "read-watchpoint", 0);
14546 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
14547 "Z4", "access-watchpoint", 0);
14549 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
14550 "qXfer:auxv:read", "read-aux-vector", 0);
14552 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
14553 "qXfer:exec-file:read", "pid-to-exec-file", 0);
14555 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
14556 "qXfer:features:read", "target-features", 0);
14558 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
14559 "qXfer:libraries:read", "library-info", 0);
14561 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
14562 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
14564 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
14565 "qXfer:memory-map:read", "memory-map", 0);
14567 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
14568 "qXfer:spu:read", "read-spu-object", 0);
14570 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
14571 "qXfer:spu:write", "write-spu-object", 0);
14573 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
14574 "qXfer:osdata:read", "osdata", 0);
14576 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
14577 "qXfer:threads:read", "threads", 0);
14579 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
14580 "qXfer:siginfo:read", "read-siginfo-object", 0);
14582 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
14583 "qXfer:siginfo:write", "write-siginfo-object", 0);
14585 add_packet_config_cmd
14586 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
14587 "qXfer:traceframe-info:read", "traceframe-info", 0);
14589 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
14590 "qXfer:uib:read", "unwind-info-block", 0);
14592 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
14593 "qGetTLSAddr", "get-thread-local-storage-address",
14596 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
14597 "qGetTIBAddr", "get-thread-information-block-address",
14600 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
14601 "bc", "reverse-continue", 0);
14603 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
14604 "bs", "reverse-step", 0);
14606 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
14607 "qSupported", "supported-packets", 0);
14609 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
14610 "qSearch:memory", "search-memory", 0);
14612 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
14613 "qTStatus", "trace-status", 0);
14615 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
14616 "vFile:setfs", "hostio-setfs", 0);
14618 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
14619 "vFile:open", "hostio-open", 0);
14621 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
14622 "vFile:pread", "hostio-pread", 0);
14624 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
14625 "vFile:pwrite", "hostio-pwrite", 0);
14627 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
14628 "vFile:close", "hostio-close", 0);
14630 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
14631 "vFile:unlink", "hostio-unlink", 0);
14633 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
14634 "vFile:readlink", "hostio-readlink", 0);
14636 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
14637 "vFile:fstat", "hostio-fstat", 0);
14639 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
14640 "vAttach", "attach", 0);
14642 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
14645 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
14646 "QStartNoAckMode", "noack", 0);
14648 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
14649 "vKill", "kill", 0);
14651 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
14652 "qAttached", "query-attached", 0);
14654 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
14655 "ConditionalTracepoints",
14656 "conditional-tracepoints", 0);
14658 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
14659 "ConditionalBreakpoints",
14660 "conditional-breakpoints", 0);
14662 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
14663 "BreakpointCommands",
14664 "breakpoint-commands", 0);
14666 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
14667 "FastTracepoints", "fast-tracepoints", 0);
14669 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
14670 "TracepointSource", "TracepointSource", 0);
14672 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
14673 "QAllow", "allow", 0);
14675 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
14676 "StaticTracepoints", "static-tracepoints", 0);
14678 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
14679 "InstallInTrace", "install-in-trace", 0);
14681 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
14682 "qXfer:statictrace:read", "read-sdata-object", 0);
14684 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
14685 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
14687 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
14688 "QDisableRandomization", "disable-randomization", 0);
14690 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
14691 "QAgent", "agent", 0);
14693 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
14694 "QTBuffer:size", "trace-buffer-size", 0);
14696 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
14697 "Qbtrace:off", "disable-btrace", 0);
14699 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
14700 "Qbtrace:bts", "enable-btrace-bts", 0);
14702 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
14703 "Qbtrace:pt", "enable-btrace-pt", 0);
14705 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
14706 "qXfer:btrace", "read-btrace", 0);
14708 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
14709 "qXfer:btrace-conf", "read-btrace-conf", 0);
14711 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
14712 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
14714 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
14715 "multiprocess-feature", "multiprocess-feature", 0);
14717 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
14718 "swbreak-feature", "swbreak-feature", 0);
14720 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
14721 "hwbreak-feature", "hwbreak-feature", 0);
14723 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
14724 "fork-event-feature", "fork-event-feature", 0);
14726 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
14727 "vfork-event-feature", "vfork-event-feature", 0);
14729 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
14730 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
14732 add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
14733 "vContSupported", "verbose-resume-supported", 0);
14735 add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
14736 "exec-event-feature", "exec-event-feature", 0);
14738 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
14739 "vCtrlC", "ctrl-c", 0);
14741 add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
14742 "QThreadEvents", "thread-events", 0);
14744 add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
14745 "N stop reply", "no-resumed-stop-reply", 0);
14747 /* Assert that we've registered "set remote foo-packet" commands
14748 for all packet configs. */
14752 for (i = 0; i < PACKET_MAX; i++)
14754 /* Ideally all configs would have a command associated. Some
14755 still don't though. */
14760 case PACKET_QNonStop:
14761 case PACKET_EnableDisableTracepoints_feature:
14762 case PACKET_tracenz_feature:
14763 case PACKET_DisconnectedTracing_feature:
14764 case PACKET_augmented_libraries_svr4_read_feature:
14766 /* Additions to this list need to be well justified:
14767 pre-existing packets are OK; new packets are not. */
14775 /* This catches both forgetting to add a config command, and
14776 forgetting to remove a packet from the exception list. */
14777 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
14781 /* Keep the old ``set remote Z-packet ...'' working. Each individual
14782 Z sub-packet has its own set and show commands, but users may
14783 have sets to this variable in their .gdbinit files (or in their
14785 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
14786 &remote_Z_packet_detect, _("\
14787 Set use of remote protocol `Z' packets"), _("\
14788 Show use of remote protocol `Z' packets "), _("\
14789 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
14791 set_remote_protocol_Z_packet_cmd,
14792 show_remote_protocol_Z_packet_cmd,
14793 /* FIXME: i18n: Use of remote protocol
14794 `Z' packets is %s. */
14795 &remote_set_cmdlist, &remote_show_cmdlist);
14797 add_prefix_cmd ("remote", class_files, remote_command, _("\
14798 Manipulate files on the remote system\n\
14799 Transfer files to and from the remote target system."),
14800 &remote_cmdlist, "remote ",
14801 0 /* allow-unknown */, &cmdlist);
14803 add_cmd ("put", class_files, remote_put_command,
14804 _("Copy a local file to the remote system."),
14807 add_cmd ("get", class_files, remote_get_command,
14808 _("Copy a remote file to the local system."),
14811 add_cmd ("delete", class_files, remote_delete_command,
14812 _("Delete a remote file."),
14815 add_setshow_string_noescape_cmd ("exec-file", class_files,
14816 &remote_exec_file_var, _("\
14817 Set the remote pathname for \"run\""), _("\
14818 Show the remote pathname for \"run\""), NULL,
14819 set_remote_exec_file,
14820 show_remote_exec_file,
14821 &remote_set_cmdlist,
14822 &remote_show_cmdlist);
14824 add_setshow_boolean_cmd ("range-stepping", class_run,
14825 &use_range_stepping, _("\
14826 Enable or disable range stepping."), _("\
14827 Show whether target-assisted range stepping is enabled."), _("\
14828 If on, and the target supports it, when stepping a source line, GDB\n\
14829 tells the target to step the corresponding range of addresses itself instead\n\
14830 of issuing multiple single-steps. This speeds up source level\n\
14831 stepping. If off, GDB always issues single-steps, even if range\n\
14832 stepping is supported by the target. The default is on."),
14833 set_range_stepping,
14834 show_range_stepping,
14838 /* Eventually initialize fileio. See fileio.c */
14839 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
14841 /* Take advantage of the fact that the TID field is not used, to tag
14842 special ptids with it set to != 0. */
14843 magic_null_ptid = ptid_t (42000, -1, 1);
14844 not_sent_ptid = ptid_t (42000, -2, 1);
14845 any_thread_ptid = ptid_t (42000, 0, 1);