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);
1732 remote_target::get_memory_write_packet_size ()
1734 return get_memory_packet_size (&memory_write_packet_config);
1737 static struct memory_packet_config memory_read_packet_config =
1739 "memory-read-packet-size",
1743 set_memory_read_packet_size (const char *args, int from_tty)
1745 set_memory_packet_size (args, &memory_read_packet_config);
1749 show_memory_read_packet_size (const char *args, int from_tty)
1751 show_memory_packet_size (&memory_read_packet_config);
1755 remote_target::get_memory_read_packet_size ()
1757 long size = get_memory_packet_size (&memory_read_packet_config);
1759 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1760 extra buffer size argument before the memory read size can be
1761 increased beyond this. */
1762 if (size > get_remote_packet_size ())
1763 size = get_remote_packet_size ();
1769 struct packet_config
1774 /* If auto, GDB auto-detects support for this packet or feature,
1775 either through qSupported, or by trying the packet and looking
1776 at the response. If true, GDB assumes the target supports this
1777 packet. If false, the packet is disabled. Configs that don't
1778 have an associated command always have this set to auto. */
1779 enum auto_boolean detect;
1781 /* Does the target support this packet? */
1782 enum packet_support support;
1785 static enum packet_support packet_config_support (struct packet_config *config);
1786 static enum packet_support packet_support (int packet);
1789 show_packet_config_cmd (struct packet_config *config)
1791 const char *support = "internal-error";
1793 switch (packet_config_support (config))
1796 support = "enabled";
1798 case PACKET_DISABLE:
1799 support = "disabled";
1801 case PACKET_SUPPORT_UNKNOWN:
1802 support = "unknown";
1805 switch (config->detect)
1807 case AUTO_BOOLEAN_AUTO:
1808 printf_filtered (_("Support for the `%s' packet "
1809 "is auto-detected, currently %s.\n"),
1810 config->name, support);
1812 case AUTO_BOOLEAN_TRUE:
1813 case AUTO_BOOLEAN_FALSE:
1814 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1815 config->name, support);
1821 add_packet_config_cmd (struct packet_config *config, const char *name,
1822 const char *title, int legacy)
1828 config->name = name;
1829 config->title = title;
1830 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1832 show_doc = xstrprintf ("Show current use of remote "
1833 "protocol `%s' (%s) packet",
1835 /* set/show TITLE-packet {auto,on,off} */
1836 cmd_name = xstrprintf ("%s-packet", title);
1837 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
1838 &config->detect, set_doc,
1839 show_doc, NULL, /* help_doc */
1841 show_remote_protocol_packet_cmd,
1842 &remote_set_cmdlist, &remote_show_cmdlist);
1843 /* The command code copies the documentation strings. */
1846 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
1851 legacy_name = xstrprintf ("%s-packet", name);
1852 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1853 &remote_set_cmdlist);
1854 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1855 &remote_show_cmdlist);
1859 static enum packet_result
1860 packet_check_result (const char *buf)
1864 /* The stub recognized the packet request. Check that the
1865 operation succeeded. */
1867 && isxdigit (buf[1]) && isxdigit (buf[2])
1869 /* "Enn" - definitly an error. */
1870 return PACKET_ERROR;
1872 /* Always treat "E." as an error. This will be used for
1873 more verbose error messages, such as E.memtypes. */
1874 if (buf[0] == 'E' && buf[1] == '.')
1875 return PACKET_ERROR;
1877 /* The packet may or may not be OK. Just assume it is. */
1881 /* The stub does not support the packet. */
1882 return PACKET_UNKNOWN;
1885 static enum packet_result
1886 packet_ok (const char *buf, struct packet_config *config)
1888 enum packet_result result;
1890 if (config->detect != AUTO_BOOLEAN_TRUE
1891 && config->support == PACKET_DISABLE)
1892 internal_error (__FILE__, __LINE__,
1893 _("packet_ok: attempt to use a disabled packet"));
1895 result = packet_check_result (buf);
1900 /* The stub recognized the packet request. */
1901 if (config->support == PACKET_SUPPORT_UNKNOWN)
1904 fprintf_unfiltered (gdb_stdlog,
1905 "Packet %s (%s) is supported\n",
1906 config->name, config->title);
1907 config->support = PACKET_ENABLE;
1910 case PACKET_UNKNOWN:
1911 /* The stub does not support the packet. */
1912 if (config->detect == AUTO_BOOLEAN_AUTO
1913 && config->support == PACKET_ENABLE)
1915 /* If the stub previously indicated that the packet was
1916 supported then there is a protocol error. */
1917 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1918 config->name, config->title);
1920 else if (config->detect == AUTO_BOOLEAN_TRUE)
1922 /* The user set it wrong. */
1923 error (_("Enabled packet %s (%s) not recognized by stub"),
1924 config->name, config->title);
1928 fprintf_unfiltered (gdb_stdlog,
1929 "Packet %s (%s) is NOT supported\n",
1930 config->name, config->title);
1931 config->support = PACKET_DISABLE;
1952 PACKET_vFile_pwrite,
1954 PACKET_vFile_unlink,
1955 PACKET_vFile_readlink,
1958 PACKET_qXfer_features,
1959 PACKET_qXfer_exec_file,
1960 PACKET_qXfer_libraries,
1961 PACKET_qXfer_libraries_svr4,
1962 PACKET_qXfer_memory_map,
1963 PACKET_qXfer_spu_read,
1964 PACKET_qXfer_spu_write,
1965 PACKET_qXfer_osdata,
1966 PACKET_qXfer_threads,
1967 PACKET_qXfer_statictrace_read,
1968 PACKET_qXfer_traceframe_info,
1974 PACKET_QPassSignals,
1975 PACKET_QCatchSyscalls,
1976 PACKET_QProgramSignals,
1977 PACKET_QSetWorkingDir,
1978 PACKET_QStartupWithShell,
1979 PACKET_QEnvironmentHexEncoded,
1980 PACKET_QEnvironmentReset,
1981 PACKET_QEnvironmentUnset,
1983 PACKET_qSearch_memory,
1986 PACKET_QStartNoAckMode,
1988 PACKET_qXfer_siginfo_read,
1989 PACKET_qXfer_siginfo_write,
1992 /* Support for conditional tracepoints. */
1993 PACKET_ConditionalTracepoints,
1995 /* Support for target-side breakpoint conditions. */
1996 PACKET_ConditionalBreakpoints,
1998 /* Support for target-side breakpoint commands. */
1999 PACKET_BreakpointCommands,
2001 /* Support for fast tracepoints. */
2002 PACKET_FastTracepoints,
2004 /* Support for static tracepoints. */
2005 PACKET_StaticTracepoints,
2007 /* Support for installing tracepoints while a trace experiment is
2009 PACKET_InstallInTrace,
2013 PACKET_TracepointSource,
2016 PACKET_QDisableRandomization,
2018 PACKET_QTBuffer_size,
2022 PACKET_qXfer_btrace,
2024 /* Support for the QNonStop packet. */
2027 /* Support for the QThreadEvents packet. */
2028 PACKET_QThreadEvents,
2030 /* Support for multi-process extensions. */
2031 PACKET_multiprocess_feature,
2033 /* Support for enabling and disabling tracepoints while a trace
2034 experiment is running. */
2035 PACKET_EnableDisableTracepoints_feature,
2037 /* Support for collecting strings using the tracenz bytecode. */
2038 PACKET_tracenz_feature,
2040 /* Support for continuing to run a trace experiment while GDB is
2042 PACKET_DisconnectedTracing_feature,
2044 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
2045 PACKET_augmented_libraries_svr4_read_feature,
2047 /* Support for the qXfer:btrace-conf:read packet. */
2048 PACKET_qXfer_btrace_conf,
2050 /* Support for the Qbtrace-conf:bts:size packet. */
2051 PACKET_Qbtrace_conf_bts_size,
2053 /* Support for swbreak+ feature. */
2054 PACKET_swbreak_feature,
2056 /* Support for hwbreak+ feature. */
2057 PACKET_hwbreak_feature,
2059 /* Support for fork events. */
2060 PACKET_fork_event_feature,
2062 /* Support for vfork events. */
2063 PACKET_vfork_event_feature,
2065 /* Support for the Qbtrace-conf:pt:size packet. */
2066 PACKET_Qbtrace_conf_pt_size,
2068 /* Support for exec events. */
2069 PACKET_exec_event_feature,
2071 /* Support for query supported vCont actions. */
2072 PACKET_vContSupported,
2074 /* Support remote CTRL-C. */
2077 /* Support TARGET_WAITKIND_NO_RESUMED. */
2083 static struct packet_config remote_protocol_packets[PACKET_MAX];
2085 /* Returns the packet's corresponding "set remote foo-packet" command
2086 state. See struct packet_config for more details. */
2088 static enum auto_boolean
2089 packet_set_cmd_state (int packet)
2091 return remote_protocol_packets[packet].detect;
2094 /* Returns whether a given packet or feature is supported. This takes
2095 into account the state of the corresponding "set remote foo-packet"
2096 command, which may be used to bypass auto-detection. */
2098 static enum packet_support
2099 packet_config_support (struct packet_config *config)
2101 switch (config->detect)
2103 case AUTO_BOOLEAN_TRUE:
2104 return PACKET_ENABLE;
2105 case AUTO_BOOLEAN_FALSE:
2106 return PACKET_DISABLE;
2107 case AUTO_BOOLEAN_AUTO:
2108 return config->support;
2110 gdb_assert_not_reached (_("bad switch"));
2114 /* Same as packet_config_support, but takes the packet's enum value as
2117 static enum packet_support
2118 packet_support (int packet)
2120 struct packet_config *config = &remote_protocol_packets[packet];
2122 return packet_config_support (config);
2126 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
2127 struct cmd_list_element *c,
2130 struct packet_config *packet;
2132 for (packet = remote_protocol_packets;
2133 packet < &remote_protocol_packets[PACKET_MAX];
2136 if (&packet->detect == c->var)
2138 show_packet_config_cmd (packet);
2142 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
2146 /* Should we try one of the 'Z' requests? */
2150 Z_PACKET_SOFTWARE_BP,
2151 Z_PACKET_HARDWARE_BP,
2158 /* For compatibility with older distributions. Provide a ``set remote
2159 Z-packet ...'' command that updates all the Z packet types. */
2161 static enum auto_boolean remote_Z_packet_detect;
2164 set_remote_protocol_Z_packet_cmd (const char *args, int from_tty,
2165 struct cmd_list_element *c)
2169 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2170 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
2174 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
2175 struct cmd_list_element *c,
2180 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2182 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
2186 /* Returns true if the multi-process extensions are in effect. */
2189 remote_multi_process_p (struct remote_state *rs)
2191 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
2194 /* Returns true if fork events are supported. */
2197 remote_fork_event_p (struct remote_state *rs)
2199 return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
2202 /* Returns true if vfork events are supported. */
2205 remote_vfork_event_p (struct remote_state *rs)
2207 return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
2210 /* Returns true if exec events are supported. */
2213 remote_exec_event_p (struct remote_state *rs)
2215 return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
2218 /* Insert fork catchpoint target routine. If fork events are enabled
2219 then return success, nothing more to do. */
2222 remote_target::insert_fork_catchpoint (int pid)
2224 struct remote_state *rs = get_remote_state ();
2226 return !remote_fork_event_p (rs);
2229 /* Remove fork catchpoint target routine. Nothing to do, just
2233 remote_target::remove_fork_catchpoint (int pid)
2238 /* Insert vfork catchpoint target routine. If vfork events are enabled
2239 then return success, nothing more to do. */
2242 remote_target::insert_vfork_catchpoint (int pid)
2244 struct remote_state *rs = get_remote_state ();
2246 return !remote_vfork_event_p (rs);
2249 /* Remove vfork catchpoint target routine. Nothing to do, just
2253 remote_target::remove_vfork_catchpoint (int pid)
2258 /* Insert exec catchpoint target routine. If exec events are
2259 enabled, just return success. */
2262 remote_target::insert_exec_catchpoint (int pid)
2264 struct remote_state *rs = get_remote_state ();
2266 return !remote_exec_event_p (rs);
2269 /* Remove exec catchpoint target routine. Nothing to do, just
2273 remote_target::remove_exec_catchpoint (int pid)
2280 static ptid_t magic_null_ptid;
2281 static ptid_t not_sent_ptid;
2282 static ptid_t any_thread_ptid;
2284 /* Find out if the stub attached to PID (and hence GDB should offer to
2285 detach instead of killing it when bailing out). */
2288 remote_target::remote_query_attached (int pid)
2290 struct remote_state *rs = get_remote_state ();
2291 size_t size = get_remote_packet_size ();
2293 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
2296 if (remote_multi_process_p (rs))
2297 xsnprintf (rs->buf, size, "qAttached:%x", pid);
2299 xsnprintf (rs->buf, size, "qAttached");
2302 getpkt (&rs->buf, &rs->buf_size, 0);
2304 switch (packet_ok (rs->buf,
2305 &remote_protocol_packets[PACKET_qAttached]))
2308 if (strcmp (rs->buf, "1") == 0)
2312 warning (_("Remote failure reply: %s"), rs->buf);
2314 case PACKET_UNKNOWN:
2321 /* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
2322 has been invented by GDB, instead of reported by the target. Since
2323 we can be connected to a remote system before before knowing about
2324 any inferior, mark the target with execution when we find the first
2325 inferior. If ATTACHED is 1, then we had just attached to this
2326 inferior. If it is 0, then we just created this inferior. If it
2327 is -1, then try querying the remote stub to find out if it had
2328 attached to the inferior or not. If TRY_OPEN_EXEC is true then
2329 attempt to open this inferior's executable as the main executable
2330 if no main executable is open already. */
2333 remote_target::remote_add_inferior (int fake_pid_p, int pid, int attached,
2336 struct inferior *inf;
2338 /* Check whether this process we're learning about is to be
2339 considered attached, or if is to be considered to have been
2340 spawned by the stub. */
2342 attached = remote_query_attached (pid);
2344 if (gdbarch_has_global_solist (target_gdbarch ()))
2346 /* If the target shares code across all inferiors, then every
2347 attach adds a new inferior. */
2348 inf = add_inferior (pid);
2350 /* ... and every inferior is bound to the same program space.
2351 However, each inferior may still have its own address
2353 inf->aspace = maybe_new_address_space ();
2354 inf->pspace = current_program_space;
2358 /* In the traditional debugging scenario, there's a 1-1 match
2359 between program/address spaces. We simply bind the inferior
2360 to the program space's address space. */
2361 inf = current_inferior ();
2362 inferior_appeared (inf, pid);
2365 inf->attach_flag = attached;
2366 inf->fake_pid_p = fake_pid_p;
2368 /* If no main executable is currently open then attempt to
2369 open the file that was executed to create this inferior. */
2370 if (try_open_exec && get_exec_file (0) == NULL)
2371 exec_file_locate_attach (pid, 0, 1);
2376 static remote_thread_info *get_remote_thread_info (thread_info *thread);
2377 static remote_thread_info *get_remote_thread_info (ptid_t ptid);
2379 /* Add thread PTID to GDB's thread list. Tag it as executing/running
2380 according to RUNNING. */
2383 remote_target::remote_add_thread (ptid_t ptid, bool running, bool executing)
2385 struct remote_state *rs = get_remote_state ();
2386 struct thread_info *thread;
2388 /* GDB historically didn't pull threads in the initial connection
2389 setup. If the remote target doesn't even have a concept of
2390 threads (e.g., a bare-metal target), even if internally we
2391 consider that a single-threaded target, mentioning a new thread
2392 might be confusing to the user. Be silent then, preserving the
2393 age old behavior. */
2394 if (rs->starting_up)
2395 thread = add_thread_silent (ptid);
2397 thread = add_thread (ptid);
2399 get_remote_thread_info (thread)->vcont_resumed = executing;
2400 set_executing (ptid, executing);
2401 set_running (ptid, running);
2406 /* Come here when we learn about a thread id from the remote target.
2407 It may be the first time we hear about such thread, so take the
2408 opportunity to add it to GDB's thread list. In case this is the
2409 first time we're noticing its corresponding inferior, add it to
2410 GDB's inferior list as well. EXECUTING indicates whether the
2411 thread is (internally) executing or stopped. */
2414 remote_target::remote_notice_new_inferior (ptid_t currthread, int executing)
2416 /* In non-stop mode, we assume new found threads are (externally)
2417 running until proven otherwise with a stop reply. In all-stop,
2418 we can only get here if all threads are stopped. */
2419 int running = target_is_non_stop_p () ? 1 : 0;
2421 /* If this is a new thread, add it to GDB's thread list.
2422 If we leave it up to WFI to do this, bad things will happen. */
2424 thread_info *tp = find_thread_ptid (currthread);
2425 if (tp != NULL && tp->state == THREAD_EXITED)
2427 /* We're seeing an event on a thread id we knew had exited.
2428 This has to be a new thread reusing the old id. Add it. */
2429 remote_add_thread (currthread, running, executing);
2433 if (!in_thread_list (currthread))
2435 struct inferior *inf = NULL;
2436 int pid = currthread.pid ();
2438 if (inferior_ptid.is_pid ()
2439 && pid == inferior_ptid.pid ())
2441 /* inferior_ptid has no thread member yet. This can happen
2442 with the vAttach -> remote_wait,"TAAthread:" path if the
2443 stub doesn't support qC. This is the first stop reported
2444 after an attach, so this is the main thread. Update the
2445 ptid in the thread list. */
2446 if (in_thread_list (ptid_t (pid)))
2447 thread_change_ptid (inferior_ptid, currthread);
2450 remote_add_thread (currthread, running, executing);
2451 inferior_ptid = currthread;
2456 if (magic_null_ptid == inferior_ptid)
2458 /* inferior_ptid is not set yet. This can happen with the
2459 vRun -> remote_wait,"TAAthread:" path if the stub
2460 doesn't support qC. This is the first stop reported
2461 after an attach, so this is the main thread. Update the
2462 ptid in the thread list. */
2463 thread_change_ptid (inferior_ptid, currthread);
2467 /* When connecting to a target remote, or to a target
2468 extended-remote which already was debugging an inferior, we
2469 may not know about it yet. Add it before adding its child
2470 thread, so notifications are emitted in a sensible order. */
2471 if (find_inferior_pid (currthread.pid ()) == NULL)
2473 struct remote_state *rs = get_remote_state ();
2474 int fake_pid_p = !remote_multi_process_p (rs);
2476 inf = remote_add_inferior (fake_pid_p,
2477 currthread.pid (), -1, 1);
2480 /* This is really a new thread. Add it. */
2481 thread_info *new_thr
2482 = remote_add_thread (currthread, running, executing);
2484 /* If we found a new inferior, let the common code do whatever
2485 it needs to with it (e.g., read shared libraries, insert
2486 breakpoints), unless we're just setting up an all-stop
2490 struct remote_state *rs = get_remote_state ();
2492 if (!rs->starting_up)
2493 notice_new_inferior (new_thr, executing, 0);
2498 /* Return THREAD's private thread data, creating it if necessary. */
2500 static remote_thread_info *
2501 get_remote_thread_info (thread_info *thread)
2503 gdb_assert (thread != NULL);
2505 if (thread->priv == NULL)
2506 thread->priv.reset (new remote_thread_info);
2508 return static_cast<remote_thread_info *> (thread->priv.get ());
2511 static remote_thread_info *
2512 get_remote_thread_info (ptid_t ptid)
2514 thread_info *thr = find_thread_ptid (ptid);
2515 return get_remote_thread_info (thr);
2518 /* Call this function as a result of
2519 1) A halt indication (T packet) containing a thread id
2520 2) A direct query of currthread
2521 3) Successful execution of set thread */
2524 record_currthread (struct remote_state *rs, ptid_t currthread)
2526 rs->general_thread = currthread;
2529 /* If 'QPassSignals' is supported, tell the remote stub what signals
2530 it can simply pass through to the inferior without reporting. */
2533 remote_target::pass_signals (int numsigs, unsigned char *pass_signals)
2535 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
2537 char *pass_packet, *p;
2539 struct remote_state *rs = get_remote_state ();
2541 gdb_assert (numsigs < 256);
2542 for (i = 0; i < numsigs; i++)
2544 if (pass_signals[i])
2547 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
2548 strcpy (pass_packet, "QPassSignals:");
2549 p = pass_packet + strlen (pass_packet);
2550 for (i = 0; i < numsigs; i++)
2552 if (pass_signals[i])
2555 *p++ = tohex (i >> 4);
2556 *p++ = tohex (i & 15);
2565 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
2567 putpkt (pass_packet);
2568 getpkt (&rs->buf, &rs->buf_size, 0);
2569 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
2570 if (rs->last_pass_packet)
2571 xfree (rs->last_pass_packet);
2572 rs->last_pass_packet = pass_packet;
2575 xfree (pass_packet);
2579 /* If 'QCatchSyscalls' is supported, tell the remote stub
2580 to report syscalls to GDB. */
2583 remote_target::set_syscall_catchpoint (int pid, bool needed, int any_count,
2584 gdb::array_view<const int> syscall_counts)
2586 const char *catch_packet;
2587 enum packet_result result;
2590 if (packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2592 /* Not supported. */
2596 if (needed && any_count == 0)
2598 /* Count how many syscalls are to be caught. */
2599 for (size_t i = 0; i < syscall_counts.size (); i++)
2601 if (syscall_counts[i] != 0)
2608 fprintf_unfiltered (gdb_stdlog,
2609 "remote_set_syscall_catchpoint "
2610 "pid %d needed %d any_count %d n_sysno %d\n",
2611 pid, needed, any_count, n_sysno);
2614 std::string built_packet;
2617 /* Prepare a packet with the sysno list, assuming max 8+1
2618 characters for a sysno. If the resulting packet size is too
2619 big, fallback on the non-selective packet. */
2620 const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
2621 built_packet.reserve (maxpktsz);
2622 built_packet = "QCatchSyscalls:1";
2625 /* Add in each syscall to be caught. */
2626 for (size_t i = 0; i < syscall_counts.size (); i++)
2628 if (syscall_counts[i] != 0)
2629 string_appendf (built_packet, ";%zx", i);
2632 if (built_packet.size () > get_remote_packet_size ())
2634 /* catch_packet too big. Fallback to less efficient
2635 non selective mode, with GDB doing the filtering. */
2636 catch_packet = "QCatchSyscalls:1";
2639 catch_packet = built_packet.c_str ();
2642 catch_packet = "QCatchSyscalls:0";
2644 struct remote_state *rs = get_remote_state ();
2646 putpkt (catch_packet);
2647 getpkt (&rs->buf, &rs->buf_size, 0);
2648 result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_QCatchSyscalls]);
2649 if (result == PACKET_OK)
2655 /* If 'QProgramSignals' is supported, tell the remote stub what
2656 signals it should pass through to the inferior when detaching. */
2659 remote_target::program_signals (int numsigs, unsigned char *signals)
2661 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
2665 struct remote_state *rs = get_remote_state ();
2667 gdb_assert (numsigs < 256);
2668 for (i = 0; i < numsigs; i++)
2673 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
2674 strcpy (packet, "QProgramSignals:");
2675 p = packet + strlen (packet);
2676 for (i = 0; i < numsigs; i++)
2678 if (signal_pass_state (i))
2681 *p++ = tohex (i >> 4);
2682 *p++ = tohex (i & 15);
2691 if (!rs->last_program_signals_packet
2692 || strcmp (rs->last_program_signals_packet, packet) != 0)
2695 getpkt (&rs->buf, &rs->buf_size, 0);
2696 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
2697 xfree (rs->last_program_signals_packet);
2698 rs->last_program_signals_packet = packet;
2705 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
2706 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2707 thread. If GEN is set, set the general thread, if not, then set
2708 the step/continue thread. */
2710 remote_target::set_thread (ptid_t ptid, int gen)
2712 struct remote_state *rs = get_remote_state ();
2713 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
2714 char *buf = rs->buf;
2715 char *endbuf = rs->buf + get_remote_packet_size ();
2721 *buf++ = gen ? 'g' : 'c';
2722 if (ptid == magic_null_ptid)
2723 xsnprintf (buf, endbuf - buf, "0");
2724 else if (ptid == any_thread_ptid)
2725 xsnprintf (buf, endbuf - buf, "0");
2726 else if (ptid == minus_one_ptid)
2727 xsnprintf (buf, endbuf - buf, "-1");
2729 write_ptid (buf, endbuf, ptid);
2731 getpkt (&rs->buf, &rs->buf_size, 0);
2733 rs->general_thread = ptid;
2735 rs->continue_thread = ptid;
2739 remote_target::set_general_thread (ptid_t ptid)
2741 set_thread (ptid, 1);
2745 remote_target::set_continue_thread (ptid_t ptid)
2747 set_thread (ptid, 0);
2750 /* Change the remote current process. Which thread within the process
2751 ends up selected isn't important, as long as it is the same process
2752 as what INFERIOR_PTID points to.
2754 This comes from that fact that there is no explicit notion of
2755 "selected process" in the protocol. The selected process for
2756 general operations is the process the selected general thread
2760 remote_target::set_general_process ()
2762 struct remote_state *rs = get_remote_state ();
2764 /* If the remote can't handle multiple processes, don't bother. */
2765 if (!remote_multi_process_p (rs))
2768 /* We only need to change the remote current thread if it's pointing
2769 at some other process. */
2770 if (rs->general_thread.pid () != inferior_ptid.pid ())
2771 set_general_thread (inferior_ptid);
2775 /* Return nonzero if this is the main thread that we made up ourselves
2776 to model non-threaded targets as single-threaded. */
2779 remote_thread_always_alive (ptid_t ptid)
2781 if (ptid == magic_null_ptid)
2782 /* The main thread is always alive. */
2785 if (ptid.pid () != 0 && ptid.lwp () == 0)
2786 /* The main thread is always alive. This can happen after a
2787 vAttach, if the remote side doesn't support
2794 /* Return nonzero if the thread PTID is still alive on the remote
2798 remote_target::thread_alive (ptid_t ptid)
2800 struct remote_state *rs = get_remote_state ();
2803 /* Check if this is a thread that we made up ourselves to model
2804 non-threaded targets as single-threaded. */
2805 if (remote_thread_always_alive (ptid))
2809 endp = rs->buf + get_remote_packet_size ();
2812 write_ptid (p, endp, ptid);
2815 getpkt (&rs->buf, &rs->buf_size, 0);
2816 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
2819 /* Return a pointer to a thread name if we know it and NULL otherwise.
2820 The thread_info object owns the memory for the name. */
2823 remote_target::thread_name (struct thread_info *info)
2825 if (info->priv != NULL)
2827 const std::string &name = get_remote_thread_info (info)->name;
2828 return !name.empty () ? name.c_str () : NULL;
2834 /* About these extended threadlist and threadinfo packets. They are
2835 variable length packets but, the fields within them are often fixed
2836 length. They are redundent enough to send over UDP as is the
2837 remote protocol in general. There is a matching unit test module
2840 /* WARNING: This threadref data structure comes from the remote O.S.,
2841 libstub protocol encoding, and remote.c. It is not particularly
2844 /* Right now, the internal structure is int. We want it to be bigger.
2845 Plan to fix this. */
2847 typedef int gdb_threadref; /* Internal GDB thread reference. */
2849 /* gdb_ext_thread_info is an internal GDB data structure which is
2850 equivalent to the reply of the remote threadinfo packet. */
2852 struct gdb_ext_thread_info
2854 threadref threadid; /* External form of thread reference. */
2855 int active; /* Has state interesting to GDB?
2857 char display[256]; /* Brief state display, name,
2858 blocked/suspended. */
2859 char shortname[32]; /* To be used to name threads. */
2860 char more_display[256]; /* Long info, statistics, queue depth,
2864 /* The volume of remote transfers can be limited by submitting
2865 a mask containing bits specifying the desired information.
2866 Use a union of these values as the 'selection' parameter to
2867 get_thread_info. FIXME: Make these TAG names more thread specific. */
2869 #define TAG_THREADID 1
2870 #define TAG_EXISTS 2
2871 #define TAG_DISPLAY 4
2872 #define TAG_THREADNAME 8
2873 #define TAG_MOREDISPLAY 16
2875 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
2877 static char *unpack_nibble (char *buf, int *val);
2879 static char *unpack_byte (char *buf, int *value);
2881 static char *pack_int (char *buf, int value);
2883 static char *unpack_int (char *buf, int *value);
2885 static char *unpack_string (char *src, char *dest, int length);
2887 static char *pack_threadid (char *pkt, threadref *id);
2889 static char *unpack_threadid (char *inbuf, threadref *id);
2891 void int_to_threadref (threadref *id, int value);
2893 static int threadref_to_int (threadref *ref);
2895 static void copy_threadref (threadref *dest, threadref *src);
2897 static int threadmatch (threadref *dest, threadref *src);
2899 static char *pack_threadinfo_request (char *pkt, int mode,
2902 static char *pack_threadlist_request (char *pkt, int startflag,
2904 threadref *nextthread);
2906 static int remote_newthread_step (threadref *ref, void *context);
2909 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
2910 buffer we're allowed to write to. Returns
2911 BUF+CHARACTERS_WRITTEN. */
2914 remote_target::write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2917 struct remote_state *rs = get_remote_state ();
2919 if (remote_multi_process_p (rs))
2923 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2925 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2929 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2931 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2936 /* Extract a PTID from BUF. If non-null, OBUF is set to one past the
2937 last parsed char. Returns null_ptid if no thread id is found, and
2938 throws an error if the thread id has an invalid format. */
2941 read_ptid (const char *buf, const char **obuf)
2943 const char *p = buf;
2945 ULONGEST pid = 0, tid = 0;
2949 /* Multi-process ptid. */
2950 pp = unpack_varlen_hex (p + 1, &pid);
2952 error (_("invalid remote ptid: %s"), p);
2955 pp = unpack_varlen_hex (p + 1, &tid);
2958 return ptid_t (pid, tid, 0);
2961 /* No multi-process. Just a tid. */
2962 pp = unpack_varlen_hex (p, &tid);
2964 /* Return null_ptid when no thread id is found. */
2972 /* Since the stub is not sending a process id, then default to
2973 what's in inferior_ptid, unless it's null at this point. If so,
2974 then since there's no way to know the pid of the reported
2975 threads, use the magic number. */
2976 if (inferior_ptid == null_ptid)
2977 pid = magic_null_ptid.pid ();
2979 pid = inferior_ptid.pid ();
2983 return ptid_t (pid, tid, 0);
2989 if (ch >= 'a' && ch <= 'f')
2990 return ch - 'a' + 10;
2991 if (ch >= '0' && ch <= '9')
2993 if (ch >= 'A' && ch <= 'F')
2994 return ch - 'A' + 10;
2999 stub_unpack_int (char *buff, int fieldlength)
3006 nibble = stubhex (*buff++);
3010 retval = retval << 4;
3016 unpack_nibble (char *buf, int *val)
3018 *val = fromhex (*buf++);
3023 unpack_byte (char *buf, int *value)
3025 *value = stub_unpack_int (buf, 2);
3030 pack_int (char *buf, int value)
3032 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
3033 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
3034 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
3035 buf = pack_hex_byte (buf, (value & 0xff));
3040 unpack_int (char *buf, int *value)
3042 *value = stub_unpack_int (buf, 8);
3046 #if 0 /* Currently unused, uncomment when needed. */
3047 static char *pack_string (char *pkt, char *string);
3050 pack_string (char *pkt, char *string)
3055 len = strlen (string);
3057 len = 200; /* Bigger than most GDB packets, junk??? */
3058 pkt = pack_hex_byte (pkt, len);
3062 if ((ch == '\0') || (ch == '#'))
3063 ch = '*'; /* Protect encapsulation. */
3068 #endif /* 0 (unused) */
3071 unpack_string (char *src, char *dest, int length)
3080 pack_threadid (char *pkt, threadref *id)
3083 unsigned char *altid;
3085 altid = (unsigned char *) id;
3086 limit = pkt + BUF_THREAD_ID_SIZE;
3088 pkt = pack_hex_byte (pkt, *altid++);
3094 unpack_threadid (char *inbuf, threadref *id)
3097 char *limit = inbuf + BUF_THREAD_ID_SIZE;
3100 altref = (char *) id;
3102 while (inbuf < limit)
3104 x = stubhex (*inbuf++);
3105 y = stubhex (*inbuf++);
3106 *altref++ = (x << 4) | y;
3111 /* Externally, threadrefs are 64 bits but internally, they are still
3112 ints. This is due to a mismatch of specifications. We would like
3113 to use 64bit thread references internally. This is an adapter
3117 int_to_threadref (threadref *id, int value)
3119 unsigned char *scan;
3121 scan = (unsigned char *) id;
3127 *scan++ = (value >> 24) & 0xff;
3128 *scan++ = (value >> 16) & 0xff;
3129 *scan++ = (value >> 8) & 0xff;
3130 *scan++ = (value & 0xff);
3134 threadref_to_int (threadref *ref)
3137 unsigned char *scan;
3143 value = (value << 8) | ((*scan++) & 0xff);
3148 copy_threadref (threadref *dest, threadref *src)
3151 unsigned char *csrc, *cdest;
3153 csrc = (unsigned char *) src;
3154 cdest = (unsigned char *) dest;
3161 threadmatch (threadref *dest, threadref *src)
3163 /* Things are broken right now, so just assume we got a match. */
3165 unsigned char *srcp, *destp;
3167 srcp = (char *) src;
3168 destp = (char *) dest;
3172 result &= (*srcp++ == *destp++) ? 1 : 0;
3179 threadid:1, # always request threadid
3186 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
3189 pack_threadinfo_request (char *pkt, int mode, threadref *id)
3191 *pkt++ = 'q'; /* Info Query */
3192 *pkt++ = 'P'; /* process or thread info */
3193 pkt = pack_int (pkt, mode); /* mode */
3194 pkt = pack_threadid (pkt, id); /* threadid */
3195 *pkt = '\0'; /* terminate */
3199 /* These values tag the fields in a thread info response packet. */
3200 /* Tagging the fields allows us to request specific fields and to
3201 add more fields as time goes by. */
3203 #define TAG_THREADID 1 /* Echo the thread identifier. */
3204 #define TAG_EXISTS 2 /* Is this process defined enough to
3205 fetch registers and its stack? */
3206 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
3207 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
3208 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
3212 remote_target::remote_unpack_thread_info_response (char *pkt,
3213 threadref *expectedref,
3214 gdb_ext_thread_info *info)
3216 struct remote_state *rs = get_remote_state ();
3220 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
3223 /* info->threadid = 0; FIXME: implement zero_threadref. */
3225 info->display[0] = '\0';
3226 info->shortname[0] = '\0';
3227 info->more_display[0] = '\0';
3229 /* Assume the characters indicating the packet type have been
3231 pkt = unpack_int (pkt, &mask); /* arg mask */
3232 pkt = unpack_threadid (pkt, &ref);
3235 warning (_("Incomplete response to threadinfo request."));
3236 if (!threadmatch (&ref, expectedref))
3237 { /* This is an answer to a different request. */
3238 warning (_("ERROR RMT Thread info mismatch."));
3241 copy_threadref (&info->threadid, &ref);
3243 /* Loop on tagged fields , try to bail if somthing goes wrong. */
3245 /* Packets are terminated with nulls. */
3246 while ((pkt < limit) && mask && *pkt)
3248 pkt = unpack_int (pkt, &tag); /* tag */
3249 pkt = unpack_byte (pkt, &length); /* length */
3250 if (!(tag & mask)) /* Tags out of synch with mask. */
3252 warning (_("ERROR RMT: threadinfo tag mismatch."));
3256 if (tag == TAG_THREADID)
3260 warning (_("ERROR RMT: length of threadid is not 16."));
3264 pkt = unpack_threadid (pkt, &ref);
3265 mask = mask & ~TAG_THREADID;
3268 if (tag == TAG_EXISTS)
3270 info->active = stub_unpack_int (pkt, length);
3272 mask = mask & ~(TAG_EXISTS);
3275 warning (_("ERROR RMT: 'exists' length too long."));
3281 if (tag == TAG_THREADNAME)
3283 pkt = unpack_string (pkt, &info->shortname[0], length);
3284 mask = mask & ~TAG_THREADNAME;
3287 if (tag == TAG_DISPLAY)
3289 pkt = unpack_string (pkt, &info->display[0], length);
3290 mask = mask & ~TAG_DISPLAY;
3293 if (tag == TAG_MOREDISPLAY)
3295 pkt = unpack_string (pkt, &info->more_display[0], length);
3296 mask = mask & ~TAG_MOREDISPLAY;
3299 warning (_("ERROR RMT: unknown thread info tag."));
3300 break; /* Not a tag we know about. */
3306 remote_target::remote_get_threadinfo (threadref *threadid,
3308 gdb_ext_thread_info *info)
3310 struct remote_state *rs = get_remote_state ();
3313 pack_threadinfo_request (rs->buf, fieldset, threadid);
3315 getpkt (&rs->buf, &rs->buf_size, 0);
3317 if (rs->buf[0] == '\0')
3320 result = remote_unpack_thread_info_response (rs->buf + 2,
3325 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
3328 pack_threadlist_request (char *pkt, int startflag, int threadcount,
3329 threadref *nextthread)
3331 *pkt++ = 'q'; /* info query packet */
3332 *pkt++ = 'L'; /* Process LIST or threadLIST request */
3333 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
3334 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
3335 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
3340 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
3343 remote_target::parse_threadlist_response (char *pkt, int result_limit,
3344 threadref *original_echo,
3345 threadref *resultlist,
3348 struct remote_state *rs = get_remote_state ();
3350 int count, resultcount, done;
3353 /* Assume the 'q' and 'M chars have been stripped. */
3354 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
3355 /* done parse past here */
3356 pkt = unpack_byte (pkt, &count); /* count field */
3357 pkt = unpack_nibble (pkt, &done);
3358 /* The first threadid is the argument threadid. */
3359 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
3360 while ((count-- > 0) && (pkt < limit))
3362 pkt = unpack_threadid (pkt, resultlist++);
3363 if (resultcount++ >= result_limit)
3371 /* Fetch the next batch of threads from the remote. Returns -1 if the
3372 qL packet is not supported, 0 on error and 1 on success. */
3375 remote_target::remote_get_threadlist (int startflag, threadref *nextthread,
3376 int result_limit, int *done, int *result_count,
3377 threadref *threadlist)
3379 struct remote_state *rs = get_remote_state ();
3382 /* Trancate result limit to be smaller than the packet size. */
3383 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
3384 >= get_remote_packet_size ())
3385 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
3387 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
3389 getpkt (&rs->buf, &rs->buf_size, 0);
3390 if (*rs->buf == '\0')
3392 /* Packet not supported. */
3397 parse_threadlist_response (rs->buf + 2, result_limit,
3398 &rs->echo_nextthread, threadlist, done);
3400 if (!threadmatch (&rs->echo_nextthread, nextthread))
3402 /* FIXME: This is a good reason to drop the packet. */
3403 /* Possably, there is a duplicate response. */
3405 retransmit immediatly - race conditions
3406 retransmit after timeout - yes
3408 wait for packet, then exit
3410 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
3411 return 0; /* I choose simply exiting. */
3413 if (*result_count <= 0)
3417 warning (_("RMT ERROR : failed to get remote thread list."));
3420 return result; /* break; */
3422 if (*result_count > result_limit)
3425 warning (_("RMT ERROR: threadlist response longer than requested."));
3431 /* Fetch the list of remote threads, with the qL packet, and call
3432 STEPFUNCTION for each thread found. Stops iterating and returns 1
3433 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
3434 STEPFUNCTION returns false. If the packet is not supported,
3438 remote_target::remote_threadlist_iterator (rmt_thread_action stepfunction,
3439 void *context, int looplimit)
3441 struct remote_state *rs = get_remote_state ();
3442 int done, i, result_count;
3450 if (loopcount++ > looplimit)
3453 warning (_("Remote fetch threadlist -infinite loop-."));
3456 result = remote_get_threadlist (startflag, &rs->nextthread,
3457 MAXTHREADLISTRESULTS,
3458 &done, &result_count,
3459 rs->resultthreadlist);
3462 /* Clear for later iterations. */
3464 /* Setup to resume next batch of thread references, set nextthread. */
3465 if (result_count >= 1)
3466 copy_threadref (&rs->nextthread,
3467 &rs->resultthreadlist[result_count - 1]);
3469 while (result_count--)
3471 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
3481 /* A thread found on the remote target. */
3485 explicit thread_item (ptid_t ptid_)
3489 thread_item (thread_item &&other) = default;
3490 thread_item &operator= (thread_item &&other) = default;
3492 DISABLE_COPY_AND_ASSIGN (thread_item);
3494 /* The thread's PTID. */
3497 /* The thread's extra info. */
3500 /* The thread's name. */
3503 /* The core the thread was running on. -1 if not known. */
3506 /* The thread handle associated with the thread. */
3507 gdb::byte_vector thread_handle;
3510 /* Context passed around to the various methods listing remote
3511 threads. As new threads are found, they're added to the ITEMS
3514 struct threads_listing_context
3516 /* Return true if this object contains an entry for a thread with ptid
3519 bool contains_thread (ptid_t ptid) const
3521 auto match_ptid = [&] (const thread_item &item)
3523 return item.ptid == ptid;
3526 auto it = std::find_if (this->items.begin (),
3530 return it != this->items.end ();
3533 /* Remove the thread with ptid PTID. */
3535 void remove_thread (ptid_t ptid)
3537 auto match_ptid = [&] (const thread_item &item)
3539 return item.ptid == ptid;
3542 auto it = std::remove_if (this->items.begin (),
3546 if (it != this->items.end ())
3547 this->items.erase (it);
3550 /* The threads found on the remote target. */
3551 std::vector<thread_item> items;
3555 remote_newthread_step (threadref *ref, void *data)
3557 struct threads_listing_context *context
3558 = (struct threads_listing_context *) data;
3559 int pid = inferior_ptid.pid ();
3560 int lwp = threadref_to_int (ref);
3561 ptid_t ptid (pid, lwp);
3563 context->items.emplace_back (ptid);
3565 return 1; /* continue iterator */
3568 #define CRAZY_MAX_THREADS 1000
3571 remote_target::remote_current_thread (ptid_t oldpid)
3573 struct remote_state *rs = get_remote_state ();
3576 getpkt (&rs->buf, &rs->buf_size, 0);
3577 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
3582 result = read_ptid (&rs->buf[2], &obuf);
3583 if (*obuf != '\0' && remote_debug)
3584 fprintf_unfiltered (gdb_stdlog,
3585 "warning: garbage in qC reply\n");
3593 /* List remote threads using the deprecated qL packet. */
3596 remote_target::remote_get_threads_with_ql (threads_listing_context *context)
3598 if (remote_threadlist_iterator (remote_newthread_step, context,
3599 CRAZY_MAX_THREADS) >= 0)
3605 #if defined(HAVE_LIBEXPAT)
3608 start_thread (struct gdb_xml_parser *parser,
3609 const struct gdb_xml_element *element,
3611 std::vector<gdb_xml_value> &attributes)
3613 struct threads_listing_context *data
3614 = (struct threads_listing_context *) user_data;
3615 struct gdb_xml_value *attr;
3617 char *id = (char *) xml_find_attribute (attributes, "id")->value.get ();
3618 ptid_t ptid = read_ptid (id, NULL);
3620 data->items.emplace_back (ptid);
3621 thread_item &item = data->items.back ();
3623 attr = xml_find_attribute (attributes, "core");
3625 item.core = *(ULONGEST *) attr->value.get ();
3627 attr = xml_find_attribute (attributes, "name");
3629 item.name = (const char *) attr->value.get ();
3631 attr = xml_find_attribute (attributes, "handle");
3633 item.thread_handle = hex2bin ((const char *) attr->value.get ());
3637 end_thread (struct gdb_xml_parser *parser,
3638 const struct gdb_xml_element *element,
3639 void *user_data, const char *body_text)
3641 struct threads_listing_context *data
3642 = (struct threads_listing_context *) user_data;
3644 if (body_text != NULL && *body_text != '\0')
3645 data->items.back ().extra = body_text;
3648 const struct gdb_xml_attribute thread_attributes[] = {
3649 { "id", GDB_XML_AF_NONE, NULL, NULL },
3650 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
3651 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
3652 { "handle", GDB_XML_AF_OPTIONAL, NULL, NULL },
3653 { NULL, GDB_XML_AF_NONE, NULL, NULL }
3656 const struct gdb_xml_element thread_children[] = {
3657 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3660 const struct gdb_xml_element threads_children[] = {
3661 { "thread", thread_attributes, thread_children,
3662 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3663 start_thread, end_thread },
3664 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3667 const struct gdb_xml_element threads_elements[] = {
3668 { "threads", NULL, threads_children,
3669 GDB_XML_EF_NONE, NULL, NULL },
3670 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3675 /* List remote threads using qXfer:threads:read. */
3678 remote_target::remote_get_threads_with_qxfer (threads_listing_context *context)
3680 #if defined(HAVE_LIBEXPAT)
3681 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3683 gdb::optional<gdb::char_vector> xml
3684 = target_read_stralloc (this, TARGET_OBJECT_THREADS, NULL);
3686 if (xml && (*xml)[0] != '\0')
3688 gdb_xml_parse_quick (_("threads"), "threads.dtd",
3689 threads_elements, xml->data (), context);
3699 /* List remote threads using qfThreadInfo/qsThreadInfo. */
3702 remote_target::remote_get_threads_with_qthreadinfo (threads_listing_context *context)
3704 struct remote_state *rs = get_remote_state ();
3706 if (rs->use_threadinfo_query)
3710 putpkt ("qfThreadInfo");
3711 getpkt (&rs->buf, &rs->buf_size, 0);
3713 if (bufp[0] != '\0') /* q packet recognized */
3715 while (*bufp++ == 'm') /* reply contains one or more TID */
3719 ptid_t ptid = read_ptid (bufp, &bufp);
3720 context->items.emplace_back (ptid);
3722 while (*bufp++ == ','); /* comma-separated list */
3723 putpkt ("qsThreadInfo");
3724 getpkt (&rs->buf, &rs->buf_size, 0);
3731 /* Packet not recognized. */
3732 rs->use_threadinfo_query = 0;
3739 /* Implement the to_update_thread_list function for the remote
3743 remote_target::update_thread_list ()
3745 struct threads_listing_context context;
3748 /* We have a few different mechanisms to fetch the thread list. Try
3749 them all, starting with the most preferred one first, falling
3750 back to older methods. */
3751 if (remote_get_threads_with_qxfer (&context)
3752 || remote_get_threads_with_qthreadinfo (&context)
3753 || remote_get_threads_with_ql (&context))
3755 struct thread_info *tp, *tmp;
3759 if (context.items.empty ()
3760 && remote_thread_always_alive (inferior_ptid))
3762 /* Some targets don't really support threads, but still
3763 reply an (empty) thread list in response to the thread
3764 listing packets, instead of replying "packet not
3765 supported". Exit early so we don't delete the main
3770 /* CONTEXT now holds the current thread list on the remote
3771 target end. Delete GDB-side threads no longer found on the
3773 ALL_THREADS_SAFE (tp, tmp)
3775 if (!context.contains_thread (tp->ptid))
3782 /* Remove any unreported fork child threads from CONTEXT so
3783 that we don't interfere with follow fork, which is where
3784 creation of such threads is handled. */
3785 remove_new_fork_children (&context);
3787 /* And now add threads we don't know about yet to our list. */
3788 for (thread_item &item : context.items)
3790 if (item.ptid != null_ptid)
3792 /* In non-stop mode, we assume new found threads are
3793 executing until proven otherwise with a stop reply.
3794 In all-stop, we can only get here if all threads are
3796 int executing = target_is_non_stop_p () ? 1 : 0;
3798 remote_notice_new_inferior (item.ptid, executing);
3800 thread_info *tp = find_thread_ptid (item.ptid);
3801 remote_thread_info *info = get_remote_thread_info (tp);
3802 info->core = item.core;
3803 info->extra = std::move (item.extra);
3804 info->name = std::move (item.name);
3805 info->thread_handle = std::move (item.thread_handle);
3812 /* If no thread listing method is supported, then query whether
3813 each known thread is alive, one by one, with the T packet.
3814 If the target doesn't support threads at all, then this is a
3815 no-op. See remote_thread_alive. */
3821 * Collect a descriptive string about the given thread.
3822 * The target may say anything it wants to about the thread
3823 * (typically info about its blocked / runnable state, name, etc.).
3824 * This string will appear in the info threads display.
3826 * Optional: targets are not required to implement this function.
3830 remote_target::extra_thread_info (thread_info *tp)
3832 struct remote_state *rs = get_remote_state ();
3835 struct gdb_ext_thread_info threadinfo;
3837 if (rs->remote_desc == 0) /* paranoia */
3838 internal_error (__FILE__, __LINE__,
3839 _("remote_threads_extra_info"));
3841 if (tp->ptid == magic_null_ptid
3842 || (tp->ptid.pid () != 0 && tp->ptid.lwp () == 0))
3843 /* This is the main thread which was added by GDB. The remote
3844 server doesn't know about it. */
3847 std::string &extra = get_remote_thread_info (tp)->extra;
3849 /* If already have cached info, use it. */
3850 if (!extra.empty ())
3851 return extra.c_str ();
3853 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3855 /* If we're using qXfer:threads:read, then the extra info is
3856 included in the XML. So if we didn't have anything cached,
3857 it's because there's really no extra info. */
3861 if (rs->use_threadextra_query)
3864 char *endb = rs->buf + get_remote_packet_size ();
3866 xsnprintf (b, endb - b, "qThreadExtraInfo,");
3868 write_ptid (b, endb, tp->ptid);
3871 getpkt (&rs->buf, &rs->buf_size, 0);
3872 if (rs->buf[0] != 0)
3874 extra.resize (strlen (rs->buf) / 2);
3875 hex2bin (rs->buf, (gdb_byte *) &extra[0], extra.size ());
3876 return extra.c_str ();
3880 /* If the above query fails, fall back to the old method. */
3881 rs->use_threadextra_query = 0;
3882 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3883 | TAG_MOREDISPLAY | TAG_DISPLAY;
3884 int_to_threadref (&id, tp->ptid.lwp ());
3885 if (remote_get_threadinfo (&id, set, &threadinfo))
3886 if (threadinfo.active)
3888 if (*threadinfo.shortname)
3889 string_appendf (extra, " Name: %s", threadinfo.shortname);
3890 if (*threadinfo.display)
3892 if (!extra.empty ())
3894 string_appendf (extra, " State: %s", threadinfo.display);
3896 if (*threadinfo.more_display)
3898 if (!extra.empty ())
3900 string_appendf (extra, " Priority: %s", threadinfo.more_display);
3902 return extra.c_str ();
3909 remote_target::static_tracepoint_marker_at (CORE_ADDR addr,
3910 struct static_tracepoint_marker *marker)
3912 struct remote_state *rs = get_remote_state ();
3915 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
3917 p += hexnumstr (p, addr);
3919 getpkt (&rs->buf, &rs->buf_size, 0);
3923 error (_("Remote failure reply: %s"), p);
3927 parse_static_tracepoint_marker_definition (p, NULL, marker);
3934 std::vector<static_tracepoint_marker>
3935 remote_target::static_tracepoint_markers_by_strid (const char *strid)
3937 struct remote_state *rs = get_remote_state ();
3938 std::vector<static_tracepoint_marker> markers;
3940 static_tracepoint_marker marker;
3942 /* Ask for a first packet of static tracepoint marker
3945 getpkt (&rs->buf, &rs->buf_size, 0);
3948 error (_("Remote failure reply: %s"), p);
3954 parse_static_tracepoint_marker_definition (p, &p, &marker);
3956 if (strid == NULL || marker.str_id == strid)
3957 markers.push_back (std::move (marker));
3959 while (*p++ == ','); /* comma-separated list */
3960 /* Ask for another packet of static tracepoint definition. */
3962 getpkt (&rs->buf, &rs->buf_size, 0);
3970 /* Implement the to_get_ada_task_ptid function for the remote targets. */
3973 remote_target::get_ada_task_ptid (long lwp, long thread)
3975 return ptid_t (inferior_ptid.pid (), lwp, 0);
3979 /* Restart the remote side; this is an extended protocol operation. */
3982 remote_target::extended_remote_restart ()
3984 struct remote_state *rs = get_remote_state ();
3986 /* Send the restart command; for reasons I don't understand the
3987 remote side really expects a number after the "R". */
3988 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
3991 remote_fileio_reset ();
3994 /* Clean up connection to a remote debugger. */
3997 remote_target::close ()
3999 /* Make sure we leave stdin registered in the event loop. */
4002 /* We don't have a connection to the remote stub anymore. Get rid
4003 of all the inferiors and their threads we were controlling.
4004 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
4005 will be unable to find the thread corresponding to (pid, 0, 0). */
4006 inferior_ptid = null_ptid;
4007 discard_all_inferiors ();
4009 trace_reset_local_state ();
4014 remote_target::~remote_target ()
4016 struct remote_state *rs = get_remote_state ();
4018 /* Check for NULL because we may get here with a partially
4019 constructed target/connection. */
4020 if (rs->remote_desc == nullptr)
4023 serial_close (rs->remote_desc);
4025 /* We are destroying the remote target, so we should discard
4026 everything of this target. */
4027 discard_pending_stop_replies_in_queue ();
4029 if (rs->remote_async_inferior_event_token)
4030 delete_async_event_handler (&rs->remote_async_inferior_event_token);
4032 remote_notif_state_xfree (rs->notif_state);
4035 /* Query the remote side for the text, data and bss offsets. */
4038 remote_target::get_offsets ()
4040 struct remote_state *rs = get_remote_state ();
4043 int lose, num_segments = 0, do_sections, do_segments;
4044 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
4045 struct section_offsets *offs;
4046 struct symfile_segment_data *data;
4048 if (symfile_objfile == NULL)
4051 putpkt ("qOffsets");
4052 getpkt (&rs->buf, &rs->buf_size, 0);
4055 if (buf[0] == '\000')
4056 return; /* Return silently. Stub doesn't support
4060 warning (_("Remote failure reply: %s"), buf);
4064 /* Pick up each field in turn. This used to be done with scanf, but
4065 scanf will make trouble if CORE_ADDR size doesn't match
4066 conversion directives correctly. The following code will work
4067 with any size of CORE_ADDR. */
4068 text_addr = data_addr = bss_addr = 0;
4072 if (startswith (ptr, "Text="))
4075 /* Don't use strtol, could lose on big values. */
4076 while (*ptr && *ptr != ';')
4077 text_addr = (text_addr << 4) + fromhex (*ptr++);
4079 if (startswith (ptr, ";Data="))
4082 while (*ptr && *ptr != ';')
4083 data_addr = (data_addr << 4) + fromhex (*ptr++);
4088 if (!lose && startswith (ptr, ";Bss="))
4091 while (*ptr && *ptr != ';')
4092 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
4094 if (bss_addr != data_addr)
4095 warning (_("Target reported unsupported offsets: %s"), buf);
4100 else if (startswith (ptr, "TextSeg="))
4103 /* Don't use strtol, could lose on big values. */
4104 while (*ptr && *ptr != ';')
4105 text_addr = (text_addr << 4) + fromhex (*ptr++);
4108 if (startswith (ptr, ";DataSeg="))
4111 while (*ptr && *ptr != ';')
4112 data_addr = (data_addr << 4) + fromhex (*ptr++);
4120 error (_("Malformed response to offset query, %s"), buf);
4121 else if (*ptr != '\0')
4122 warning (_("Target reported unsupported offsets: %s"), buf);
4124 offs = ((struct section_offsets *)
4125 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
4126 memcpy (offs, symfile_objfile->section_offsets,
4127 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
4129 data = get_symfile_segment_data (symfile_objfile->obfd);
4130 do_segments = (data != NULL);
4131 do_sections = num_segments == 0;
4133 if (num_segments > 0)
4135 segments[0] = text_addr;
4136 segments[1] = data_addr;
4138 /* If we have two segments, we can still try to relocate everything
4139 by assuming that the .text and .data offsets apply to the whole
4140 text and data segments. Convert the offsets given in the packet
4141 to base addresses for symfile_map_offsets_to_segments. */
4142 else if (data && data->num_segments == 2)
4144 segments[0] = data->segment_bases[0] + text_addr;
4145 segments[1] = data->segment_bases[1] + data_addr;
4148 /* If the object file has only one segment, assume that it is text
4149 rather than data; main programs with no writable data are rare,
4150 but programs with no code are useless. Of course the code might
4151 have ended up in the data segment... to detect that we would need
4152 the permissions here. */
4153 else if (data && data->num_segments == 1)
4155 segments[0] = data->segment_bases[0] + text_addr;
4158 /* There's no way to relocate by segment. */
4164 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
4165 offs, num_segments, segments);
4167 if (ret == 0 && !do_sections)
4168 error (_("Can not handle qOffsets TextSeg "
4169 "response with this symbol file"));
4176 free_symfile_segment_data (data);
4180 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
4182 /* This is a temporary kludge to force data and bss to use the
4183 same offsets because that's what nlmconv does now. The real
4184 solution requires changes to the stub and remote.c that I
4185 don't have time to do right now. */
4187 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
4188 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
4191 objfile_relocate (symfile_objfile, offs);
4194 /* Send interrupt_sequence to remote target. */
4197 remote_target::send_interrupt_sequence ()
4199 struct remote_state *rs = get_remote_state ();
4201 if (interrupt_sequence_mode == interrupt_sequence_control_c)
4202 remote_serial_write ("\x03", 1);
4203 else if (interrupt_sequence_mode == interrupt_sequence_break)
4204 serial_send_break (rs->remote_desc);
4205 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
4207 serial_send_break (rs->remote_desc);
4208 remote_serial_write ("g", 1);
4211 internal_error (__FILE__, __LINE__,
4212 _("Invalid value for interrupt_sequence_mode: %s."),
4213 interrupt_sequence_mode);
4217 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
4218 and extract the PTID. Returns NULL_PTID if not found. */
4221 stop_reply_extract_thread (char *stop_reply)
4223 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
4227 /* Txx r:val ; r:val (...) */
4230 /* Look for "register" named "thread". */
4235 p1 = strchr (p, ':');
4239 if (strncmp (p, "thread", p1 - p) == 0)
4240 return read_ptid (++p1, &p);
4242 p1 = strchr (p, ';');
4254 /* Determine the remote side's current thread. If we have a stop
4255 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
4256 "thread" register we can extract the current thread from. If not,
4257 ask the remote which is the current thread with qC. The former
4258 method avoids a roundtrip. */
4261 remote_target::get_current_thread (char *wait_status)
4263 ptid_t ptid = null_ptid;
4265 /* Note we don't use remote_parse_stop_reply as that makes use of
4266 the target architecture, which we haven't yet fully determined at
4268 if (wait_status != NULL)
4269 ptid = stop_reply_extract_thread (wait_status);
4270 if (ptid == null_ptid)
4271 ptid = remote_current_thread (inferior_ptid);
4276 /* Query the remote target for which is the current thread/process,
4277 add it to our tables, and update INFERIOR_PTID. The caller is
4278 responsible for setting the state such that the remote end is ready
4279 to return the current thread.
4281 This function is called after handling the '?' or 'vRun' packets,
4282 whose response is a stop reply from which we can also try
4283 extracting the thread. If the target doesn't support the explicit
4284 qC query, we infer the current thread from that stop reply, passed
4285 in in WAIT_STATUS, which may be NULL. */
4288 remote_target::add_current_inferior_and_thread (char *wait_status)
4290 struct remote_state *rs = get_remote_state ();
4293 inferior_ptid = null_ptid;
4295 /* Now, if we have thread information, update inferior_ptid. */
4296 ptid_t curr_ptid = get_current_thread (wait_status);
4298 if (curr_ptid != null_ptid)
4300 if (!remote_multi_process_p (rs))
4305 /* Without this, some commands which require an active target
4306 (such as kill) won't work. This variable serves (at least)
4307 double duty as both the pid of the target process (if it has
4308 such), and as a flag indicating that a target is active. */
4309 curr_ptid = magic_null_ptid;
4313 remote_add_inferior (fake_pid_p, curr_ptid.pid (), -1, 1);
4315 /* Add the main thread and switch to it. Don't try reading
4316 registers yet, since we haven't fetched the target description
4318 thread_info *tp = add_thread_silent (curr_ptid);
4319 switch_to_thread_no_regs (tp);
4322 /* Print info about a thread that was found already stopped on
4326 print_one_stopped_thread (struct thread_info *thread)
4328 struct target_waitstatus *ws = &thread->suspend.waitstatus;
4330 switch_to_thread (thread);
4331 thread->suspend.stop_pc = get_frame_pc (get_current_frame ());
4332 set_current_sal_from_frame (get_current_frame ());
4334 thread->suspend.waitstatus_pending_p = 0;
4336 if (ws->kind == TARGET_WAITKIND_STOPPED)
4338 enum gdb_signal sig = ws->value.sig;
4340 if (signal_print_state (sig))
4341 gdb::observers::signal_received.notify (sig);
4343 gdb::observers::normal_stop.notify (NULL, 1);
4346 /* Process all initial stop replies the remote side sent in response
4347 to the ? packet. These indicate threads that were already stopped
4348 on initial connection. We mark these threads as stopped and print
4349 their current frame before giving the user the prompt. */
4352 remote_target::process_initial_stop_replies (int from_tty)
4354 int pending_stop_replies = stop_reply_queue_length ();
4355 struct inferior *inf;
4356 struct thread_info *thread;
4357 struct thread_info *selected = NULL;
4358 struct thread_info *lowest_stopped = NULL;
4359 struct thread_info *first = NULL;
4361 /* Consume the initial pending events. */
4362 while (pending_stop_replies-- > 0)
4364 ptid_t waiton_ptid = minus_one_ptid;
4366 struct target_waitstatus ws;
4367 int ignore_event = 0;
4368 struct thread_info *thread;
4370 memset (&ws, 0, sizeof (ws));
4371 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
4373 print_target_wait_results (waiton_ptid, event_ptid, &ws);
4377 case TARGET_WAITKIND_IGNORE:
4378 case TARGET_WAITKIND_NO_RESUMED:
4379 case TARGET_WAITKIND_SIGNALLED:
4380 case TARGET_WAITKIND_EXITED:
4381 /* We shouldn't see these, but if we do, just ignore. */
4383 fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
4387 case TARGET_WAITKIND_EXECD:
4388 xfree (ws.value.execd_pathname);
4397 thread = find_thread_ptid (event_ptid);
4399 if (ws.kind == TARGET_WAITKIND_STOPPED)
4401 enum gdb_signal sig = ws.value.sig;
4403 /* Stubs traditionally report SIGTRAP as initial signal,
4404 instead of signal 0. Suppress it. */
4405 if (sig == GDB_SIGNAL_TRAP)
4407 thread->suspend.stop_signal = sig;
4411 thread->suspend.waitstatus = ws;
4413 if (ws.kind != TARGET_WAITKIND_STOPPED
4414 || ws.value.sig != GDB_SIGNAL_0)
4415 thread->suspend.waitstatus_pending_p = 1;
4417 set_executing (event_ptid, 0);
4418 set_running (event_ptid, 0);
4419 get_remote_thread_info (thread)->vcont_resumed = 0;
4422 /* "Notice" the new inferiors before anything related to
4423 registers/memory. */
4429 inf->needs_setup = 1;
4433 thread = any_live_thread_of_inferior (inf);
4434 notice_new_inferior (thread, thread->state == THREAD_RUNNING,
4439 /* If all-stop on top of non-stop, pause all threads. Note this
4440 records the threads' stop pc, so must be done after "noticing"
4444 stop_all_threads ();
4446 /* If all threads of an inferior were already stopped, we
4447 haven't setup the inferior yet. */
4453 if (inf->needs_setup)
4455 thread = any_live_thread_of_inferior (inf);
4456 switch_to_thread_no_regs (thread);
4462 /* Now go over all threads that are stopped, and print their current
4463 frame. If all-stop, then if there's a signalled thread, pick
4465 ALL_NON_EXITED_THREADS (thread)
4471 thread->set_running (false);
4472 else if (thread->state != THREAD_STOPPED)
4475 if (selected == NULL
4476 && thread->suspend.waitstatus_pending_p)
4479 if (lowest_stopped == NULL
4480 || thread->inf->num < lowest_stopped->inf->num
4481 || thread->per_inf_num < lowest_stopped->per_inf_num)
4482 lowest_stopped = thread;
4485 print_one_stopped_thread (thread);
4488 /* In all-stop, we only print the status of one thread, and leave
4489 others with their status pending. */
4494 thread = lowest_stopped;
4498 print_one_stopped_thread (thread);
4501 /* For "info program". */
4502 thread = inferior_thread ();
4503 if (thread->state == THREAD_STOPPED)
4504 set_last_target_status (inferior_ptid, thread->suspend.waitstatus);
4507 /* Start the remote connection and sync state. */
4510 remote_target::start_remote (int from_tty, int extended_p)
4512 struct remote_state *rs = get_remote_state ();
4513 struct packet_config *noack_config;
4514 char *wait_status = NULL;
4516 /* Signal other parts that we're going through the initial setup,
4517 and so things may not be stable yet. E.g., we don't try to
4518 install tracepoints until we've relocated symbols. Also, a
4519 Ctrl-C before we're connected and synced up can't interrupt the
4520 target. Instead, it offers to drop the (potentially wedged)
4522 rs->starting_up = 1;
4526 if (interrupt_on_connect)
4527 send_interrupt_sequence ();
4529 /* Ack any packet which the remote side has already sent. */
4530 remote_serial_write ("+", 1);
4532 /* The first packet we send to the target is the optional "supported
4533 packets" request. If the target can answer this, it will tell us
4534 which later probes to skip. */
4535 remote_query_supported ();
4537 /* If the stub wants to get a QAllow, compose one and send it. */
4538 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
4541 /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
4542 unknown 'v' packet with string "OK". "OK" gets interpreted by GDB
4543 as a reply to known packet. For packet "vFile:setfs:" it is an
4544 invalid reply and GDB would return error in
4545 remote_hostio_set_filesystem, making remote files access impossible.
4546 Disable "vFile:setfs:" in such case. Do not disable other 'v' packets as
4547 other "vFile" packets get correctly detected even on gdbserver < 7.7. */
4549 const char v_mustreplyempty[] = "vMustReplyEmpty";
4551 putpkt (v_mustreplyempty);
4552 getpkt (&rs->buf, &rs->buf_size, 0);
4553 if (strcmp (rs->buf, "OK") == 0)
4554 remote_protocol_packets[PACKET_vFile_setfs].support = PACKET_DISABLE;
4555 else if (strcmp (rs->buf, "") != 0)
4556 error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
4560 /* Next, we possibly activate noack mode.
4562 If the QStartNoAckMode packet configuration is set to AUTO,
4563 enable noack mode if the stub reported a wish for it with
4566 If set to TRUE, then enable noack mode even if the stub didn't
4567 report it in qSupported. If the stub doesn't reply OK, the
4568 session ends with an error.
4570 If FALSE, then don't activate noack mode, regardless of what the
4571 stub claimed should be the default with qSupported. */
4573 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4574 if (packet_config_support (noack_config) != PACKET_DISABLE)
4576 putpkt ("QStartNoAckMode");
4577 getpkt (&rs->buf, &rs->buf_size, 0);
4578 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
4584 /* Tell the remote that we are using the extended protocol. */
4586 getpkt (&rs->buf, &rs->buf_size, 0);
4589 /* Let the target know which signals it is allowed to pass down to
4591 update_signals_program_target ();
4593 /* Next, if the target can specify a description, read it. We do
4594 this before anything involving memory or registers. */
4595 target_find_description ();
4597 /* Next, now that we know something about the target, update the
4598 address spaces in the program spaces. */
4599 update_address_spaces ();
4601 /* On OSs where the list of libraries is global to all
4602 processes, we fetch them early. */
4603 if (gdbarch_has_global_solist (target_gdbarch ()))
4604 solib_add (NULL, from_tty, auto_solib_add);
4606 if (target_is_non_stop_p ())
4608 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
4609 error (_("Non-stop mode requested, but remote "
4610 "does not support non-stop"));
4612 putpkt ("QNonStop:1");
4613 getpkt (&rs->buf, &rs->buf_size, 0);
4615 if (strcmp (rs->buf, "OK") != 0)
4616 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
4618 /* Find about threads and processes the stub is already
4619 controlling. We default to adding them in the running state.
4620 The '?' query below will then tell us about which threads are
4622 this->update_thread_list ();
4624 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
4626 /* Don't assume that the stub can operate in all-stop mode.
4627 Request it explicitly. */
4628 putpkt ("QNonStop:0");
4629 getpkt (&rs->buf, &rs->buf_size, 0);
4631 if (strcmp (rs->buf, "OK") != 0)
4632 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
4635 /* Upload TSVs regardless of whether the target is running or not. The
4636 remote stub, such as GDBserver, may have some predefined or builtin
4637 TSVs, even if the target is not running. */
4638 if (get_trace_status (current_trace_status ()) != -1)
4640 struct uploaded_tsv *uploaded_tsvs = NULL;
4642 upload_trace_state_variables (&uploaded_tsvs);
4643 merge_uploaded_trace_state_variables (&uploaded_tsvs);
4646 /* Check whether the target is running now. */
4648 getpkt (&rs->buf, &rs->buf_size, 0);
4650 if (!target_is_non_stop_p ())
4652 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
4655 error (_("The target is not running (try extended-remote?)"));
4657 /* We're connected, but not running. Drop out before we
4658 call start_remote. */
4659 rs->starting_up = 0;
4664 /* Save the reply for later. */
4665 wait_status = (char *) alloca (strlen (rs->buf) + 1);
4666 strcpy (wait_status, rs->buf);
4669 /* Fetch thread list. */
4670 target_update_thread_list ();
4672 /* Let the stub know that we want it to return the thread. */
4673 set_continue_thread (minus_one_ptid);
4675 if (thread_count () == 0)
4677 /* Target has no concept of threads at all. GDB treats
4678 non-threaded target as single-threaded; add a main
4680 add_current_inferior_and_thread (wait_status);
4684 /* We have thread information; select the thread the target
4685 says should be current. If we're reconnecting to a
4686 multi-threaded program, this will ideally be the thread
4687 that last reported an event before GDB disconnected. */
4688 inferior_ptid = get_current_thread (wait_status);
4689 if (inferior_ptid == null_ptid)
4691 /* Odd... The target was able to list threads, but not
4692 tell us which thread was current (no "thread"
4693 register in T stop reply?). Just pick the first
4694 thread in the thread list then. */
4697 fprintf_unfiltered (gdb_stdlog,
4698 "warning: couldn't determine remote "
4699 "current thread; picking first in list.\n");
4701 inferior_ptid = thread_list->ptid;
4705 /* init_wait_for_inferior should be called before get_offsets in order
4706 to manage `inserted' flag in bp loc in a correct state.
4707 breakpoint_init_inferior, called from init_wait_for_inferior, set
4708 `inserted' flag to 0, while before breakpoint_re_set, called from
4709 start_remote, set `inserted' flag to 1. In the initialization of
4710 inferior, breakpoint_init_inferior should be called first, and then
4711 breakpoint_re_set can be called. If this order is broken, state of
4712 `inserted' flag is wrong, and cause some problems on breakpoint
4714 init_wait_for_inferior ();
4716 get_offsets (); /* Get text, data & bss offsets. */
4718 /* If we could not find a description using qXfer, and we know
4719 how to do it some other way, try again. This is not
4720 supported for non-stop; it could be, but it is tricky if
4721 there are no stopped threads when we connect. */
4722 if (remote_read_description_p (this)
4723 && gdbarch_target_desc (target_gdbarch ()) == NULL)
4725 target_clear_description ();
4726 target_find_description ();
4729 /* Use the previously fetched status. */
4730 gdb_assert (wait_status != NULL);
4731 strcpy (rs->buf, wait_status);
4732 rs->cached_wait_status = 1;
4734 ::start_remote (from_tty); /* Initialize gdb process mechanisms. */
4738 /* Clear WFI global state. Do this before finding about new
4739 threads and inferiors, and setting the current inferior.
4740 Otherwise we would clear the proceed status of the current
4741 inferior when we want its stop_soon state to be preserved
4742 (see notice_new_inferior). */
4743 init_wait_for_inferior ();
4745 /* In non-stop, we will either get an "OK", meaning that there
4746 are no stopped threads at this time; or, a regular stop
4747 reply. In the latter case, there may be more than one thread
4748 stopped --- we pull them all out using the vStopped
4750 if (strcmp (rs->buf, "OK") != 0)
4752 struct notif_client *notif = ¬if_client_stop;
4754 /* remote_notif_get_pending_replies acks this one, and gets
4756 rs->notif_state->pending_event[notif_client_stop.id]
4757 = remote_notif_parse (this, notif, rs->buf);
4758 remote_notif_get_pending_events (notif);
4761 if (thread_count () == 0)
4764 error (_("The target is not running (try extended-remote?)"));
4766 /* We're connected, but not running. Drop out before we
4767 call start_remote. */
4768 rs->starting_up = 0;
4772 /* In non-stop mode, any cached wait status will be stored in
4773 the stop reply queue. */
4774 gdb_assert (wait_status == NULL);
4776 /* Report all signals during attach/startup. */
4777 pass_signals (0, NULL);
4779 /* If there are already stopped threads, mark them stopped and
4780 report their stops before giving the prompt to the user. */
4781 process_initial_stop_replies (from_tty);
4783 if (target_can_async_p ())
4787 /* If we connected to a live target, do some additional setup. */
4788 if (target_has_execution)
4790 if (symfile_objfile) /* No use without a symbol-file. */
4791 remote_check_symbols ();
4794 /* Possibly the target has been engaged in a trace run started
4795 previously; find out where things are at. */
4796 if (get_trace_status (current_trace_status ()) != -1)
4798 struct uploaded_tp *uploaded_tps = NULL;
4800 if (current_trace_status ()->running)
4801 printf_filtered (_("Trace is already running on the target.\n"));
4803 upload_tracepoints (&uploaded_tps);
4805 merge_uploaded_tracepoints (&uploaded_tps);
4808 /* Possibly the target has been engaged in a btrace record started
4809 previously; find out where things are at. */
4810 remote_btrace_maybe_reopen ();
4812 /* The thread and inferior lists are now synchronized with the
4813 target, our symbols have been relocated, and we're merged the
4814 target's tracepoints with ours. We're done with basic start
4816 rs->starting_up = 0;
4818 /* Maybe breakpoints are global and need to be inserted now. */
4819 if (breakpoints_should_be_inserted_now ())
4820 insert_breakpoints ();
4823 /* Open a connection to a remote debugger.
4824 NAME is the filename used for communication. */
4827 remote_target::open (const char *name, int from_tty)
4829 open_1 (name, from_tty, 0);
4832 /* Open a connection to a remote debugger using the extended
4833 remote gdb protocol. NAME is the filename used for communication. */
4836 extended_remote_target::open (const char *name, int from_tty)
4838 open_1 (name, from_tty, 1 /*extended_p */);
4841 /* Reset all packets back to "unknown support". Called when opening a
4842 new connection to a remote target. */
4845 reset_all_packet_configs_support (void)
4849 for (i = 0; i < PACKET_MAX; i++)
4850 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4853 /* Initialize all packet configs. */
4856 init_all_packet_configs (void)
4860 for (i = 0; i < PACKET_MAX; i++)
4862 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
4863 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4867 /* Symbol look-up. */
4870 remote_target::remote_check_symbols ()
4872 char *msg, *reply, *tmp;
4875 struct cleanup *old_chain;
4877 /* The remote side has no concept of inferiors that aren't running
4878 yet, it only knows about running processes. If we're connected
4879 but our current inferior is not running, we should not invite the
4880 remote target to request symbol lookups related to its
4881 (unrelated) current process. */
4882 if (!target_has_execution)
4885 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
4888 /* Make sure the remote is pointing at the right process. Note
4889 there's no way to select "no process". */
4890 set_general_process ();
4892 /* Allocate a message buffer. We can't reuse the input buffer in RS,
4893 because we need both at the same time. */
4894 msg = (char *) xmalloc (get_remote_packet_size ());
4895 old_chain = make_cleanup (xfree, msg);
4896 reply = (char *) xmalloc (get_remote_packet_size ());
4897 make_cleanup (free_current_contents, &reply);
4898 reply_size = get_remote_packet_size ();
4900 /* Invite target to request symbol lookups. */
4902 putpkt ("qSymbol::");
4903 getpkt (&reply, &reply_size, 0);
4904 packet_ok (reply, &remote_protocol_packets[PACKET_qSymbol]);
4906 while (startswith (reply, "qSymbol:"))
4908 struct bound_minimal_symbol sym;
4911 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
4913 sym = lookup_minimal_symbol (msg, NULL, NULL);
4914 if (sym.minsym == NULL)
4915 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
4918 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4919 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
4921 /* If this is a function address, return the start of code
4922 instead of any data function descriptor. */
4923 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
4925 current_top_target ());
4927 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
4928 phex_nz (sym_addr, addr_size), &reply[8]);
4932 getpkt (&reply, &reply_size, 0);
4935 do_cleanups (old_chain);
4938 static struct serial *
4939 remote_serial_open (const char *name)
4941 static int udp_warning = 0;
4943 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
4944 of in ser-tcp.c, because it is the remote protocol assuming that the
4945 serial connection is reliable and not the serial connection promising
4947 if (!udp_warning && startswith (name, "udp:"))
4949 warning (_("The remote protocol may be unreliable over UDP.\n"
4950 "Some events may be lost, rendering further debugging "
4955 return serial_open (name);
4958 /* Inform the target of our permission settings. The permission flags
4959 work without this, but if the target knows the settings, it can do
4960 a couple things. First, it can add its own check, to catch cases
4961 that somehow manage to get by the permissions checks in target
4962 methods. Second, if the target is wired to disallow particular
4963 settings (for instance, a system in the field that is not set up to
4964 be able to stop at a breakpoint), it can object to any unavailable
4968 remote_target::set_permissions ()
4970 struct remote_state *rs = get_remote_state ();
4972 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
4973 "WriteReg:%x;WriteMem:%x;"
4974 "InsertBreak:%x;InsertTrace:%x;"
4975 "InsertFastTrace:%x;Stop:%x",
4976 may_write_registers, may_write_memory,
4977 may_insert_breakpoints, may_insert_tracepoints,
4978 may_insert_fast_tracepoints, may_stop);
4980 getpkt (&rs->buf, &rs->buf_size, 0);
4982 /* If the target didn't like the packet, warn the user. Do not try
4983 to undo the user's settings, that would just be maddening. */
4984 if (strcmp (rs->buf, "OK") != 0)
4985 warning (_("Remote refused setting permissions with: %s"), rs->buf);
4988 /* This type describes each known response to the qSupported
4990 struct protocol_feature
4992 /* The name of this protocol feature. */
4995 /* The default for this protocol feature. */
4996 enum packet_support default_support;
4998 /* The function to call when this feature is reported, or after
4999 qSupported processing if the feature is not supported.
5000 The first argument points to this structure. The second
5001 argument indicates whether the packet requested support be
5002 enabled, disabled, or probed (or the default, if this function
5003 is being called at the end of processing and this feature was
5004 not reported). The third argument may be NULL; if not NULL, it
5005 is a NUL-terminated string taken from the packet following
5006 this feature's name and an equals sign. */
5007 void (*func) (remote_target *remote, const struct protocol_feature *,
5008 enum packet_support, const char *);
5010 /* The corresponding packet for this feature. Only used if
5011 FUNC is remote_supported_packet. */
5016 remote_supported_packet (remote_target *remote,
5017 const struct protocol_feature *feature,
5018 enum packet_support support,
5019 const char *argument)
5023 warning (_("Remote qSupported response supplied an unexpected value for"
5024 " \"%s\"."), feature->name);
5028 remote_protocol_packets[feature->packet].support = support;
5032 remote_target::remote_packet_size (const protocol_feature *feature,
5033 enum packet_support support, const char *value)
5035 struct remote_state *rs = get_remote_state ();
5040 if (support != PACKET_ENABLE)
5043 if (value == NULL || *value == '\0')
5045 warning (_("Remote target reported \"%s\" without a size."),
5051 packet_size = strtol (value, &value_end, 16);
5052 if (errno != 0 || *value_end != '\0' || packet_size < 0)
5054 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
5055 feature->name, value);
5059 /* Record the new maximum packet size. */
5060 rs->explicit_packet_size = packet_size;
5064 remote_packet_size (remote_target *remote, const protocol_feature *feature,
5065 enum packet_support support, const char *value)
5067 remote->remote_packet_size (feature, support, value);
5070 static const struct protocol_feature remote_protocol_features[] = {
5071 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
5072 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
5073 PACKET_qXfer_auxv },
5074 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
5075 PACKET_qXfer_exec_file },
5076 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
5077 PACKET_qXfer_features },
5078 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
5079 PACKET_qXfer_libraries },
5080 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
5081 PACKET_qXfer_libraries_svr4 },
5082 { "augmented-libraries-svr4-read", PACKET_DISABLE,
5083 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
5084 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
5085 PACKET_qXfer_memory_map },
5086 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
5087 PACKET_qXfer_spu_read },
5088 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
5089 PACKET_qXfer_spu_write },
5090 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
5091 PACKET_qXfer_osdata },
5092 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
5093 PACKET_qXfer_threads },
5094 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
5095 PACKET_qXfer_traceframe_info },
5096 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
5097 PACKET_QPassSignals },
5098 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
5099 PACKET_QCatchSyscalls },
5100 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
5101 PACKET_QProgramSignals },
5102 { "QSetWorkingDir", PACKET_DISABLE, remote_supported_packet,
5103 PACKET_QSetWorkingDir },
5104 { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
5105 PACKET_QStartupWithShell },
5106 { "QEnvironmentHexEncoded", PACKET_DISABLE, remote_supported_packet,
5107 PACKET_QEnvironmentHexEncoded },
5108 { "QEnvironmentReset", PACKET_DISABLE, remote_supported_packet,
5109 PACKET_QEnvironmentReset },
5110 { "QEnvironmentUnset", PACKET_DISABLE, remote_supported_packet,
5111 PACKET_QEnvironmentUnset },
5112 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
5113 PACKET_QStartNoAckMode },
5114 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
5115 PACKET_multiprocess_feature },
5116 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
5117 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
5118 PACKET_qXfer_siginfo_read },
5119 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
5120 PACKET_qXfer_siginfo_write },
5121 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
5122 PACKET_ConditionalTracepoints },
5123 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
5124 PACKET_ConditionalBreakpoints },
5125 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
5126 PACKET_BreakpointCommands },
5127 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
5128 PACKET_FastTracepoints },
5129 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
5130 PACKET_StaticTracepoints },
5131 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
5132 PACKET_InstallInTrace},
5133 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
5134 PACKET_DisconnectedTracing_feature },
5135 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
5137 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
5139 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
5140 PACKET_TracepointSource },
5141 { "QAllow", PACKET_DISABLE, remote_supported_packet,
5143 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
5144 PACKET_EnableDisableTracepoints_feature },
5145 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
5146 PACKET_qXfer_fdpic },
5147 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
5149 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
5150 PACKET_QDisableRandomization },
5151 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
5152 { "QTBuffer:size", PACKET_DISABLE,
5153 remote_supported_packet, PACKET_QTBuffer_size},
5154 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
5155 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
5156 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
5157 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
5158 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
5159 PACKET_qXfer_btrace },
5160 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
5161 PACKET_qXfer_btrace_conf },
5162 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
5163 PACKET_Qbtrace_conf_bts_size },
5164 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
5165 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
5166 { "fork-events", PACKET_DISABLE, remote_supported_packet,
5167 PACKET_fork_event_feature },
5168 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
5169 PACKET_vfork_event_feature },
5170 { "exec-events", PACKET_DISABLE, remote_supported_packet,
5171 PACKET_exec_event_feature },
5172 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
5173 PACKET_Qbtrace_conf_pt_size },
5174 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
5175 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
5176 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
5179 static char *remote_support_xml;
5181 /* Register string appended to "xmlRegisters=" in qSupported query. */
5184 register_remote_support_xml (const char *xml)
5186 #if defined(HAVE_LIBEXPAT)
5187 if (remote_support_xml == NULL)
5188 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
5191 char *copy = xstrdup (remote_support_xml + 13);
5192 char *p = strtok (copy, ",");
5196 if (strcmp (p, xml) == 0)
5203 while ((p = strtok (NULL, ",")) != NULL);
5206 remote_support_xml = reconcat (remote_support_xml,
5207 remote_support_xml, ",", xml,
5214 remote_query_supported_append (std::string *msg, const char *append)
5218 msg->append (append);
5222 remote_target::remote_query_supported ()
5224 struct remote_state *rs = get_remote_state ();
5227 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
5229 /* The packet support flags are handled differently for this packet
5230 than for most others. We treat an error, a disabled packet, and
5231 an empty response identically: any features which must be reported
5232 to be used will be automatically disabled. An empty buffer
5233 accomplishes this, since that is also the representation for a list
5234 containing no features. */
5237 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
5241 if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
5242 remote_query_supported_append (&q, "multiprocess+");
5244 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
5245 remote_query_supported_append (&q, "swbreak+");
5246 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
5247 remote_query_supported_append (&q, "hwbreak+");
5249 remote_query_supported_append (&q, "qRelocInsn+");
5251 if (packet_set_cmd_state (PACKET_fork_event_feature)
5252 != AUTO_BOOLEAN_FALSE)
5253 remote_query_supported_append (&q, "fork-events+");
5254 if (packet_set_cmd_state (PACKET_vfork_event_feature)
5255 != AUTO_BOOLEAN_FALSE)
5256 remote_query_supported_append (&q, "vfork-events+");
5257 if (packet_set_cmd_state (PACKET_exec_event_feature)
5258 != AUTO_BOOLEAN_FALSE)
5259 remote_query_supported_append (&q, "exec-events+");
5261 if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
5262 remote_query_supported_append (&q, "vContSupported+");
5264 if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
5265 remote_query_supported_append (&q, "QThreadEvents+");
5267 if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
5268 remote_query_supported_append (&q, "no-resumed+");
5270 /* Keep this one last to work around a gdbserver <= 7.10 bug in
5271 the qSupported:xmlRegisters=i386 handling. */
5272 if (remote_support_xml != NULL
5273 && packet_support (PACKET_qXfer_features) != PACKET_DISABLE)
5274 remote_query_supported_append (&q, remote_support_xml);
5276 q = "qSupported:" + q;
5277 putpkt (q.c_str ());
5279 getpkt (&rs->buf, &rs->buf_size, 0);
5281 /* If an error occured, warn, but do not return - just reset the
5282 buffer to empty and go on to disable features. */
5283 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
5286 warning (_("Remote failure reply: %s"), rs->buf);
5291 memset (seen, 0, sizeof (seen));
5296 enum packet_support is_supported;
5297 char *p, *end, *name_end, *value;
5299 /* First separate out this item from the rest of the packet. If
5300 there's another item after this, we overwrite the separator
5301 (terminated strings are much easier to work with). */
5303 end = strchr (p, ';');
5306 end = p + strlen (p);
5316 warning (_("empty item in \"qSupported\" response"));
5321 name_end = strchr (p, '=');
5324 /* This is a name=value entry. */
5325 is_supported = PACKET_ENABLE;
5326 value = name_end + 1;
5335 is_supported = PACKET_ENABLE;
5339 is_supported = PACKET_DISABLE;
5343 is_supported = PACKET_SUPPORT_UNKNOWN;
5347 warning (_("unrecognized item \"%s\" "
5348 "in \"qSupported\" response"), p);
5354 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5355 if (strcmp (remote_protocol_features[i].name, p) == 0)
5357 const struct protocol_feature *feature;
5360 feature = &remote_protocol_features[i];
5361 feature->func (this, feature, is_supported, value);
5366 /* If we increased the packet size, make sure to increase the global
5367 buffer size also. We delay this until after parsing the entire
5368 qSupported packet, because this is the same buffer we were
5370 if (rs->buf_size < rs->explicit_packet_size)
5372 rs->buf_size = rs->explicit_packet_size;
5373 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
5376 /* Handle the defaults for unmentioned features. */
5377 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5380 const struct protocol_feature *feature;
5382 feature = &remote_protocol_features[i];
5383 feature->func (this, feature, feature->default_support, NULL);
5387 /* Serial QUIT handler for the remote serial descriptor.
5389 Defers handling a Ctrl-C until we're done with the current
5390 command/response packet sequence, unless:
5392 - We're setting up the connection. Don't send a remote interrupt
5393 request, as we're not fully synced yet. Quit immediately
5396 - The target has been resumed in the foreground
5397 (target_terminal::is_ours is false) with a synchronous resume
5398 packet, and we're blocked waiting for the stop reply, thus a
5399 Ctrl-C should be immediately sent to the target.
5401 - We get a second Ctrl-C while still within the same serial read or
5402 write. In that case the serial is seemingly wedged --- offer to
5405 - We see a second Ctrl-C without target response, after having
5406 previously interrupted the target. In that case the target/stub
5407 is probably wedged --- offer to quit/disconnect.
5411 remote_target::remote_serial_quit_handler ()
5413 struct remote_state *rs = get_remote_state ();
5415 if (check_quit_flag ())
5417 /* If we're starting up, we're not fully synced yet. Quit
5419 if (rs->starting_up)
5421 else if (rs->got_ctrlc_during_io)
5423 if (query (_("The target is not responding to GDB commands.\n"
5424 "Stop debugging it? ")))
5425 remote_unpush_and_throw ();
5427 /* If ^C has already been sent once, offer to disconnect. */
5428 else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
5430 /* All-stop protocol, and blocked waiting for stop reply. Send
5431 an interrupt request. */
5432 else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
5433 target_interrupt ();
5435 rs->got_ctrlc_during_io = 1;
5439 /* The remote_target that is current while the quit handler is
5440 overridden with remote_serial_quit_handler. */
5441 static remote_target *curr_quit_handler_target;
5444 remote_serial_quit_handler ()
5446 curr_quit_handler_target->remote_serial_quit_handler ();
5449 /* Remove any of the remote.c targets from target stack. Upper targets depend
5450 on it so remove them first. */
5453 remote_unpush_target (void)
5455 pop_all_targets_at_and_above (process_stratum);
5459 remote_unpush_and_throw (void)
5461 remote_unpush_target ();
5462 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5466 remote_target::open_1 (const char *name, int from_tty, int extended_p)
5468 remote_target *curr_remote = get_current_remote_target ();
5471 error (_("To open a remote debug connection, you need to specify what\n"
5472 "serial device is attached to the remote system\n"
5473 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
5475 /* If we're connected to a running target, target_preopen will kill it.
5476 Ask this question first, before target_preopen has a chance to kill
5478 if (curr_remote != NULL && !have_inferiors ())
5481 && !query (_("Already connected to a remote target. Disconnect? ")))
5482 error (_("Still connected."));
5485 /* Here the possibly existing remote target gets unpushed. */
5486 target_preopen (from_tty);
5488 remote_fileio_reset ();
5489 reopen_exec_file ();
5492 remote_target *remote
5493 = (extended_p ? new extended_remote_target () : new remote_target ());
5494 target_ops_up target_holder (remote);
5496 remote_state *rs = remote->get_remote_state ();
5498 /* See FIXME above. */
5499 if (!target_async_permitted)
5500 rs->wait_forever_enabled_p = 1;
5502 rs->remote_desc = remote_serial_open (name);
5503 if (!rs->remote_desc)
5504 perror_with_name (name);
5506 if (baud_rate != -1)
5508 if (serial_setbaudrate (rs->remote_desc, baud_rate))
5510 /* The requested speed could not be set. Error out to
5511 top level after closing remote_desc. Take care to
5512 set remote_desc to NULL to avoid closing remote_desc
5514 serial_close (rs->remote_desc);
5515 rs->remote_desc = NULL;
5516 perror_with_name (name);
5520 serial_setparity (rs->remote_desc, serial_parity);
5521 serial_raw (rs->remote_desc);
5523 /* If there is something sitting in the buffer we might take it as a
5524 response to a command, which would be bad. */
5525 serial_flush_input (rs->remote_desc);
5529 puts_filtered ("Remote debugging using ");
5530 puts_filtered (name);
5531 puts_filtered ("\n");
5534 /* Switch to using the remote target now. */
5535 push_target (remote);
5536 /* The target stack owns the target now. */
5537 target_holder.release ();
5539 /* Register extra event sources in the event loop. */
5540 rs->remote_async_inferior_event_token
5541 = create_async_event_handler (remote_async_inferior_event_handler,
5543 rs->notif_state = remote_notif_state_allocate (remote);
5545 /* Reset the target state; these things will be queried either by
5546 remote_query_supported or as they are needed. */
5547 reset_all_packet_configs_support ();
5548 rs->cached_wait_status = 0;
5549 rs->explicit_packet_size = 0;
5551 rs->extended = extended_p;
5552 rs->waiting_for_stop_reply = 0;
5553 rs->ctrlc_pending_p = 0;
5554 rs->got_ctrlc_during_io = 0;
5556 rs->general_thread = not_sent_ptid;
5557 rs->continue_thread = not_sent_ptid;
5558 rs->remote_traceframe_number = -1;
5560 rs->last_resume_exec_dir = EXEC_FORWARD;
5562 /* Probe for ability to use "ThreadInfo" query, as required. */
5563 rs->use_threadinfo_query = 1;
5564 rs->use_threadextra_query = 1;
5566 rs->readahead_cache.invalidate ();
5568 if (target_async_permitted)
5570 /* FIXME: cagney/1999-09-23: During the initial connection it is
5571 assumed that the target is already ready and able to respond to
5572 requests. Unfortunately remote_start_remote() eventually calls
5573 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
5574 around this. Eventually a mechanism that allows
5575 wait_for_inferior() to expect/get timeouts will be
5577 rs->wait_forever_enabled_p = 0;
5580 /* First delete any symbols previously loaded from shared libraries. */
5581 no_shared_libraries (NULL, 0);
5584 init_thread_list ();
5586 /* Start the remote connection. If error() or QUIT, discard this
5587 target (we'd otherwise be in an inconsistent state) and then
5588 propogate the error on up the exception chain. This ensures that
5589 the caller doesn't stumble along blindly assuming that the
5590 function succeeded. The CLI doesn't have this problem but other
5591 UI's, such as MI do.
5593 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
5594 this function should return an error indication letting the
5595 caller restore the previous state. Unfortunately the command
5596 ``target remote'' is directly wired to this function making that
5597 impossible. On a positive note, the CLI side of this problem has
5598 been fixed - the function set_cmd_context() makes it possible for
5599 all the ``target ....'' commands to share a common callback
5600 function. See cli-dump.c. */
5605 remote->start_remote (from_tty, extended_p);
5607 CATCH (ex, RETURN_MASK_ALL)
5609 /* Pop the partially set up target - unless something else did
5610 already before throwing the exception. */
5611 if (ex.error != TARGET_CLOSE_ERROR)
5612 remote_unpush_target ();
5613 throw_exception (ex);
5618 remote_btrace_reset (rs);
5620 if (target_async_permitted)
5621 rs->wait_forever_enabled_p = 1;
5624 /* Detach the specified process. */
5627 remote_target::remote_detach_pid (int pid)
5629 struct remote_state *rs = get_remote_state ();
5631 /* This should not be necessary, but the handling for D;PID in
5632 GDBserver versions prior to 8.2 incorrectly assumes that the
5633 selected process points to the same process we're detaching,
5634 leading to misbehavior (and possibly GDBserver crashing) when it
5635 does not. Since it's easy and cheap, work around it by forcing
5636 GDBserver to select GDB's current process. */
5637 set_general_process ();
5639 if (remote_multi_process_p (rs))
5640 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
5642 strcpy (rs->buf, "D");
5645 getpkt (&rs->buf, &rs->buf_size, 0);
5647 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
5649 else if (rs->buf[0] == '\0')
5650 error (_("Remote doesn't know how to detach"));
5652 error (_("Can't detach process."));
5655 /* This detaches a program to which we previously attached, using
5656 inferior_ptid to identify the process. After this is done, GDB
5657 can be used to debug some other program. We better not have left
5658 any breakpoints in the target program or it'll die when it hits
5662 remote_target::remote_detach_1 (inferior *inf, int from_tty)
5664 int pid = inferior_ptid.pid ();
5665 struct remote_state *rs = get_remote_state ();
5668 if (!target_has_execution)
5669 error (_("No process to detach from."));
5671 target_announce_detach (from_tty);
5673 /* Tell the remote target to detach. */
5674 remote_detach_pid (pid);
5676 /* Exit only if this is the only active inferior. */
5677 if (from_tty && !rs->extended && number_of_live_inferiors () == 1)
5678 puts_filtered (_("Ending remote debugging.\n"));
5680 struct thread_info *tp = find_thread_ptid (inferior_ptid);
5682 /* Check to see if we are detaching a fork parent. Note that if we
5683 are detaching a fork child, tp == NULL. */
5684 is_fork_parent = (tp != NULL
5685 && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
5687 /* If doing detach-on-fork, we don't mourn, because that will delete
5688 breakpoints that should be available for the followed inferior. */
5689 if (!is_fork_parent)
5691 /* Save the pid as a string before mourning, since that will
5692 unpush the remote target, and we need the string after. */
5693 std::string infpid = target_pid_to_str (ptid_t (pid));
5695 target_mourn_inferior (inferior_ptid);
5696 if (print_inferior_events)
5697 printf_unfiltered (_("[Inferior %d (%s) detached]\n"),
5698 inf->num, infpid.c_str ());
5702 inferior_ptid = null_ptid;
5703 detach_inferior (current_inferior ());
5708 remote_target::detach (inferior *inf, int from_tty)
5710 remote_detach_1 (inf, from_tty);
5714 extended_remote_target::detach (inferior *inf, int from_tty)
5716 remote_detach_1 (inf, from_tty);
5719 /* Target follow-fork function for remote targets. On entry, and
5720 at return, the current inferior is the fork parent.
5722 Note that although this is currently only used for extended-remote,
5723 it is named remote_follow_fork in anticipation of using it for the
5724 remote target as well. */
5727 remote_target::follow_fork (int follow_child, int detach_fork)
5729 struct remote_state *rs = get_remote_state ();
5730 enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
5732 if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
5733 || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
5735 /* When following the parent and detaching the child, we detach
5736 the child here. For the case of following the child and
5737 detaching the parent, the detach is done in the target-
5738 independent follow fork code in infrun.c. We can't use
5739 target_detach when detaching an unfollowed child because
5740 the client side doesn't know anything about the child. */
5741 if (detach_fork && !follow_child)
5743 /* Detach the fork child. */
5747 child_ptid = inferior_thread ()->pending_follow.value.related_pid;
5748 child_pid = child_ptid.pid ();
5750 remote_detach_pid (child_pid);
5756 /* Target follow-exec function for remote targets. Save EXECD_PATHNAME
5757 in the program space of the new inferior. On entry and at return the
5758 current inferior is the exec'ing inferior. INF is the new exec'd
5759 inferior, which may be the same as the exec'ing inferior unless
5760 follow-exec-mode is "new". */
5763 remote_target::follow_exec (struct inferior *inf, char *execd_pathname)
5765 /* We know that this is a target file name, so if it has the "target:"
5766 prefix we strip it off before saving it in the program space. */
5767 if (is_target_filename (execd_pathname))
5768 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
5770 set_pspace_remote_exec_file (inf->pspace, execd_pathname);
5773 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
5776 remote_target::disconnect (const char *args, int from_tty)
5779 error (_("Argument given to \"disconnect\" when remotely debugging."));
5781 /* Make sure we unpush even the extended remote targets. Calling
5782 target_mourn_inferior won't unpush, and remote_mourn won't
5783 unpush if there is more than one inferior left. */
5784 unpush_target (this);
5785 generic_mourn_inferior ();
5788 puts_filtered ("Ending remote debugging.\n");
5791 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
5792 be chatty about it. */
5795 extended_remote_target::attach (const char *args, int from_tty)
5797 struct remote_state *rs = get_remote_state ();
5799 char *wait_status = NULL;
5801 pid = parse_pid_to_attach (args);
5803 /* Remote PID can be freely equal to getpid, do not check it here the same
5804 way as in other targets. */
5806 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
5807 error (_("This target does not support attaching to a process"));
5811 char *exec_file = get_exec_file (0);
5814 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
5815 target_pid_to_str (ptid_t (pid)));
5817 printf_unfiltered (_("Attaching to %s\n"),
5818 target_pid_to_str (ptid_t (pid)));
5820 gdb_flush (gdb_stdout);
5823 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
5825 getpkt (&rs->buf, &rs->buf_size, 0);
5827 switch (packet_ok (rs->buf,
5828 &remote_protocol_packets[PACKET_vAttach]))
5831 if (!target_is_non_stop_p ())
5833 /* Save the reply for later. */
5834 wait_status = (char *) alloca (strlen (rs->buf) + 1);
5835 strcpy (wait_status, rs->buf);
5837 else if (strcmp (rs->buf, "OK") != 0)
5838 error (_("Attaching to %s failed with: %s"),
5839 target_pid_to_str (ptid_t (pid)),
5842 case PACKET_UNKNOWN:
5843 error (_("This target does not support attaching to a process"));
5845 error (_("Attaching to %s failed"),
5846 target_pid_to_str (ptid_t (pid)));
5849 set_current_inferior (remote_add_inferior (0, pid, 1, 0));
5851 inferior_ptid = ptid_t (pid);
5853 if (target_is_non_stop_p ())
5855 struct thread_info *thread;
5857 /* Get list of threads. */
5858 update_thread_list ();
5860 thread = first_thread_of_inferior (current_inferior ());
5862 inferior_ptid = thread->ptid;
5864 inferior_ptid = ptid_t (pid);
5866 /* Invalidate our notion of the remote current thread. */
5867 record_currthread (rs, minus_one_ptid);
5871 /* Now, if we have thread information, update inferior_ptid. */
5872 inferior_ptid = remote_current_thread (inferior_ptid);
5874 /* Add the main thread to the thread list. */
5875 thread_info *thr = add_thread_silent (inferior_ptid);
5876 /* Don't consider the thread stopped until we've processed the
5877 saved stop reply. */
5878 set_executing (thr->ptid, true);
5881 /* Next, if the target can specify a description, read it. We do
5882 this before anything involving memory or registers. */
5883 target_find_description ();
5885 if (!target_is_non_stop_p ())
5887 /* Use the previously fetched status. */
5888 gdb_assert (wait_status != NULL);
5890 if (target_can_async_p ())
5892 struct notif_event *reply
5893 = remote_notif_parse (this, ¬if_client_stop, wait_status);
5895 push_stop_reply ((struct stop_reply *) reply);
5901 gdb_assert (wait_status != NULL);
5902 strcpy (rs->buf, wait_status);
5903 rs->cached_wait_status = 1;
5907 gdb_assert (wait_status == NULL);
5910 /* Implementation of the to_post_attach method. */
5913 extended_remote_target::post_attach (int pid)
5915 /* Get text, data & bss offsets. */
5918 /* In certain cases GDB might not have had the chance to start
5919 symbol lookup up until now. This could happen if the debugged
5920 binary is not using shared libraries, the vsyscall page is not
5921 present (on Linux) and the binary itself hadn't changed since the
5922 debugging process was started. */
5923 if (symfile_objfile != NULL)
5924 remote_check_symbols();
5928 /* Check for the availability of vCont. This function should also check
5932 remote_target::remote_vcont_probe ()
5934 remote_state *rs = get_remote_state ();
5937 strcpy (rs->buf, "vCont?");
5939 getpkt (&rs->buf, &rs->buf_size, 0);
5942 /* Make sure that the features we assume are supported. */
5943 if (startswith (buf, "vCont"))
5946 int support_c, support_C;
5948 rs->supports_vCont.s = 0;
5949 rs->supports_vCont.S = 0;
5952 rs->supports_vCont.t = 0;
5953 rs->supports_vCont.r = 0;
5954 while (p && *p == ';')
5957 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
5958 rs->supports_vCont.s = 1;
5959 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
5960 rs->supports_vCont.S = 1;
5961 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
5963 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
5965 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
5966 rs->supports_vCont.t = 1;
5967 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
5968 rs->supports_vCont.r = 1;
5970 p = strchr (p, ';');
5973 /* If c, and C are not all supported, we can't use vCont. Clearing
5974 BUF will make packet_ok disable the packet. */
5975 if (!support_c || !support_C)
5979 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
5982 /* Helper function for building "vCont" resumptions. Write a
5983 resumption to P. ENDP points to one-passed-the-end of the buffer
5984 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
5985 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
5986 resumed thread should be single-stepped and/or signalled. If PTID
5987 equals minus_one_ptid, then all threads are resumed; if PTID
5988 represents a process, then all threads of the process are resumed;
5989 the thread to be stepped and/or signalled is given in the global
5993 remote_target::append_resumption (char *p, char *endp,
5994 ptid_t ptid, int step, gdb_signal siggnal)
5996 struct remote_state *rs = get_remote_state ();
5998 if (step && siggnal != GDB_SIGNAL_0)
5999 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
6001 /* GDB is willing to range step. */
6002 && use_range_stepping
6003 /* Target supports range stepping. */
6004 && rs->supports_vCont.r
6005 /* We don't currently support range stepping multiple
6006 threads with a wildcard (though the protocol allows it,
6007 so stubs shouldn't make an active effort to forbid
6009 && !(remote_multi_process_p (rs) && ptid.is_pid ()))
6011 struct thread_info *tp;
6013 if (ptid == minus_one_ptid)
6015 /* If we don't know about the target thread's tid, then
6016 we're resuming magic_null_ptid (see caller). */
6017 tp = find_thread_ptid (magic_null_ptid);
6020 tp = find_thread_ptid (ptid);
6021 gdb_assert (tp != NULL);
6023 if (tp->control.may_range_step)
6025 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
6027 p += xsnprintf (p, endp - p, ";r%s,%s",
6028 phex_nz (tp->control.step_range_start,
6030 phex_nz (tp->control.step_range_end,
6034 p += xsnprintf (p, endp - p, ";s");
6037 p += xsnprintf (p, endp - p, ";s");
6038 else if (siggnal != GDB_SIGNAL_0)
6039 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
6041 p += xsnprintf (p, endp - p, ";c");
6043 if (remote_multi_process_p (rs) && ptid.is_pid ())
6047 /* All (-1) threads of process. */
6048 nptid = ptid_t (ptid.pid (), -1, 0);
6050 p += xsnprintf (p, endp - p, ":");
6051 p = write_ptid (p, endp, nptid);
6053 else if (ptid != minus_one_ptid)
6055 p += xsnprintf (p, endp - p, ":");
6056 p = write_ptid (p, endp, ptid);
6062 /* Clear the thread's private info on resume. */
6065 resume_clear_thread_private_info (struct thread_info *thread)
6067 if (thread->priv != NULL)
6069 remote_thread_info *priv = get_remote_thread_info (thread);
6071 priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6072 priv->watch_data_address = 0;
6076 /* Append a vCont continue-with-signal action for threads that have a
6077 non-zero stop signal. */
6080 remote_target::append_pending_thread_resumptions (char *p, char *endp,
6083 struct thread_info *thread;
6085 ALL_NON_EXITED_THREADS (thread)
6086 if (thread->ptid.matches (ptid)
6087 && inferior_ptid != thread->ptid
6088 && thread->suspend.stop_signal != GDB_SIGNAL_0)
6090 p = append_resumption (p, endp, thread->ptid,
6091 0, thread->suspend.stop_signal);
6092 thread->suspend.stop_signal = GDB_SIGNAL_0;
6093 resume_clear_thread_private_info (thread);
6099 /* Set the target running, using the packets that use Hc
6103 remote_target::remote_resume_with_hc (ptid_t ptid, int step,
6106 struct remote_state *rs = get_remote_state ();
6107 struct thread_info *thread;
6110 rs->last_sent_signal = siggnal;
6111 rs->last_sent_step = step;
6113 /* The c/s/C/S resume packets use Hc, so set the continue
6115 if (ptid == minus_one_ptid)
6116 set_continue_thread (any_thread_ptid);
6118 set_continue_thread (ptid);
6120 ALL_NON_EXITED_THREADS (thread)
6121 resume_clear_thread_private_info (thread);
6124 if (::execution_direction == EXEC_REVERSE)
6126 /* We don't pass signals to the target in reverse exec mode. */
6127 if (info_verbose && siggnal != GDB_SIGNAL_0)
6128 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
6131 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
6132 error (_("Remote reverse-step not supported."));
6133 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
6134 error (_("Remote reverse-continue not supported."));
6136 strcpy (buf, step ? "bs" : "bc");
6138 else if (siggnal != GDB_SIGNAL_0)
6140 buf[0] = step ? 'S' : 'C';
6141 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
6142 buf[2] = tohex (((int) siggnal) & 0xf);
6146 strcpy (buf, step ? "s" : "c");
6151 /* Resume the remote inferior by using a "vCont" packet. The thread
6152 to be resumed is PTID; STEP and SIGGNAL indicate whether the
6153 resumed thread should be single-stepped and/or signalled. If PTID
6154 equals minus_one_ptid, then all threads are resumed; the thread to
6155 be stepped and/or signalled is given in the global INFERIOR_PTID.
6156 This function returns non-zero iff it resumes the inferior.
6158 This function issues a strict subset of all possible vCont commands
6162 remote_target::remote_resume_with_vcont (ptid_t ptid, int step,
6163 enum gdb_signal siggnal)
6165 struct remote_state *rs = get_remote_state ();
6169 /* No reverse execution actions defined for vCont. */
6170 if (::execution_direction == EXEC_REVERSE)
6173 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6174 remote_vcont_probe ();
6176 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
6180 endp = rs->buf + get_remote_packet_size ();
6182 /* If we could generate a wider range of packets, we'd have to worry
6183 about overflowing BUF. Should there be a generic
6184 "multi-part-packet" packet? */
6186 p += xsnprintf (p, endp - p, "vCont");
6188 if (ptid == magic_null_ptid)
6190 /* MAGIC_NULL_PTID means that we don't have any active threads,
6191 so we don't have any TID numbers the inferior will
6192 understand. Make sure to only send forms that do not specify
6194 append_resumption (p, endp, minus_one_ptid, step, siggnal);
6196 else if (ptid == minus_one_ptid || ptid.is_pid ())
6198 /* Resume all threads (of all processes, or of a single
6199 process), with preference for INFERIOR_PTID. This assumes
6200 inferior_ptid belongs to the set of all threads we are about
6202 if (step || siggnal != GDB_SIGNAL_0)
6204 /* Step inferior_ptid, with or without signal. */
6205 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
6208 /* Also pass down any pending signaled resumption for other
6209 threads not the current. */
6210 p = append_pending_thread_resumptions (p, endp, ptid);
6212 /* And continue others without a signal. */
6213 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
6217 /* Scheduler locking; resume only PTID. */
6218 append_resumption (p, endp, ptid, step, siggnal);
6221 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
6224 if (target_is_non_stop_p ())
6226 /* In non-stop, the stub replies to vCont with "OK". The stop
6227 reply will be reported asynchronously by means of a `%Stop'
6229 getpkt (&rs->buf, &rs->buf_size, 0);
6230 if (strcmp (rs->buf, "OK") != 0)
6231 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
6237 /* Tell the remote machine to resume. */
6240 remote_target::resume (ptid_t ptid, int step, enum gdb_signal siggnal)
6242 struct remote_state *rs = get_remote_state ();
6244 /* When connected in non-stop mode, the core resumes threads
6245 individually. Resuming remote threads directly in target_resume
6246 would thus result in sending one packet per thread. Instead, to
6247 minimize roundtrip latency, here we just store the resume
6248 request; the actual remote resumption will be done in
6249 target_commit_resume / remote_commit_resume, where we'll be able
6250 to do vCont action coalescing. */
6251 if (target_is_non_stop_p () && ::execution_direction != EXEC_REVERSE)
6253 remote_thread_info *remote_thr;
6255 if (minus_one_ptid == ptid || ptid.is_pid ())
6256 remote_thr = get_remote_thread_info (inferior_ptid);
6258 remote_thr = get_remote_thread_info (ptid);
6260 remote_thr->last_resume_step = step;
6261 remote_thr->last_resume_sig = siggnal;
6265 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
6266 (explained in remote-notif.c:handle_notification) so
6267 remote_notif_process is not called. We need find a place where
6268 it is safe to start a 'vNotif' sequence. It is good to do it
6269 before resuming inferior, because inferior was stopped and no RSP
6270 traffic at that moment. */
6271 if (!target_is_non_stop_p ())
6272 remote_notif_process (rs->notif_state, ¬if_client_stop);
6274 rs->last_resume_exec_dir = ::execution_direction;
6276 /* Prefer vCont, and fallback to s/c/S/C, which use Hc. */
6277 if (!remote_resume_with_vcont (ptid, step, siggnal))
6278 remote_resume_with_hc (ptid, step, siggnal);
6280 /* We are about to start executing the inferior, let's register it
6281 with the event loop. NOTE: this is the one place where all the
6282 execution commands end up. We could alternatively do this in each
6283 of the execution commands in infcmd.c. */
6284 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
6285 into infcmd.c in order to allow inferior function calls to work
6286 NOT asynchronously. */
6287 if (target_can_async_p ())
6290 /* We've just told the target to resume. The remote server will
6291 wait for the inferior to stop, and then send a stop reply. In
6292 the mean time, we can't start another command/query ourselves
6293 because the stub wouldn't be ready to process it. This applies
6294 only to the base all-stop protocol, however. In non-stop (which
6295 only supports vCont), the stub replies with an "OK", and is
6296 immediate able to process further serial input. */
6297 if (!target_is_non_stop_p ())
6298 rs->waiting_for_stop_reply = 1;
6301 static int is_pending_fork_parent_thread (struct thread_info *thread);
6303 /* Private per-inferior info for target remote processes. */
6305 struct remote_inferior : public private_inferior
6307 /* Whether we can send a wildcard vCont for this process. */
6308 bool may_wildcard_vcont = true;
6311 /* Get the remote private inferior data associated to INF. */
6313 static remote_inferior *
6314 get_remote_inferior (inferior *inf)
6316 if (inf->priv == NULL)
6317 inf->priv.reset (new remote_inferior);
6319 return static_cast<remote_inferior *> (inf->priv.get ());
6322 /* Class used to track the construction of a vCont packet in the
6323 outgoing packet buffer. This is used to send multiple vCont
6324 packets if we have more actions than would fit a single packet. */
6329 explicit vcont_builder (remote_target *remote)
6336 void push_action (ptid_t ptid, bool step, gdb_signal siggnal);
6341 /* The remote target. */
6342 remote_target *m_remote;
6344 /* Pointer to the first action. P points here if no action has been
6346 char *m_first_action;
6348 /* Where the next action will be appended. */
6351 /* The end of the buffer. Must never write past this. */
6355 /* Prepare the outgoing buffer for a new vCont packet. */
6358 vcont_builder::restart ()
6360 struct remote_state *rs = m_remote->get_remote_state ();
6363 m_endp = rs->buf + m_remote->get_remote_packet_size ();
6364 m_p += xsnprintf (m_p, m_endp - m_p, "vCont");
6365 m_first_action = m_p;
6368 /* If the vCont packet being built has any action, send it to the
6372 vcont_builder::flush ()
6374 struct remote_state *rs;
6376 if (m_p == m_first_action)
6379 rs = m_remote->get_remote_state ();
6380 m_remote->putpkt (rs->buf);
6381 m_remote->getpkt (&rs->buf, &rs->buf_size, 0);
6382 if (strcmp (rs->buf, "OK") != 0)
6383 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
6386 /* The largest action is range-stepping, with its two addresses. This
6387 is more than sufficient. If a new, bigger action is created, it'll
6388 quickly trigger a failed assertion in append_resumption (and we'll
6390 #define MAX_ACTION_SIZE 200
6392 /* Append a new vCont action in the outgoing packet being built. If
6393 the action doesn't fit the packet along with previous actions, push
6394 what we've got so far to the remote end and start over a new vCont
6395 packet (with the new action). */
6398 vcont_builder::push_action (ptid_t ptid, bool step, gdb_signal siggnal)
6400 char buf[MAX_ACTION_SIZE + 1];
6402 char *endp = m_remote->append_resumption (buf, buf + sizeof (buf),
6403 ptid, step, siggnal);
6405 /* Check whether this new action would fit in the vCont packet along
6406 with previous actions. If not, send what we've got so far and
6407 start a new vCont packet. */
6408 size_t rsize = endp - buf;
6409 if (rsize > m_endp - m_p)
6414 /* Should now fit. */
6415 gdb_assert (rsize <= m_endp - m_p);
6418 memcpy (m_p, buf, rsize);
6423 /* to_commit_resume implementation. */
6426 remote_target::commit_resume ()
6428 struct inferior *inf;
6429 struct thread_info *tp;
6430 int any_process_wildcard;
6431 int may_global_wildcard_vcont;
6433 /* If connected in all-stop mode, we'd send the remote resume
6434 request directly from remote_resume. Likewise if
6435 reverse-debugging, as there are no defined vCont actions for
6436 reverse execution. */
6437 if (!target_is_non_stop_p () || ::execution_direction == EXEC_REVERSE)
6440 /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
6441 instead of resuming all threads of each process individually.
6442 However, if any thread of a process must remain halted, we can't
6443 send wildcard resumes and must send one action per thread.
6445 Care must be taken to not resume threads/processes the server
6446 side already told us are stopped, but the core doesn't know about
6447 yet, because the events are still in the vStopped notification
6450 #1 => vCont s:p1.1;c
6452 #3 <= %Stopped T05 p1.1
6457 #8 (infrun handles the stop for p1.1 and continues stepping)
6458 #9 => vCont s:p1.1;c
6460 The last vCont above would resume thread p1.2 by mistake, because
6461 the server has no idea that the event for p1.2 had not been
6464 The server side must similarly ignore resume actions for the
6465 thread that has a pending %Stopped notification (and any other
6466 threads with events pending), until GDB acks the notification
6467 with vStopped. Otherwise, e.g., the following case is
6470 #1 => g (or any other packet)
6472 #3 <= %Stopped T05 p1.2
6473 #4 => vCont s:p1.1;c
6476 Above, the server must not resume thread p1.2. GDB can't know
6477 that p1.2 stopped until it acks the %Stopped notification, and
6478 since from GDB's perspective all threads should be running, it
6481 Finally, special care must also be given to handling fork/vfork
6482 events. A (v)fork event actually tells us that two processes
6483 stopped -- the parent and the child. Until we follow the fork,
6484 we must not resume the child. Therefore, if we have a pending
6485 fork follow, we must not send a global wildcard resume action
6486 (vCont;c). We can still send process-wide wildcards though. */
6488 /* Start by assuming a global wildcard (vCont;c) is possible. */
6489 may_global_wildcard_vcont = 1;
6491 /* And assume every process is individually wildcard-able too. */
6492 ALL_NON_EXITED_INFERIORS (inf)
6494 remote_inferior *priv = get_remote_inferior (inf);
6496 priv->may_wildcard_vcont = true;
6499 /* Check for any pending events (not reported or processed yet) and
6500 disable process and global wildcard resumes appropriately. */
6501 check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
6503 ALL_NON_EXITED_THREADS (tp)
6505 /* If a thread of a process is not meant to be resumed, then we
6506 can't wildcard that process. */
6509 get_remote_inferior (tp->inf)->may_wildcard_vcont = false;
6511 /* And if we can't wildcard a process, we can't wildcard
6512 everything either. */
6513 may_global_wildcard_vcont = 0;
6517 /* If a thread is the parent of an unfollowed fork, then we
6518 can't do a global wildcard, as that would resume the fork
6520 if (is_pending_fork_parent_thread (tp))
6521 may_global_wildcard_vcont = 0;
6524 /* Now let's build the vCont packet(s). Actions must be appended
6525 from narrower to wider scopes (thread -> process -> global). If
6526 we end up with too many actions for a single packet vcont_builder
6527 flushes the current vCont packet to the remote side and starts a
6529 struct vcont_builder vcont_builder (this);
6531 /* Threads first. */
6532 ALL_NON_EXITED_THREADS (tp)
6534 remote_thread_info *remote_thr = get_remote_thread_info (tp);
6536 if (!tp->executing || remote_thr->vcont_resumed)
6539 gdb_assert (!thread_is_in_step_over_chain (tp));
6541 if (!remote_thr->last_resume_step
6542 && remote_thr->last_resume_sig == GDB_SIGNAL_0
6543 && get_remote_inferior (tp->inf)->may_wildcard_vcont)
6545 /* We'll send a wildcard resume instead. */
6546 remote_thr->vcont_resumed = 1;
6550 vcont_builder.push_action (tp->ptid,
6551 remote_thr->last_resume_step,
6552 remote_thr->last_resume_sig);
6553 remote_thr->vcont_resumed = 1;
6556 /* Now check whether we can send any process-wide wildcard. This is
6557 to avoid sending a global wildcard in the case nothing is
6558 supposed to be resumed. */
6559 any_process_wildcard = 0;
6561 ALL_NON_EXITED_INFERIORS (inf)
6563 if (get_remote_inferior (inf)->may_wildcard_vcont)
6565 any_process_wildcard = 1;
6570 if (any_process_wildcard)
6572 /* If all processes are wildcard-able, then send a single "c"
6573 action, otherwise, send an "all (-1) threads of process"
6574 continue action for each running process, if any. */
6575 if (may_global_wildcard_vcont)
6577 vcont_builder.push_action (minus_one_ptid,
6578 false, GDB_SIGNAL_0);
6582 ALL_NON_EXITED_INFERIORS (inf)
6584 if (get_remote_inferior (inf)->may_wildcard_vcont)
6586 vcont_builder.push_action (ptid_t (inf->pid),
6587 false, GDB_SIGNAL_0);
6593 vcont_builder.flush ();
6598 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
6599 thread, all threads of a remote process, or all threads of all
6603 remote_target::remote_stop_ns (ptid_t ptid)
6605 struct remote_state *rs = get_remote_state ();
6607 char *endp = rs->buf + get_remote_packet_size ();
6609 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6610 remote_vcont_probe ();
6612 if (!rs->supports_vCont.t)
6613 error (_("Remote server does not support stopping threads"));
6615 if (ptid == minus_one_ptid
6616 || (!remote_multi_process_p (rs) && ptid.is_pid ()))
6617 p += xsnprintf (p, endp - p, "vCont;t");
6622 p += xsnprintf (p, endp - p, "vCont;t:");
6625 /* All (-1) threads of process. */
6626 nptid = ptid_t (ptid.pid (), -1, 0);
6629 /* Small optimization: if we already have a stop reply for
6630 this thread, no use in telling the stub we want this
6632 if (peek_stop_reply (ptid))
6638 write_ptid (p, endp, nptid);
6641 /* In non-stop, we get an immediate OK reply. The stop reply will
6642 come in asynchronously by notification. */
6644 getpkt (&rs->buf, &rs->buf_size, 0);
6645 if (strcmp (rs->buf, "OK") != 0)
6646 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
6649 /* All-stop version of target_interrupt. Sends a break or a ^C to
6650 interrupt the remote target. It is undefined which thread of which
6651 process reports the interrupt. */
6654 remote_target::remote_interrupt_as ()
6656 struct remote_state *rs = get_remote_state ();
6658 rs->ctrlc_pending_p = 1;
6660 /* If the inferior is stopped already, but the core didn't know
6661 about it yet, just ignore the request. The cached wait status
6662 will be collected in remote_wait. */
6663 if (rs->cached_wait_status)
6666 /* Send interrupt_sequence to remote target. */
6667 send_interrupt_sequence ();
6670 /* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
6671 the remote target. It is undefined which thread of which process
6672 reports the interrupt. Throws an error if the packet is not
6673 supported by the server. */
6676 remote_target::remote_interrupt_ns ()
6678 struct remote_state *rs = get_remote_state ();
6680 char *endp = rs->buf + get_remote_packet_size ();
6682 xsnprintf (p, endp - p, "vCtrlC");
6684 /* In non-stop, we get an immediate OK reply. The stop reply will
6685 come in asynchronously by notification. */
6687 getpkt (&rs->buf, &rs->buf_size, 0);
6689 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
6693 case PACKET_UNKNOWN:
6694 error (_("No support for interrupting the remote target."));
6696 error (_("Interrupting target failed: %s"), rs->buf);
6700 /* Implement the to_stop function for the remote targets. */
6703 remote_target::stop (ptid_t ptid)
6706 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
6708 if (target_is_non_stop_p ())
6709 remote_stop_ns (ptid);
6712 /* We don't currently have a way to transparently pause the
6713 remote target in all-stop mode. Interrupt it instead. */
6714 remote_interrupt_as ();
6718 /* Implement the to_interrupt function for the remote targets. */
6721 remote_target::interrupt ()
6724 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
6726 if (target_is_non_stop_p ())
6727 remote_interrupt_ns ();
6729 remote_interrupt_as ();
6732 /* Implement the to_pass_ctrlc function for the remote targets. */
6735 remote_target::pass_ctrlc ()
6737 struct remote_state *rs = get_remote_state ();
6740 fprintf_unfiltered (gdb_stdlog, "remote_pass_ctrlc called\n");
6742 /* If we're starting up, we're not fully synced yet. Quit
6744 if (rs->starting_up)
6746 /* If ^C has already been sent once, offer to disconnect. */
6747 else if (rs->ctrlc_pending_p)
6750 target_interrupt ();
6753 /* Ask the user what to do when an interrupt is received. */
6756 remote_target::interrupt_query ()
6758 struct remote_state *rs = get_remote_state ();
6760 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
6762 if (query (_("The target is not responding to interrupt requests.\n"
6763 "Stop debugging it? ")))
6765 remote_unpush_target ();
6766 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
6771 if (query (_("Interrupted while waiting for the program.\n"
6772 "Give up waiting? ")))
6777 /* Enable/disable target terminal ownership. Most targets can use
6778 terminal groups to control terminal ownership. Remote targets are
6779 different in that explicit transfer of ownership to/from GDB/target
6783 remote_target::terminal_inferior ()
6785 /* NOTE: At this point we could also register our selves as the
6786 recipient of all input. Any characters typed could then be
6787 passed on down to the target. */
6791 remote_target::terminal_ours ()
6796 remote_console_output (char *msg)
6800 for (p = msg; p[0] && p[1]; p += 2)
6803 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
6807 fputs_unfiltered (tb, gdb_stdtarg);
6809 gdb_flush (gdb_stdtarg);
6812 DEF_VEC_O(cached_reg_t);
6814 typedef struct stop_reply
6816 struct notif_event base;
6818 /* The identifier of the thread about this event */
6821 /* The remote state this event is associated with. When the remote
6822 connection, represented by a remote_state object, is closed,
6823 all the associated stop_reply events should be released. */
6824 struct remote_state *rs;
6826 struct target_waitstatus ws;
6828 /* The architecture associated with the expedited registers. */
6831 /* Expedited registers. This makes remote debugging a bit more
6832 efficient for those targets that provide critical registers as
6833 part of their normal status mechanism (as another roundtrip to
6834 fetch them is avoided). */
6835 VEC(cached_reg_t) *regcache;
6837 enum target_stop_reason stop_reason;
6839 CORE_ADDR watch_data_address;
6845 stop_reply_xfree (struct stop_reply *r)
6847 notif_event_xfree ((struct notif_event *) r);
6850 /* Return the length of the stop reply queue. */
6853 remote_target::stop_reply_queue_length ()
6855 remote_state *rs = get_remote_state ();
6856 return rs->stop_reply_queue.size ();
6860 remote_notif_stop_parse (remote_target *remote,
6861 struct notif_client *self, char *buf,
6862 struct notif_event *event)
6864 remote->remote_parse_stop_reply (buf, (struct stop_reply *) event);
6868 remote_notif_stop_ack (remote_target *remote,
6869 struct notif_client *self, char *buf,
6870 struct notif_event *event)
6872 struct stop_reply *stop_reply = (struct stop_reply *) event;
6875 putpkt (remote, self->ack_command);
6877 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
6879 /* We got an unknown stop reply. */
6880 error (_("Unknown stop reply"));
6883 remote->push_stop_reply (stop_reply);
6887 remote_notif_stop_can_get_pending_events (remote_target *remote,
6888 struct notif_client *self)
6890 /* We can't get pending events in remote_notif_process for
6891 notification stop, and we have to do this in remote_wait_ns
6892 instead. If we fetch all queued events from stub, remote stub
6893 may exit and we have no chance to process them back in
6895 remote_state *rs = remote->get_remote_state ();
6896 mark_async_event_handler (rs->remote_async_inferior_event_token);
6901 stop_reply_dtr (struct notif_event *event)
6903 struct stop_reply *r = (struct stop_reply *) event;
6908 VEC_iterate (cached_reg_t, r->regcache, ix, reg);
6912 VEC_free (cached_reg_t, r->regcache);
6915 static struct notif_event *
6916 remote_notif_stop_alloc_reply (void)
6918 /* We cast to a pointer to the "base class". */
6919 struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
6921 r->dtr = stop_reply_dtr;
6926 /* A client of notification Stop. */
6928 struct notif_client notif_client_stop =
6932 remote_notif_stop_parse,
6933 remote_notif_stop_ack,
6934 remote_notif_stop_can_get_pending_events,
6935 remote_notif_stop_alloc_reply,
6939 /* Determine if THREAD_PTID is a pending fork parent thread. ARG contains
6940 the pid of the process that owns the threads we want to check, or
6941 -1 if we want to check all threads. */
6944 is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
6947 if (ws->kind == TARGET_WAITKIND_FORKED
6948 || ws->kind == TARGET_WAITKIND_VFORKED)
6950 if (event_pid == -1 || event_pid == thread_ptid.pid ())
6957 /* Return the thread's pending status used to determine whether the
6958 thread is a fork parent stopped at a fork event. */
6960 static struct target_waitstatus *
6961 thread_pending_fork_status (struct thread_info *thread)
6963 if (thread->suspend.waitstatus_pending_p)
6964 return &thread->suspend.waitstatus;
6966 return &thread->pending_follow;
6969 /* Determine if THREAD is a pending fork parent thread. */
6972 is_pending_fork_parent_thread (struct thread_info *thread)
6974 struct target_waitstatus *ws = thread_pending_fork_status (thread);
6977 return is_pending_fork_parent (ws, pid, thread->ptid);
6980 /* If CONTEXT contains any fork child threads that have not been
6981 reported yet, remove them from the CONTEXT list. If such a
6982 thread exists it is because we are stopped at a fork catchpoint
6983 and have not yet called follow_fork, which will set up the
6984 host-side data structures for the new process. */
6987 remote_target::remove_new_fork_children (threads_listing_context *context)
6989 struct thread_info * thread;
6991 struct notif_client *notif = ¬if_client_stop;
6993 /* For any threads stopped at a fork event, remove the corresponding
6994 fork child threads from the CONTEXT list. */
6995 ALL_NON_EXITED_THREADS (thread)
6997 struct target_waitstatus *ws = thread_pending_fork_status (thread);
6999 if (is_pending_fork_parent (ws, pid, thread->ptid))
7000 context->remove_thread (ws->value.related_pid);
7003 /* Check for any pending fork events (not reported or processed yet)
7004 in process PID and remove those fork child threads from the
7005 CONTEXT list as well. */
7006 remote_notif_get_pending_events (notif);
7007 for (auto &event : get_remote_state ()->stop_reply_queue)
7008 if (event->ws.kind == TARGET_WAITKIND_FORKED
7009 || event->ws.kind == TARGET_WAITKIND_VFORKED
7010 || event->ws.kind == TARGET_WAITKIND_THREAD_EXITED)
7011 context->remove_thread (event->ws.value.related_pid);
7014 /* Check whether any event pending in the vStopped queue would prevent
7015 a global or process wildcard vCont action. Clear
7016 *may_global_wildcard if we can't do a global wildcard (vCont;c),
7017 and clear the event inferior's may_wildcard_vcont flag if we can't
7018 do a process-wide wildcard resume (vCont;c:pPID.-1). */
7021 remote_target::check_pending_events_prevent_wildcard_vcont
7022 (int *may_global_wildcard)
7024 struct notif_client *notif = ¬if_client_stop;
7026 remote_notif_get_pending_events (notif);
7027 for (auto &event : get_remote_state ()->stop_reply_queue)
7029 if (event->ws.kind == TARGET_WAITKIND_NO_RESUMED
7030 || event->ws.kind == TARGET_WAITKIND_NO_HISTORY)
7033 if (event->ws.kind == TARGET_WAITKIND_FORKED
7034 || event->ws.kind == TARGET_WAITKIND_VFORKED)
7035 *may_global_wildcard = 0;
7037 struct inferior *inf = find_inferior_ptid (event->ptid);
7039 /* This may be the first time we heard about this process.
7040 Regardless, we must not do a global wildcard resume, otherwise
7041 we'd resume this process too. */
7042 *may_global_wildcard = 0;
7044 get_remote_inferior (inf)->may_wildcard_vcont = false;
7048 /* Discard all pending stop replies of inferior INF. */
7051 remote_target::discard_pending_stop_replies (struct inferior *inf)
7053 struct stop_reply *reply;
7054 struct remote_state *rs = get_remote_state ();
7055 struct remote_notif_state *rns = rs->notif_state;
7057 /* This function can be notified when an inferior exists. When the
7058 target is not remote, the notification state is NULL. */
7059 if (rs->remote_desc == NULL)
7062 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
7064 /* Discard the in-flight notification. */
7065 if (reply != NULL && reply->ptid.pid () == inf->pid)
7067 stop_reply_xfree (reply);
7068 rns->pending_event[notif_client_stop.id] = NULL;
7071 /* Discard the stop replies we have already pulled with
7073 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7074 rs->stop_reply_queue.end (),
7075 [=] (const stop_reply_up &event)
7077 return event->ptid.pid () == inf->pid;
7079 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7082 /* Discard the stop replies for RS in stop_reply_queue. */
7085 remote_target::discard_pending_stop_replies_in_queue ()
7087 remote_state *rs = get_remote_state ();
7089 /* Discard the stop replies we have already pulled with
7091 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7092 rs->stop_reply_queue.end (),
7093 [=] (const stop_reply_up &event)
7095 return event->rs == rs;
7097 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7100 /* Remove the first reply in 'stop_reply_queue' which matches
7104 remote_target::remote_notif_remove_queued_reply (ptid_t ptid)
7106 remote_state *rs = get_remote_state ();
7108 auto iter = std::find_if (rs->stop_reply_queue.begin (),
7109 rs->stop_reply_queue.end (),
7110 [=] (const stop_reply_up &event)
7112 return event->ptid.matches (ptid);
7114 struct stop_reply *result;
7115 if (iter == rs->stop_reply_queue.end ())
7119 result = iter->release ();
7120 rs->stop_reply_queue.erase (iter);
7124 fprintf_unfiltered (gdb_stdlog,
7125 "notif: discard queued event: 'Stop' in %s\n",
7126 target_pid_to_str (ptid));
7131 /* Look for a queued stop reply belonging to PTID. If one is found,
7132 remove it from the queue, and return it. Returns NULL if none is
7133 found. If there are still queued events left to process, tell the
7134 event loop to get back to target_wait soon. */
7137 remote_target::queued_stop_reply (ptid_t ptid)
7139 remote_state *rs = get_remote_state ();
7140 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
7142 if (!rs->stop_reply_queue.empty ())
7144 /* There's still at least an event left. */
7145 mark_async_event_handler (rs->remote_async_inferior_event_token);
7151 /* Push a fully parsed stop reply in the stop reply queue. Since we
7152 know that we now have at least one queued event left to pass to the
7153 core side, tell the event loop to get back to target_wait soon. */
7156 remote_target::push_stop_reply (struct stop_reply *new_event)
7158 remote_state *rs = get_remote_state ();
7159 rs->stop_reply_queue.push_back (stop_reply_up (new_event));
7162 fprintf_unfiltered (gdb_stdlog,
7163 "notif: push 'Stop' %s to queue %d\n",
7164 target_pid_to_str (new_event->ptid),
7165 int (rs->stop_reply_queue.size ()));
7167 mark_async_event_handler (rs->remote_async_inferior_event_token);
7170 /* Returns true if we have a stop reply for PTID. */
7173 remote_target::peek_stop_reply (ptid_t ptid)
7175 remote_state *rs = get_remote_state ();
7176 for (auto &event : rs->stop_reply_queue)
7177 if (ptid == event->ptid
7178 && event->ws.kind == TARGET_WAITKIND_STOPPED)
7183 /* Helper for remote_parse_stop_reply. Return nonzero if the substring
7184 starting with P and ending with PEND matches PREFIX. */
7187 strprefix (const char *p, const char *pend, const char *prefix)
7189 for ( ; p < pend; p++, prefix++)
7192 return *prefix == '\0';
7195 /* Parse the stop reply in BUF. Either the function succeeds, and the
7196 result is stored in EVENT, or throws an error. */
7199 remote_target::remote_parse_stop_reply (char *buf, stop_reply *event)
7201 remote_arch_state *rsa = NULL;
7206 event->ptid = null_ptid;
7207 event->rs = get_remote_state ();
7208 event->ws.kind = TARGET_WAITKIND_IGNORE;
7209 event->ws.value.integer = 0;
7210 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
7211 event->regcache = NULL;
7216 case 'T': /* Status with PC, SP, FP, ... */
7217 /* Expedited reply, containing Signal, {regno, reg} repeat. */
7218 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
7220 n... = register number
7221 r... = register contents
7224 p = &buf[3]; /* after Txx */
7230 p1 = strchr (p, ':');
7232 error (_("Malformed packet(a) (missing colon): %s\n\
7236 error (_("Malformed packet(a) (missing register number): %s\n\
7240 /* Some "registers" are actually extended stop information.
7241 Note if you're adding a new entry here: GDB 7.9 and
7242 earlier assume that all register "numbers" that start
7243 with an hex digit are real register numbers. Make sure
7244 the server only sends such a packet if it knows the
7245 client understands it. */
7247 if (strprefix (p, p1, "thread"))
7248 event->ptid = read_ptid (++p1, &p);
7249 else if (strprefix (p, p1, "syscall_entry"))
7253 event->ws.kind = TARGET_WAITKIND_SYSCALL_ENTRY;
7254 p = unpack_varlen_hex (++p1, &sysno);
7255 event->ws.value.syscall_number = (int) sysno;
7257 else if (strprefix (p, p1, "syscall_return"))
7261 event->ws.kind = TARGET_WAITKIND_SYSCALL_RETURN;
7262 p = unpack_varlen_hex (++p1, &sysno);
7263 event->ws.value.syscall_number = (int) sysno;
7265 else if (strprefix (p, p1, "watch")
7266 || strprefix (p, p1, "rwatch")
7267 || strprefix (p, p1, "awatch"))
7269 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
7270 p = unpack_varlen_hex (++p1, &addr);
7271 event->watch_data_address = (CORE_ADDR) addr;
7273 else if (strprefix (p, p1, "swbreak"))
7275 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
7277 /* Make sure the stub doesn't forget to indicate support
7279 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
7280 error (_("Unexpected swbreak stop reason"));
7282 /* The value part is documented as "must be empty",
7283 though we ignore it, in case we ever decide to make
7284 use of it in a backward compatible way. */
7285 p = strchrnul (p1 + 1, ';');
7287 else if (strprefix (p, p1, "hwbreak"))
7289 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
7291 /* Make sure the stub doesn't forget to indicate support
7293 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
7294 error (_("Unexpected hwbreak stop reason"));
7297 p = strchrnul (p1 + 1, ';');
7299 else if (strprefix (p, p1, "library"))
7301 event->ws.kind = TARGET_WAITKIND_LOADED;
7302 p = strchrnul (p1 + 1, ';');
7304 else if (strprefix (p, p1, "replaylog"))
7306 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
7307 /* p1 will indicate "begin" or "end", but it makes
7308 no difference for now, so ignore it. */
7309 p = strchrnul (p1 + 1, ';');
7311 else if (strprefix (p, p1, "core"))
7315 p = unpack_varlen_hex (++p1, &c);
7318 else if (strprefix (p, p1, "fork"))
7320 event->ws.value.related_pid = read_ptid (++p1, &p);
7321 event->ws.kind = TARGET_WAITKIND_FORKED;
7323 else if (strprefix (p, p1, "vfork"))
7325 event->ws.value.related_pid = read_ptid (++p1, &p);
7326 event->ws.kind = TARGET_WAITKIND_VFORKED;
7328 else if (strprefix (p, p1, "vforkdone"))
7330 event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
7331 p = strchrnul (p1 + 1, ';');
7333 else if (strprefix (p, p1, "exec"))
7336 char pathname[PATH_MAX];
7339 /* Determine the length of the execd pathname. */
7340 p = unpack_varlen_hex (++p1, &ignored);
7341 pathlen = (p - p1) / 2;
7343 /* Save the pathname for event reporting and for
7344 the next run command. */
7345 hex2bin (p1, (gdb_byte *) pathname, pathlen);
7346 pathname[pathlen] = '\0';
7348 /* This is freed during event handling. */
7349 event->ws.value.execd_pathname = xstrdup (pathname);
7350 event->ws.kind = TARGET_WAITKIND_EXECD;
7352 /* Skip the registers included in this packet, since
7353 they may be for an architecture different from the
7354 one used by the original program. */
7357 else if (strprefix (p, p1, "create"))
7359 event->ws.kind = TARGET_WAITKIND_THREAD_CREATED;
7360 p = strchrnul (p1 + 1, ';');
7369 p = strchrnul (p1 + 1, ';');
7374 /* Maybe a real ``P'' register number. */
7375 p_temp = unpack_varlen_hex (p, &pnum);
7376 /* If the first invalid character is the colon, we got a
7377 register number. Otherwise, it's an unknown stop
7381 /* If we haven't parsed the event's thread yet, find
7382 it now, in order to find the architecture of the
7383 reported expedited registers. */
7384 if (event->ptid == null_ptid)
7386 const char *thr = strstr (p1 + 1, ";thread:");
7388 event->ptid = read_ptid (thr + strlen (";thread:"),
7392 /* Either the current thread hasn't changed,
7393 or the inferior is not multi-threaded.
7394 The event must be for the thread we last
7395 set as (or learned as being) current. */
7396 event->ptid = event->rs->general_thread;
7402 inferior *inf = (event->ptid == null_ptid
7404 : find_inferior_ptid (event->ptid));
7405 /* If this is the first time we learn anything
7406 about this process, skip the registers
7407 included in this packet, since we don't yet
7408 know which architecture to use to parse them.
7409 We'll determine the architecture later when
7410 we process the stop reply and retrieve the
7411 target description, via
7412 remote_notice_new_inferior ->
7413 post_create_inferior. */
7416 p = strchrnul (p1 + 1, ';');
7421 event->arch = inf->gdbarch;
7422 rsa = event->rs->get_remote_arch_state (event->arch);
7426 = packet_reg_from_pnum (event->arch, rsa, pnum);
7427 cached_reg_t cached_reg;
7430 error (_("Remote sent bad register number %s: %s\n\
7432 hex_string (pnum), p, buf);
7434 cached_reg.num = reg->regnum;
7435 cached_reg.data = (gdb_byte *)
7436 xmalloc (register_size (event->arch, reg->regnum));
7439 fieldsize = hex2bin (p, cached_reg.data,
7440 register_size (event->arch, reg->regnum));
7442 if (fieldsize < register_size (event->arch, reg->regnum))
7443 warning (_("Remote reply is too short: %s"), buf);
7445 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
7449 /* Not a number. Silently skip unknown optional
7451 p = strchrnul (p1 + 1, ';');
7456 error (_("Remote register badly formatted: %s\nhere: %s"),
7461 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
7465 case 'S': /* Old style status, just signal only. */
7469 event->ws.kind = TARGET_WAITKIND_STOPPED;
7470 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
7471 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
7472 event->ws.value.sig = (enum gdb_signal) sig;
7474 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
7477 case 'w': /* Thread exited. */
7482 event->ws.kind = TARGET_WAITKIND_THREAD_EXITED;
7483 p = unpack_varlen_hex (&buf[1], &value);
7484 event->ws.value.integer = value;
7486 error (_("stop reply packet badly formatted: %s"), buf);
7487 event->ptid = read_ptid (++p, NULL);
7490 case 'W': /* Target exited. */
7497 /* GDB used to accept only 2 hex chars here. Stubs should
7498 only send more if they detect GDB supports multi-process
7500 p = unpack_varlen_hex (&buf[1], &value);
7504 /* The remote process exited. */
7505 event->ws.kind = TARGET_WAITKIND_EXITED;
7506 event->ws.value.integer = value;
7510 /* The remote process exited with a signal. */
7511 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
7512 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
7513 event->ws.value.sig = (enum gdb_signal) value;
7515 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
7518 /* If no process is specified, assume inferior_ptid. */
7519 pid = inferior_ptid.pid ();
7528 else if (startswith (p, "process:"))
7532 p += sizeof ("process:") - 1;
7533 unpack_varlen_hex (p, &upid);
7537 error (_("unknown stop reply packet: %s"), buf);
7540 error (_("unknown stop reply packet: %s"), buf);
7541 event->ptid = ptid_t (pid);
7545 event->ws.kind = TARGET_WAITKIND_NO_RESUMED;
7546 event->ptid = minus_one_ptid;
7550 if (target_is_non_stop_p () && event->ptid == null_ptid)
7551 error (_("No process or thread specified in stop reply: %s"), buf);
7554 /* When the stub wants to tell GDB about a new notification reply, it
7555 sends a notification (%Stop, for example). Those can come it at
7556 any time, hence, we have to make sure that any pending
7557 putpkt/getpkt sequence we're making is finished, before querying
7558 the stub for more events with the corresponding ack command
7559 (vStopped, for example). E.g., if we started a vStopped sequence
7560 immediately upon receiving the notification, something like this
7568 1.6) <-- (registers reply to step #1.3)
7570 Obviously, the reply in step #1.6 would be unexpected to a vStopped
7573 To solve this, whenever we parse a %Stop notification successfully,
7574 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
7575 doing whatever we were doing:
7581 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
7582 2.5) <-- (registers reply to step #2.3)
7584 Eventualy after step #2.5, we return to the event loop, which
7585 notices there's an event on the
7586 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
7587 associated callback --- the function below. At this point, we're
7588 always safe to start a vStopped sequence. :
7591 2.7) <-- T05 thread:2
7597 remote_target::remote_notif_get_pending_events (notif_client *nc)
7599 struct remote_state *rs = get_remote_state ();
7601 if (rs->notif_state->pending_event[nc->id] != NULL)
7604 fprintf_unfiltered (gdb_stdlog,
7605 "notif: process: '%s' ack pending event\n",
7609 nc->ack (this, nc, rs->buf, rs->notif_state->pending_event[nc->id]);
7610 rs->notif_state->pending_event[nc->id] = NULL;
7614 getpkt (&rs->buf, &rs->buf_size, 0);
7615 if (strcmp (rs->buf, "OK") == 0)
7618 remote_notif_ack (this, nc, rs->buf);
7624 fprintf_unfiltered (gdb_stdlog,
7625 "notif: process: '%s' no pending reply\n",
7630 /* Wrapper around remote_target::remote_notif_get_pending_events to
7631 avoid having to export the whole remote_target class. */
7634 remote_notif_get_pending_events (remote_target *remote, notif_client *nc)
7636 remote->remote_notif_get_pending_events (nc);
7639 /* Called when it is decided that STOP_REPLY holds the info of the
7640 event that is to be returned to the core. This function always
7641 destroys STOP_REPLY. */
7644 remote_target::process_stop_reply (struct stop_reply *stop_reply,
7645 struct target_waitstatus *status)
7649 *status = stop_reply->ws;
7650 ptid = stop_reply->ptid;
7652 /* If no thread/process was reported by the stub, assume the current
7654 if (ptid == null_ptid)
7655 ptid = inferior_ptid;
7657 if (status->kind != TARGET_WAITKIND_EXITED
7658 && status->kind != TARGET_WAITKIND_SIGNALLED
7659 && status->kind != TARGET_WAITKIND_NO_RESUMED)
7661 /* Expedited registers. */
7662 if (stop_reply->regcache)
7664 struct regcache *regcache
7665 = get_thread_arch_regcache (ptid, stop_reply->arch);
7670 VEC_iterate (cached_reg_t, stop_reply->regcache, ix, reg);
7673 regcache->raw_supply (reg->num, reg->data);
7677 VEC_free (cached_reg_t, stop_reply->regcache);
7680 remote_notice_new_inferior (ptid, 0);
7681 remote_thread_info *remote_thr = get_remote_thread_info (ptid);
7682 remote_thr->core = stop_reply->core;
7683 remote_thr->stop_reason = stop_reply->stop_reason;
7684 remote_thr->watch_data_address = stop_reply->watch_data_address;
7685 remote_thr->vcont_resumed = 0;
7688 stop_reply_xfree (stop_reply);
7692 /* The non-stop mode version of target_wait. */
7695 remote_target::wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
7697 struct remote_state *rs = get_remote_state ();
7698 struct stop_reply *stop_reply;
7702 /* If in non-stop mode, get out of getpkt even if a
7703 notification is received. */
7705 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7706 0 /* forever */, &is_notif);
7709 if (ret != -1 && !is_notif)
7712 case 'E': /* Error of some sort. */
7713 /* We're out of sync with the target now. Did it continue
7714 or not? We can't tell which thread it was in non-stop,
7715 so just ignore this. */
7716 warning (_("Remote failure reply: %s"), rs->buf);
7718 case 'O': /* Console output. */
7719 remote_console_output (rs->buf + 1);
7722 warning (_("Invalid remote reply: %s"), rs->buf);
7726 /* Acknowledge a pending stop reply that may have arrived in the
7728 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
7729 remote_notif_get_pending_events (¬if_client_stop);
7731 /* If indeed we noticed a stop reply, we're done. */
7732 stop_reply = queued_stop_reply (ptid);
7733 if (stop_reply != NULL)
7734 return process_stop_reply (stop_reply, status);
7736 /* Still no event. If we're just polling for an event, then
7737 return to the event loop. */
7738 if (options & TARGET_WNOHANG)
7740 status->kind = TARGET_WAITKIND_IGNORE;
7741 return minus_one_ptid;
7744 /* Otherwise do a blocking wait. */
7745 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7746 1 /* forever */, &is_notif);
7750 /* Wait until the remote machine stops, then return, storing status in
7751 STATUS just as `wait' would. */
7754 remote_target::wait_as (ptid_t ptid, target_waitstatus *status, int options)
7756 struct remote_state *rs = get_remote_state ();
7757 ptid_t event_ptid = null_ptid;
7759 struct stop_reply *stop_reply;
7763 status->kind = TARGET_WAITKIND_IGNORE;
7764 status->value.integer = 0;
7766 stop_reply = queued_stop_reply (ptid);
7767 if (stop_reply != NULL)
7768 return process_stop_reply (stop_reply, status);
7770 if (rs->cached_wait_status)
7771 /* Use the cached wait status, but only once. */
7772 rs->cached_wait_status = 0;
7777 int forever = ((options & TARGET_WNOHANG) == 0
7778 && rs->wait_forever_enabled_p);
7780 if (!rs->waiting_for_stop_reply)
7782 status->kind = TARGET_WAITKIND_NO_RESUMED;
7783 return minus_one_ptid;
7786 /* FIXME: cagney/1999-09-27: If we're in async mode we should
7787 _never_ wait for ever -> test on target_is_async_p().
7788 However, before we do that we need to ensure that the caller
7789 knows how to take the target into/out of async mode. */
7790 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7791 forever, &is_notif);
7793 /* GDB gets a notification. Return to core as this event is
7795 if (ret != -1 && is_notif)
7796 return minus_one_ptid;
7798 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
7799 return minus_one_ptid;
7804 /* Assume that the target has acknowledged Ctrl-C unless we receive
7805 an 'F' or 'O' packet. */
7806 if (buf[0] != 'F' && buf[0] != 'O')
7807 rs->ctrlc_pending_p = 0;
7811 case 'E': /* Error of some sort. */
7812 /* We're out of sync with the target now. Did it continue or
7813 not? Not is more likely, so report a stop. */
7814 rs->waiting_for_stop_reply = 0;
7816 warning (_("Remote failure reply: %s"), buf);
7817 status->kind = TARGET_WAITKIND_STOPPED;
7818 status->value.sig = GDB_SIGNAL_0;
7820 case 'F': /* File-I/O request. */
7821 /* GDB may access the inferior memory while handling the File-I/O
7822 request, but we don't want GDB accessing memory while waiting
7823 for a stop reply. See the comments in putpkt_binary. Set
7824 waiting_for_stop_reply to 0 temporarily. */
7825 rs->waiting_for_stop_reply = 0;
7826 remote_fileio_request (this, buf, rs->ctrlc_pending_p);
7827 rs->ctrlc_pending_p = 0;
7828 /* GDB handled the File-I/O request, and the target is running
7829 again. Keep waiting for events. */
7830 rs->waiting_for_stop_reply = 1;
7832 case 'N': case 'T': case 'S': case 'X': case 'W':
7834 struct stop_reply *stop_reply;
7836 /* There is a stop reply to handle. */
7837 rs->waiting_for_stop_reply = 0;
7840 = (struct stop_reply *) remote_notif_parse (this,
7844 event_ptid = process_stop_reply (stop_reply, status);
7847 case 'O': /* Console output. */
7848 remote_console_output (buf + 1);
7851 if (rs->last_sent_signal != GDB_SIGNAL_0)
7853 /* Zero length reply means that we tried 'S' or 'C' and the
7854 remote system doesn't support it. */
7855 target_terminal::ours_for_output ();
7857 ("Can't send signals to this remote system. %s not sent.\n",
7858 gdb_signal_to_name (rs->last_sent_signal));
7859 rs->last_sent_signal = GDB_SIGNAL_0;
7860 target_terminal::inferior ();
7862 strcpy (buf, rs->last_sent_step ? "s" : "c");
7868 warning (_("Invalid remote reply: %s"), buf);
7872 if (status->kind == TARGET_WAITKIND_NO_RESUMED)
7873 return minus_one_ptid;
7874 else if (status->kind == TARGET_WAITKIND_IGNORE)
7876 /* Nothing interesting happened. If we're doing a non-blocking
7877 poll, we're done. Otherwise, go back to waiting. */
7878 if (options & TARGET_WNOHANG)
7879 return minus_one_ptid;
7883 else if (status->kind != TARGET_WAITKIND_EXITED
7884 && status->kind != TARGET_WAITKIND_SIGNALLED)
7886 if (event_ptid != null_ptid)
7887 record_currthread (rs, event_ptid);
7889 event_ptid = inferior_ptid;
7892 /* A process exit. Invalidate our notion of current thread. */
7893 record_currthread (rs, minus_one_ptid);
7898 /* Wait until the remote machine stops, then return, storing status in
7899 STATUS just as `wait' would. */
7902 remote_target::wait (ptid_t ptid, struct target_waitstatus *status, int options)
7906 if (target_is_non_stop_p ())
7907 event_ptid = wait_ns (ptid, status, options);
7909 event_ptid = wait_as (ptid, status, options);
7911 if (target_is_async_p ())
7913 remote_state *rs = get_remote_state ();
7915 /* If there are are events left in the queue tell the event loop
7917 if (!rs->stop_reply_queue.empty ())
7918 mark_async_event_handler (rs->remote_async_inferior_event_token);
7924 /* Fetch a single register using a 'p' packet. */
7927 remote_target::fetch_register_using_p (struct regcache *regcache,
7930 struct gdbarch *gdbarch = regcache->arch ();
7931 struct remote_state *rs = get_remote_state ();
7933 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
7936 if (packet_support (PACKET_p) == PACKET_DISABLE)
7939 if (reg->pnum == -1)
7944 p += hexnumstr (p, reg->pnum);
7947 getpkt (&rs->buf, &rs->buf_size, 0);
7951 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
7955 case PACKET_UNKNOWN:
7958 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
7959 gdbarch_register_name (regcache->arch (),
7964 /* If this register is unfetchable, tell the regcache. */
7967 regcache->raw_supply (reg->regnum, NULL);
7971 /* Otherwise, parse and supply the value. */
7977 error (_("fetch_register_using_p: early buf termination"));
7979 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
7982 regcache->raw_supply (reg->regnum, regp);
7986 /* Fetch the registers included in the target's 'g' packet. */
7989 remote_target::send_g_packet ()
7991 struct remote_state *rs = get_remote_state ();
7994 xsnprintf (rs->buf, get_remote_packet_size (), "g");
7996 getpkt (&rs->buf, &rs->buf_size, 0);
7997 if (packet_check_result (rs->buf) == PACKET_ERROR)
7998 error (_("Could not read registers; remote failure reply '%s'"),
8001 /* We can get out of synch in various cases. If the first character
8002 in the buffer is not a hex character, assume that has happened
8003 and try to fetch another packet to read. */
8004 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
8005 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
8006 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
8007 && rs->buf[0] != 'x') /* New: unavailable register value. */
8010 fprintf_unfiltered (gdb_stdlog,
8011 "Bad register packet; fetching a new packet\n");
8012 getpkt (&rs->buf, &rs->buf_size, 0);
8015 buf_len = strlen (rs->buf);
8017 /* Sanity check the received packet. */
8018 if (buf_len % 2 != 0)
8019 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
8025 remote_target::process_g_packet (struct regcache *regcache)
8027 struct gdbarch *gdbarch = regcache->arch ();
8028 struct remote_state *rs = get_remote_state ();
8029 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8034 buf_len = strlen (rs->buf);
8036 /* Further sanity checks, with knowledge of the architecture. */
8037 if (buf_len > 2 * rsa->sizeof_g_packet)
8038 error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
8039 "bytes): %s"), rsa->sizeof_g_packet, buf_len / 2, rs->buf);
8041 /* Save the size of the packet sent to us by the target. It is used
8042 as a heuristic when determining the max size of packets that the
8043 target can safely receive. */
8044 if (rsa->actual_register_packet_size == 0)
8045 rsa->actual_register_packet_size = buf_len;
8047 /* If this is smaller than we guessed the 'g' packet would be,
8048 update our records. A 'g' reply that doesn't include a register's
8049 value implies either that the register is not available, or that
8050 the 'p' packet must be used. */
8051 if (buf_len < 2 * rsa->sizeof_g_packet)
8053 long sizeof_g_packet = buf_len / 2;
8055 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8057 long offset = rsa->regs[i].offset;
8058 long reg_size = register_size (gdbarch, i);
8060 if (rsa->regs[i].pnum == -1)
8063 if (offset >= sizeof_g_packet)
8064 rsa->regs[i].in_g_packet = 0;
8065 else if (offset + reg_size > sizeof_g_packet)
8066 error (_("Truncated register %d in remote 'g' packet"), i);
8068 rsa->regs[i].in_g_packet = 1;
8071 /* Looks valid enough, we can assume this is the correct length
8072 for a 'g' packet. It's important not to adjust
8073 rsa->sizeof_g_packet if we have truncated registers otherwise
8074 this "if" won't be run the next time the method is called
8075 with a packet of the same size and one of the internal errors
8076 below will trigger instead. */
8077 rsa->sizeof_g_packet = sizeof_g_packet;
8080 regs = (char *) alloca (rsa->sizeof_g_packet);
8082 /* Unimplemented registers read as all bits zero. */
8083 memset (regs, 0, rsa->sizeof_g_packet);
8085 /* Reply describes registers byte by byte, each byte encoded as two
8086 hex characters. Suck them all up, then supply them to the
8087 register cacheing/storage mechanism. */
8090 for (i = 0; i < rsa->sizeof_g_packet; i++)
8092 if (p[0] == 0 || p[1] == 0)
8093 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
8094 internal_error (__FILE__, __LINE__,
8095 _("unexpected end of 'g' packet reply"));
8097 if (p[0] == 'x' && p[1] == 'x')
8098 regs[i] = 0; /* 'x' */
8100 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
8104 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8106 struct packet_reg *r = &rsa->regs[i];
8107 long reg_size = register_size (gdbarch, i);
8111 if ((r->offset + reg_size) * 2 > strlen (rs->buf))
8112 /* This shouldn't happen - we adjusted in_g_packet above. */
8113 internal_error (__FILE__, __LINE__,
8114 _("unexpected end of 'g' packet reply"));
8115 else if (rs->buf[r->offset * 2] == 'x')
8117 gdb_assert (r->offset * 2 < strlen (rs->buf));
8118 /* The register isn't available, mark it as such (at
8119 the same time setting the value to zero). */
8120 regcache->raw_supply (r->regnum, NULL);
8123 regcache->raw_supply (r->regnum, regs + r->offset);
8129 remote_target::fetch_registers_using_g (struct regcache *regcache)
8132 process_g_packet (regcache);
8135 /* Make the remote selected traceframe match GDB's selected
8139 remote_target::set_remote_traceframe ()
8142 struct remote_state *rs = get_remote_state ();
8144 if (rs->remote_traceframe_number == get_traceframe_number ())
8147 /* Avoid recursion, remote_trace_find calls us again. */
8148 rs->remote_traceframe_number = get_traceframe_number ();
8150 newnum = target_trace_find (tfind_number,
8151 get_traceframe_number (), 0, 0, NULL);
8153 /* Should not happen. If it does, all bets are off. */
8154 if (newnum != get_traceframe_number ())
8155 warning (_("could not set remote traceframe"));
8159 remote_target::fetch_registers (struct regcache *regcache, int regnum)
8161 struct gdbarch *gdbarch = regcache->arch ();
8162 struct remote_state *rs = get_remote_state ();
8163 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8166 set_remote_traceframe ();
8167 set_general_thread (regcache->ptid ());
8171 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8173 gdb_assert (reg != NULL);
8175 /* If this register might be in the 'g' packet, try that first -
8176 we are likely to read more than one register. If this is the
8177 first 'g' packet, we might be overly optimistic about its
8178 contents, so fall back to 'p'. */
8179 if (reg->in_g_packet)
8181 fetch_registers_using_g (regcache);
8182 if (reg->in_g_packet)
8186 if (fetch_register_using_p (regcache, reg))
8189 /* This register is not available. */
8190 regcache->raw_supply (reg->regnum, NULL);
8195 fetch_registers_using_g (regcache);
8197 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8198 if (!rsa->regs[i].in_g_packet)
8199 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
8201 /* This register is not available. */
8202 regcache->raw_supply (i, NULL);
8206 /* Prepare to store registers. Since we may send them all (using a
8207 'G' request), we have to read out the ones we don't want to change
8211 remote_target::prepare_to_store (struct regcache *regcache)
8213 struct remote_state *rs = get_remote_state ();
8214 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
8217 /* Make sure the entire registers array is valid. */
8218 switch (packet_support (PACKET_P))
8220 case PACKET_DISABLE:
8221 case PACKET_SUPPORT_UNKNOWN:
8222 /* Make sure all the necessary registers are cached. */
8223 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8224 if (rsa->regs[i].in_g_packet)
8225 regcache->raw_update (rsa->regs[i].regnum);
8232 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
8233 packet was not recognized. */
8236 remote_target::store_register_using_P (const struct regcache *regcache,
8239 struct gdbarch *gdbarch = regcache->arch ();
8240 struct remote_state *rs = get_remote_state ();
8241 /* Try storing a single register. */
8242 char *buf = rs->buf;
8243 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
8246 if (packet_support (PACKET_P) == PACKET_DISABLE)
8249 if (reg->pnum == -1)
8252 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
8253 p = buf + strlen (buf);
8254 regcache->raw_collect (reg->regnum, regp);
8255 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
8257 getpkt (&rs->buf, &rs->buf_size, 0);
8259 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
8264 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
8265 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
8266 case PACKET_UNKNOWN:
8269 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8273 /* Store register REGNUM, or all registers if REGNUM == -1, from the
8274 contents of the register cache buffer. FIXME: ignores errors. */
8277 remote_target::store_registers_using_G (const struct regcache *regcache)
8279 struct remote_state *rs = get_remote_state ();
8280 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
8284 /* Extract all the registers in the regcache copying them into a
8289 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
8290 memset (regs, 0, rsa->sizeof_g_packet);
8291 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8293 struct packet_reg *r = &rsa->regs[i];
8296 regcache->raw_collect (r->regnum, regs + r->offset);
8300 /* Command describes registers byte by byte,
8301 each byte encoded as two hex characters. */
8304 bin2hex (regs, p, rsa->sizeof_g_packet);
8306 getpkt (&rs->buf, &rs->buf_size, 0);
8307 if (packet_check_result (rs->buf) == PACKET_ERROR)
8308 error (_("Could not write registers; remote failure reply '%s'"),
8312 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
8313 of the register cache buffer. FIXME: ignores errors. */
8316 remote_target::store_registers (struct regcache *regcache, int regnum)
8318 struct gdbarch *gdbarch = regcache->arch ();
8319 struct remote_state *rs = get_remote_state ();
8320 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8323 set_remote_traceframe ();
8324 set_general_thread (regcache->ptid ());
8328 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8330 gdb_assert (reg != NULL);
8332 /* Always prefer to store registers using the 'P' packet if
8333 possible; we often change only a small number of registers.
8334 Sometimes we change a larger number; we'd need help from a
8335 higher layer to know to use 'G'. */
8336 if (store_register_using_P (regcache, reg))
8339 /* For now, don't complain if we have no way to write the
8340 register. GDB loses track of unavailable registers too
8341 easily. Some day, this may be an error. We don't have
8342 any way to read the register, either... */
8343 if (!reg->in_g_packet)
8346 store_registers_using_G (regcache);
8350 store_registers_using_G (regcache);
8352 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8353 if (!rsa->regs[i].in_g_packet)
8354 if (!store_register_using_P (regcache, &rsa->regs[i]))
8355 /* See above for why we do not issue an error here. */
8360 /* Return the number of hex digits in num. */
8363 hexnumlen (ULONGEST num)
8367 for (i = 0; num != 0; i++)
8370 return std::max (i, 1);
8373 /* Set BUF to the minimum number of hex digits representing NUM. */
8376 hexnumstr (char *buf, ULONGEST num)
8378 int len = hexnumlen (num);
8380 return hexnumnstr (buf, num, len);
8384 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
8387 hexnumnstr (char *buf, ULONGEST num, int width)
8393 for (i = width - 1; i >= 0; i--)
8395 buf[i] = "0123456789abcdef"[(num & 0xf)];
8402 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
8405 remote_address_masked (CORE_ADDR addr)
8407 unsigned int address_size = remote_address_size;
8409 /* If "remoteaddresssize" was not set, default to target address size. */
8411 address_size = gdbarch_addr_bit (target_gdbarch ());
8413 if (address_size > 0
8414 && address_size < (sizeof (ULONGEST) * 8))
8416 /* Only create a mask when that mask can safely be constructed
8417 in a ULONGEST variable. */
8420 mask = (mask << address_size) - 1;
8426 /* Determine whether the remote target supports binary downloading.
8427 This is accomplished by sending a no-op memory write of zero length
8428 to the target at the specified address. It does not suffice to send
8429 the whole packet, since many stubs strip the eighth bit and
8430 subsequently compute a wrong checksum, which causes real havoc with
8433 NOTE: This can still lose if the serial line is not eight-bit
8434 clean. In cases like this, the user should clear "remote
8438 remote_target::check_binary_download (CORE_ADDR addr)
8440 struct remote_state *rs = get_remote_state ();
8442 switch (packet_support (PACKET_X))
8444 case PACKET_DISABLE:
8448 case PACKET_SUPPORT_UNKNOWN:
8454 p += hexnumstr (p, (ULONGEST) addr);
8456 p += hexnumstr (p, (ULONGEST) 0);
8460 putpkt_binary (rs->buf, (int) (p - rs->buf));
8461 getpkt (&rs->buf, &rs->buf_size, 0);
8463 if (rs->buf[0] == '\0')
8466 fprintf_unfiltered (gdb_stdlog,
8467 "binary downloading NOT "
8468 "supported by target\n");
8469 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
8474 fprintf_unfiltered (gdb_stdlog,
8475 "binary downloading supported by target\n");
8476 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
8483 /* Helper function to resize the payload in order to try to get a good
8484 alignment. We try to write an amount of data such that the next write will
8485 start on an address aligned on REMOTE_ALIGN_WRITES. */
8488 align_for_efficient_write (int todo, CORE_ADDR memaddr)
8490 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
8493 /* Write memory data directly to the remote machine.
8494 This does not inform the data cache; the data cache uses this.
8495 HEADER is the starting part of the packet.
8496 MEMADDR is the address in the remote memory space.
8497 MYADDR is the address of the buffer in our space.
8498 LEN_UNITS is the number of addressable units to write.
8499 UNIT_SIZE is the length in bytes of an addressable unit.
8500 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
8501 should send data as binary ('X'), or hex-encoded ('M').
8503 The function creates packet of the form
8504 <HEADER><ADDRESS>,<LENGTH>:<DATA>
8506 where encoding of <DATA> is terminated by PACKET_FORMAT.
8508 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
8511 Return the transferred status, error or OK (an
8512 'enum target_xfer_status' value). Save the number of addressable units
8513 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
8515 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
8516 exchange between gdb and the stub could look like (?? in place of the
8522 -> $M1000,3:eeeeffffeeee#??
8526 <- eeeeffffeeeedddd */
8529 remote_target::remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
8530 const gdb_byte *myaddr,
8533 ULONGEST *xfered_len_units,
8534 char packet_format, int use_length)
8536 struct remote_state *rs = get_remote_state ();
8542 int payload_capacity_bytes;
8543 int payload_length_bytes;
8545 if (packet_format != 'X' && packet_format != 'M')
8546 internal_error (__FILE__, __LINE__,
8547 _("remote_write_bytes_aux: bad packet format"));
8550 return TARGET_XFER_EOF;
8552 payload_capacity_bytes = get_memory_write_packet_size ();
8554 /* The packet buffer will be large enough for the payload;
8555 get_memory_packet_size ensures this. */
8558 /* Compute the size of the actual payload by subtracting out the
8559 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
8561 payload_capacity_bytes -= strlen ("$,:#NN");
8563 /* The comma won't be used. */
8564 payload_capacity_bytes += 1;
8565 payload_capacity_bytes -= strlen (header);
8566 payload_capacity_bytes -= hexnumlen (memaddr);
8568 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
8570 strcat (rs->buf, header);
8571 p = rs->buf + strlen (header);
8573 /* Compute a best guess of the number of bytes actually transfered. */
8574 if (packet_format == 'X')
8576 /* Best guess at number of bytes that will fit. */
8577 todo_units = std::min (len_units,
8578 (ULONGEST) payload_capacity_bytes / unit_size);
8580 payload_capacity_bytes -= hexnumlen (todo_units);
8581 todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
8585 /* Number of bytes that will fit. */
8587 = std::min (len_units,
8588 (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
8590 payload_capacity_bytes -= hexnumlen (todo_units);
8591 todo_units = std::min (todo_units,
8592 (payload_capacity_bytes / unit_size) / 2);
8595 if (todo_units <= 0)
8596 internal_error (__FILE__, __LINE__,
8597 _("minimum packet size too small to write data"));
8599 /* If we already need another packet, then try to align the end
8600 of this packet to a useful boundary. */
8601 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
8602 todo_units = align_for_efficient_write (todo_units, memaddr);
8604 /* Append "<memaddr>". */
8605 memaddr = remote_address_masked (memaddr);
8606 p += hexnumstr (p, (ULONGEST) memaddr);
8613 /* Append the length and retain its location and size. It may need to be
8614 adjusted once the packet body has been created. */
8616 plenlen = hexnumstr (p, (ULONGEST) todo_units);
8624 /* Append the packet body. */
8625 if (packet_format == 'X')
8627 /* Binary mode. Send target system values byte by byte, in
8628 increasing byte addresses. Only escape certain critical
8630 payload_length_bytes =
8631 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
8632 &units_written, payload_capacity_bytes);
8634 /* If not all TODO units fit, then we'll need another packet. Make
8635 a second try to keep the end of the packet aligned. Don't do
8636 this if the packet is tiny. */
8637 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
8641 new_todo_units = align_for_efficient_write (units_written, memaddr);
8643 if (new_todo_units != units_written)
8644 payload_length_bytes =
8645 remote_escape_output (myaddr, new_todo_units, unit_size,
8646 (gdb_byte *) p, &units_written,
8647 payload_capacity_bytes);
8650 p += payload_length_bytes;
8651 if (use_length && units_written < todo_units)
8653 /* Escape chars have filled up the buffer prematurely,
8654 and we have actually sent fewer units than planned.
8655 Fix-up the length field of the packet. Use the same
8656 number of characters as before. */
8657 plen += hexnumnstr (plen, (ULONGEST) units_written,
8659 *plen = ':'; /* overwrite \0 from hexnumnstr() */
8664 /* Normal mode: Send target system values byte by byte, in
8665 increasing byte addresses. Each byte is encoded as a two hex
8667 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
8668 units_written = todo_units;
8671 putpkt_binary (rs->buf, (int) (p - rs->buf));
8672 getpkt (&rs->buf, &rs->buf_size, 0);
8674 if (rs->buf[0] == 'E')
8675 return TARGET_XFER_E_IO;
8677 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
8678 send fewer units than we'd planned. */
8679 *xfered_len_units = (ULONGEST) units_written;
8680 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
8683 /* Write memory data directly to the remote machine.
8684 This does not inform the data cache; the data cache uses this.
8685 MEMADDR is the address in the remote memory space.
8686 MYADDR is the address of the buffer in our space.
8687 LEN is the number of bytes.
8689 Return the transferred status, error or OK (an
8690 'enum target_xfer_status' value). Save the number of bytes
8691 transferred in *XFERED_LEN. Only transfer a single packet. */
8694 remote_target::remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr,
8695 ULONGEST len, int unit_size,
8696 ULONGEST *xfered_len)
8698 const char *packet_format = NULL;
8700 /* Check whether the target supports binary download. */
8701 check_binary_download (memaddr);
8703 switch (packet_support (PACKET_X))
8706 packet_format = "X";
8708 case PACKET_DISABLE:
8709 packet_format = "M";
8711 case PACKET_SUPPORT_UNKNOWN:
8712 internal_error (__FILE__, __LINE__,
8713 _("remote_write_bytes: bad internal state"));
8715 internal_error (__FILE__, __LINE__, _("bad switch"));
8718 return remote_write_bytes_aux (packet_format,
8719 memaddr, myaddr, len, unit_size, xfered_len,
8720 packet_format[0], 1);
8723 /* Read memory data directly from the remote machine.
8724 This does not use the data cache; the data cache uses this.
8725 MEMADDR is the address in the remote memory space.
8726 MYADDR is the address of the buffer in our space.
8727 LEN_UNITS is the number of addressable memory units to read..
8728 UNIT_SIZE is the length in bytes of an addressable unit.
8730 Return the transferred status, error or OK (an
8731 'enum target_xfer_status' value). Save the number of bytes
8732 transferred in *XFERED_LEN_UNITS.
8734 See the comment of remote_write_bytes_aux for an example of
8735 memory read/write exchange between gdb and the stub. */
8738 remote_target::remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
8740 int unit_size, ULONGEST *xfered_len_units)
8742 struct remote_state *rs = get_remote_state ();
8743 int buf_size_bytes; /* Max size of packet output buffer. */
8748 buf_size_bytes = get_memory_read_packet_size ();
8749 /* The packet buffer will be large enough for the payload;
8750 get_memory_packet_size ensures this. */
8752 /* Number of units that will fit. */
8753 todo_units = std::min (len_units,
8754 (ULONGEST) (buf_size_bytes / unit_size) / 2);
8756 /* Construct "m"<memaddr>","<len>". */
8757 memaddr = remote_address_masked (memaddr);
8760 p += hexnumstr (p, (ULONGEST) memaddr);
8762 p += hexnumstr (p, (ULONGEST) todo_units);
8765 getpkt (&rs->buf, &rs->buf_size, 0);
8766 if (rs->buf[0] == 'E'
8767 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
8768 && rs->buf[3] == '\0')
8769 return TARGET_XFER_E_IO;
8770 /* Reply describes memory byte by byte, each byte encoded as two hex
8773 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
8774 /* Return what we have. Let higher layers handle partial reads. */
8775 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
8776 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
8779 /* Using the set of read-only target sections of remote, read live
8782 For interface/parameters/return description see target.h,
8786 remote_target::remote_xfer_live_readonly_partial (gdb_byte *readbuf,
8790 ULONGEST *xfered_len)
8792 struct target_section *secp;
8793 struct target_section_table *table;
8795 secp = target_section_by_addr (this, memaddr);
8797 && (bfd_get_section_flags (secp->the_bfd_section->owner,
8798 secp->the_bfd_section)
8801 struct target_section *p;
8802 ULONGEST memend = memaddr + len;
8804 table = target_get_section_table (this);
8806 for (p = table->sections; p < table->sections_end; p++)
8808 if (memaddr >= p->addr)
8810 if (memend <= p->endaddr)
8812 /* Entire transfer is within this section. */
8813 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
8816 else if (memaddr >= p->endaddr)
8818 /* This section ends before the transfer starts. */
8823 /* This section overlaps the transfer. Just do half. */
8824 len = p->endaddr - memaddr;
8825 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
8832 return TARGET_XFER_EOF;
8835 /* Similar to remote_read_bytes_1, but it reads from the remote stub
8836 first if the requested memory is unavailable in traceframe.
8837 Otherwise, fall back to remote_read_bytes_1. */
8840 remote_target::remote_read_bytes (CORE_ADDR memaddr,
8841 gdb_byte *myaddr, ULONGEST len, int unit_size,
8842 ULONGEST *xfered_len)
8845 return TARGET_XFER_EOF;
8847 if (get_traceframe_number () != -1)
8849 std::vector<mem_range> available;
8851 /* If we fail to get the set of available memory, then the
8852 target does not support querying traceframe info, and so we
8853 attempt reading from the traceframe anyway (assuming the
8854 target implements the old QTro packet then). */
8855 if (traceframe_available_memory (&available, memaddr, len))
8857 if (available.empty () || available[0].start != memaddr)
8859 enum target_xfer_status res;
8861 /* Don't read into the traceframe's available
8863 if (!available.empty ())
8865 LONGEST oldlen = len;
8867 len = available[0].start - memaddr;
8868 gdb_assert (len <= oldlen);
8871 /* This goes through the topmost target again. */
8872 res = remote_xfer_live_readonly_partial (myaddr, memaddr,
8873 len, unit_size, xfered_len);
8874 if (res == TARGET_XFER_OK)
8875 return TARGET_XFER_OK;
8878 /* No use trying further, we know some memory starting
8879 at MEMADDR isn't available. */
8881 return (*xfered_len != 0) ?
8882 TARGET_XFER_UNAVAILABLE : TARGET_XFER_EOF;
8886 /* Don't try to read more than how much is available, in
8887 case the target implements the deprecated QTro packet to
8888 cater for older GDBs (the target's knowledge of read-only
8889 sections may be outdated by now). */
8890 len = available[0].length;
8894 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
8899 /* Sends a packet with content determined by the printf format string
8900 FORMAT and the remaining arguments, then gets the reply. Returns
8901 whether the packet was a success, a failure, or unknown. */
8904 remote_target::remote_send_printf (const char *format, ...)
8906 struct remote_state *rs = get_remote_state ();
8907 int max_size = get_remote_packet_size ();
8910 va_start (ap, format);
8913 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
8914 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
8916 if (putpkt (rs->buf) < 0)
8917 error (_("Communication problem with target."));
8920 getpkt (&rs->buf, &rs->buf_size, 0);
8922 return packet_check_result (rs->buf);
8925 /* Flash writing can take quite some time. We'll set
8926 effectively infinite timeout for flash operations.
8927 In future, we'll need to decide on a better approach. */
8928 static const int remote_flash_timeout = 1000;
8931 remote_target::flash_erase (ULONGEST address, LONGEST length)
8933 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
8934 enum packet_result ret;
8935 scoped_restore restore_timeout
8936 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8938 ret = remote_send_printf ("vFlashErase:%s,%s",
8939 phex (address, addr_size),
8943 case PACKET_UNKNOWN:
8944 error (_("Remote target does not support flash erase"));
8946 error (_("Error erasing flash with vFlashErase packet"));
8953 remote_target::remote_flash_write (ULONGEST address,
8954 ULONGEST length, ULONGEST *xfered_len,
8955 const gdb_byte *data)
8957 scoped_restore restore_timeout
8958 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8959 return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
8964 remote_target::flash_done ()
8968 scoped_restore restore_timeout
8969 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8971 ret = remote_send_printf ("vFlashDone");
8975 case PACKET_UNKNOWN:
8976 error (_("Remote target does not support vFlashDone"));
8978 error (_("Error finishing flash operation"));
8985 remote_target::files_info ()
8987 puts_filtered ("Debugging a target over a serial line.\n");
8990 /* Stuff for dealing with the packets which are part of this protocol.
8991 See comment at top of file for details. */
8993 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
8994 error to higher layers. Called when a serial error is detected.
8995 The exception message is STRING, followed by a colon and a blank,
8996 the system error message for errno at function entry and final dot
8997 for output compatibility with throw_perror_with_name. */
9000 unpush_and_perror (const char *string)
9002 int saved_errno = errno;
9004 remote_unpush_target ();
9005 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
9006 safe_strerror (saved_errno));
9009 /* Read a single character from the remote end. The current quit
9010 handler is overridden to avoid quitting in the middle of packet
9011 sequence, as that would break communication with the remote server.
9012 See remote_serial_quit_handler for more detail. */
9015 remote_target::readchar (int timeout)
9018 struct remote_state *rs = get_remote_state ();
9021 scoped_restore restore_quit_target
9022 = make_scoped_restore (&curr_quit_handler_target, this);
9023 scoped_restore restore_quit
9024 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9026 rs->got_ctrlc_during_io = 0;
9028 ch = serial_readchar (rs->remote_desc, timeout);
9030 if (rs->got_ctrlc_during_io)
9037 switch ((enum serial_rc) ch)
9040 remote_unpush_target ();
9041 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
9044 unpush_and_perror (_("Remote communication error. "
9045 "Target disconnected."));
9047 case SERIAL_TIMEOUT:
9053 /* Wrapper for serial_write that closes the target and throws if
9054 writing fails. The current quit handler is overridden to avoid
9055 quitting in the middle of packet sequence, as that would break
9056 communication with the remote server. See
9057 remote_serial_quit_handler for more detail. */
9060 remote_target::remote_serial_write (const char *str, int len)
9062 struct remote_state *rs = get_remote_state ();
9064 scoped_restore restore_quit_target
9065 = make_scoped_restore (&curr_quit_handler_target, this);
9066 scoped_restore restore_quit
9067 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9069 rs->got_ctrlc_during_io = 0;
9071 if (serial_write (rs->remote_desc, str, len))
9073 unpush_and_perror (_("Remote communication error. "
9074 "Target disconnected."));
9077 if (rs->got_ctrlc_during_io)
9081 /* Return a string representing an escaped version of BUF, of len N.
9082 E.g. \n is converted to \\n, \t to \\t, etc. */
9085 escape_buffer (const char *buf, int n)
9089 stb.putstrn (buf, n, '\\');
9090 return std::move (stb.string ());
9093 /* Display a null-terminated packet on stdout, for debugging, using C
9097 print_packet (const char *buf)
9099 puts_filtered ("\"");
9100 fputstr_filtered (buf, '"', gdb_stdout);
9101 puts_filtered ("\"");
9105 remote_target::putpkt (const char *buf)
9107 return putpkt_binary (buf, strlen (buf));
9110 /* Wrapper around remote_target::putpkt to avoid exporting
9114 putpkt (remote_target *remote, const char *buf)
9116 return remote->putpkt (buf);
9119 /* Send a packet to the remote machine, with error checking. The data
9120 of the packet is in BUF. The string in BUF can be at most
9121 get_remote_packet_size () - 5 to account for the $, # and checksum,
9122 and for a possible /0 if we are debugging (remote_debug) and want
9123 to print the sent packet as a string. */
9126 remote_target::putpkt_binary (const char *buf, int cnt)
9128 struct remote_state *rs = get_remote_state ();
9130 unsigned char csum = 0;
9131 gdb::def_vector<char> data (cnt + 6);
9132 char *buf2 = data.data ();
9138 /* Catch cases like trying to read memory or listing threads while
9139 we're waiting for a stop reply. The remote server wouldn't be
9140 ready to handle this request, so we'd hang and timeout. We don't
9141 have to worry about this in synchronous mode, because in that
9142 case it's not possible to issue a command while the target is
9143 running. This is not a problem in non-stop mode, because in that
9144 case, the stub is always ready to process serial input. */
9145 if (!target_is_non_stop_p ()
9146 && target_is_async_p ()
9147 && rs->waiting_for_stop_reply)
9149 error (_("Cannot execute this command while the target is running.\n"
9150 "Use the \"interrupt\" command to stop the target\n"
9151 "and then try again."));
9154 /* We're sending out a new packet. Make sure we don't look at a
9155 stale cached response. */
9156 rs->cached_wait_status = 0;
9158 /* Copy the packet into buffer BUF2, encapsulating it
9159 and giving it a checksum. */
9164 for (i = 0; i < cnt; i++)
9170 *p++ = tohex ((csum >> 4) & 0xf);
9171 *p++ = tohex (csum & 0xf);
9173 /* Send it over and over until we get a positive ack. */
9177 int started_error_output = 0;
9183 int len = (int) (p - buf2);
9186 = escape_buffer (buf2, std::min (len, REMOTE_DEBUG_MAX_CHAR));
9188 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s", str.c_str ());
9190 if (len > REMOTE_DEBUG_MAX_CHAR)
9191 fprintf_unfiltered (gdb_stdlog, "[%d bytes omitted]",
9192 len - REMOTE_DEBUG_MAX_CHAR);
9194 fprintf_unfiltered (gdb_stdlog, "...");
9196 gdb_flush (gdb_stdlog);
9198 remote_serial_write (buf2, p - buf2);
9200 /* If this is a no acks version of the remote protocol, send the
9201 packet and move on. */
9205 /* Read until either a timeout occurs (-2) or '+' is read.
9206 Handle any notification that arrives in the mean time. */
9209 ch = readchar (remote_timeout);
9217 case SERIAL_TIMEOUT:
9220 if (started_error_output)
9222 putchar_unfiltered ('\n');
9223 started_error_output = 0;
9232 fprintf_unfiltered (gdb_stdlog, "Ack\n");
9236 fprintf_unfiltered (gdb_stdlog, "Nak\n");
9238 case SERIAL_TIMEOUT:
9242 break; /* Retransmit buffer. */
9246 fprintf_unfiltered (gdb_stdlog,
9247 "Packet instead of Ack, ignoring it\n");
9248 /* It's probably an old response sent because an ACK
9249 was lost. Gobble up the packet and ack it so it
9250 doesn't get retransmitted when we resend this
9253 remote_serial_write ("+", 1);
9254 continue; /* Now, go look for +. */
9261 /* If we got a notification, handle it, and go back to looking
9263 /* We've found the start of a notification. Now
9264 collect the data. */
9265 val = read_frame (&rs->buf, &rs->buf_size);
9270 std::string str = escape_buffer (rs->buf, val);
9272 fprintf_unfiltered (gdb_stdlog,
9273 " Notification received: %s\n",
9276 handle_notification (rs->notif_state, rs->buf);
9277 /* We're in sync now, rewait for the ack. */
9284 if (!started_error_output)
9286 started_error_output = 1;
9287 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
9289 fputc_unfiltered (ch & 0177, gdb_stdlog);
9290 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
9299 if (!started_error_output)
9301 started_error_output = 1;
9302 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
9304 fputc_unfiltered (ch & 0177, gdb_stdlog);
9308 break; /* Here to retransmit. */
9312 /* This is wrong. If doing a long backtrace, the user should be
9313 able to get out next time we call QUIT, without anything as
9314 violent as interrupt_query. If we want to provide a way out of
9315 here without getting to the next QUIT, it should be based on
9316 hitting ^C twice as in remote_wait. */
9328 /* Come here after finding the start of a frame when we expected an
9329 ack. Do our best to discard the rest of this packet. */
9332 remote_target::skip_frame ()
9338 c = readchar (remote_timeout);
9341 case SERIAL_TIMEOUT:
9342 /* Nothing we can do. */
9345 /* Discard the two bytes of checksum and stop. */
9346 c = readchar (remote_timeout);
9348 c = readchar (remote_timeout);
9351 case '*': /* Run length encoding. */
9352 /* Discard the repeat count. */
9353 c = readchar (remote_timeout);
9358 /* A regular character. */
9364 /* Come here after finding the start of the frame. Collect the rest
9365 into *BUF, verifying the checksum, length, and handling run-length
9366 compression. NUL terminate the buffer. If there is not enough room,
9367 expand *BUF using xrealloc.
9369 Returns -1 on error, number of characters in buffer (ignoring the
9370 trailing NULL) on success. (could be extended to return one of the
9371 SERIAL status indications). */
9374 remote_target::read_frame (char **buf_p, long *sizeof_buf)
9380 struct remote_state *rs = get_remote_state ();
9387 c = readchar (remote_timeout);
9390 case SERIAL_TIMEOUT:
9392 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
9396 fputs_filtered ("Saw new packet start in middle of old one\n",
9398 return -1; /* Start a new packet, count retries. */
9401 unsigned char pktcsum;
9407 check_0 = readchar (remote_timeout);
9409 check_1 = readchar (remote_timeout);
9411 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
9414 fputs_filtered ("Timeout in checksum, retrying\n",
9418 else if (check_0 < 0 || check_1 < 0)
9421 fputs_filtered ("Communication error in checksum\n",
9426 /* Don't recompute the checksum; with no ack packets we
9427 don't have any way to indicate a packet retransmission
9432 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
9433 if (csum == pktcsum)
9438 std::string str = escape_buffer (buf, bc);
9440 fprintf_unfiltered (gdb_stdlog,
9441 "Bad checksum, sentsum=0x%x, "
9442 "csum=0x%x, buf=%s\n",
9443 pktcsum, csum, str.c_str ());
9445 /* Number of characters in buffer ignoring trailing
9449 case '*': /* Run length encoding. */
9454 c = readchar (remote_timeout);
9456 repeat = c - ' ' + 3; /* Compute repeat count. */
9458 /* The character before ``*'' is repeated. */
9460 if (repeat > 0 && repeat <= 255 && bc > 0)
9462 if (bc + repeat - 1 >= *sizeof_buf - 1)
9464 /* Make some more room in the buffer. */
9465 *sizeof_buf += repeat;
9466 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
9470 memset (&buf[bc], buf[bc - 1], repeat);
9476 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
9480 if (bc >= *sizeof_buf - 1)
9482 /* Make some more room in the buffer. */
9484 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
9495 /* Read a packet from the remote machine, with error checking, and
9496 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
9497 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
9498 rather than timing out; this is used (in synchronous mode) to wait
9499 for a target that is is executing user code to stop. */
9500 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
9501 don't have to change all the calls to getpkt to deal with the
9502 return value, because at the moment I don't know what the right
9503 thing to do it for those. */
9506 remote_target::getpkt (char **buf, long *sizeof_buf, int forever)
9508 getpkt_sane (buf, sizeof_buf, forever);
9512 /* Read a packet from the remote machine, with error checking, and
9513 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
9514 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
9515 rather than timing out; this is used (in synchronous mode) to wait
9516 for a target that is is executing user code to stop. If FOREVER ==
9517 0, this function is allowed to time out gracefully and return an
9518 indication of this to the caller. Otherwise return the number of
9519 bytes read. If EXPECTING_NOTIF, consider receiving a notification
9520 enough reason to return to the caller. *IS_NOTIF is an output
9521 boolean that indicates whether *BUF holds a notification or not
9522 (a regular packet). */
9525 remote_target::getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf,
9526 int forever, int expecting_notif,
9529 struct remote_state *rs = get_remote_state ();
9535 /* We're reading a new response. Make sure we don't look at a
9536 previously cached response. */
9537 rs->cached_wait_status = 0;
9539 strcpy (*buf, "timeout");
9542 timeout = watchdog > 0 ? watchdog : -1;
9543 else if (expecting_notif)
9544 timeout = 0; /* There should already be a char in the buffer. If
9547 timeout = remote_timeout;
9551 /* Process any number of notifications, and then return when
9555 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
9557 for (tries = 1; tries <= MAX_TRIES; tries++)
9559 /* This can loop forever if the remote side sends us
9560 characters continuously, but if it pauses, we'll get
9561 SERIAL_TIMEOUT from readchar because of timeout. Then
9562 we'll count that as a retry.
9564 Note that even when forever is set, we will only wait
9565 forever prior to the start of a packet. After that, we
9566 expect characters to arrive at a brisk pace. They should
9567 show up within remote_timeout intervals. */
9569 c = readchar (timeout);
9570 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
9572 if (c == SERIAL_TIMEOUT)
9574 if (expecting_notif)
9575 return -1; /* Don't complain, it's normal to not get
9576 anything in this case. */
9578 if (forever) /* Watchdog went off? Kill the target. */
9580 remote_unpush_target ();
9581 throw_error (TARGET_CLOSE_ERROR,
9582 _("Watchdog timeout has expired. "
9583 "Target detached."));
9586 fputs_filtered ("Timed out.\n", gdb_stdlog);
9590 /* We've found the start of a packet or notification.
9591 Now collect the data. */
9592 val = read_frame (buf, sizeof_buf);
9597 remote_serial_write ("-", 1);
9600 if (tries > MAX_TRIES)
9602 /* We have tried hard enough, and just can't receive the
9603 packet/notification. Give up. */
9604 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
9606 /* Skip the ack char if we're in no-ack mode. */
9607 if (!rs->noack_mode)
9608 remote_serial_write ("+", 1);
9612 /* If we got an ordinary packet, return that to our caller. */
9618 = escape_buffer (*buf,
9619 std::min (val, REMOTE_DEBUG_MAX_CHAR));
9621 fprintf_unfiltered (gdb_stdlog, "Packet received: %s",
9624 if (val > REMOTE_DEBUG_MAX_CHAR)
9625 fprintf_unfiltered (gdb_stdlog, "[%d bytes omitted]",
9626 val - REMOTE_DEBUG_MAX_CHAR);
9628 fprintf_unfiltered (gdb_stdlog, "\n");
9631 /* Skip the ack char if we're in no-ack mode. */
9632 if (!rs->noack_mode)
9633 remote_serial_write ("+", 1);
9634 if (is_notif != NULL)
9639 /* If we got a notification, handle it, and go back to looking
9643 gdb_assert (c == '%');
9647 std::string str = escape_buffer (*buf, val);
9649 fprintf_unfiltered (gdb_stdlog,
9650 " Notification received: %s\n",
9653 if (is_notif != NULL)
9656 handle_notification (rs->notif_state, *buf);
9658 /* Notifications require no acknowledgement. */
9660 if (expecting_notif)
9667 remote_target::getpkt_sane (char **buf, long *sizeof_buf, int forever)
9669 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
9673 remote_target::getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
9676 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
9680 /* Kill any new fork children of process PID that haven't been
9681 processed by follow_fork. */
9684 remote_target::kill_new_fork_children (int pid)
9686 remote_state *rs = get_remote_state ();
9687 struct thread_info *thread;
9688 struct notif_client *notif = ¬if_client_stop;
9690 /* Kill the fork child threads of any threads in process PID
9691 that are stopped at a fork event. */
9692 ALL_NON_EXITED_THREADS (thread)
9694 struct target_waitstatus *ws = &thread->pending_follow;
9696 if (is_pending_fork_parent (ws, pid, thread->ptid))
9698 int child_pid = ws->value.related_pid.pid ();
9701 res = remote_vkill (child_pid);
9703 error (_("Can't kill fork child process %d"), child_pid);
9707 /* Check for any pending fork events (not reported or processed yet)
9708 in process PID and kill those fork child threads as well. */
9709 remote_notif_get_pending_events (notif);
9710 for (auto &event : rs->stop_reply_queue)
9711 if (is_pending_fork_parent (&event->ws, pid, event->ptid))
9713 int child_pid = event->ws.value.related_pid.pid ();
9716 res = remote_vkill (child_pid);
9718 error (_("Can't kill fork child process %d"), child_pid);
9723 /* Target hook to kill the current inferior. */
9726 remote_target::kill ()
9729 int pid = inferior_ptid.pid ();
9730 struct remote_state *rs = get_remote_state ();
9732 if (packet_support (PACKET_vKill) != PACKET_DISABLE)
9734 /* If we're stopped while forking and we haven't followed yet,
9735 kill the child task. We need to do this before killing the
9736 parent task because if this is a vfork then the parent will
9738 kill_new_fork_children (pid);
9740 res = remote_vkill (pid);
9743 target_mourn_inferior (inferior_ptid);
9748 /* If we are in 'target remote' mode and we are killing the only
9749 inferior, then we will tell gdbserver to exit and unpush the
9751 if (res == -1 && !remote_multi_process_p (rs)
9752 && number_of_live_inferiors () == 1)
9756 /* We've killed the remote end, we get to mourn it. If we are
9757 not in extended mode, mourning the inferior also unpushes
9758 remote_ops from the target stack, which closes the remote
9760 target_mourn_inferior (inferior_ptid);
9765 error (_("Can't kill process"));
9768 /* Send a kill request to the target using the 'vKill' packet. */
9771 remote_target::remote_vkill (int pid)
9773 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
9776 remote_state *rs = get_remote_state ();
9778 /* Tell the remote target to detach. */
9779 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
9781 getpkt (&rs->buf, &rs->buf_size, 0);
9783 switch (packet_ok (rs->buf,
9784 &remote_protocol_packets[PACKET_vKill]))
9790 case PACKET_UNKNOWN:
9793 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
9797 /* Send a kill request to the target using the 'k' packet. */
9800 remote_target::remote_kill_k ()
9802 /* Catch errors so the user can quit from gdb even when we
9803 aren't on speaking terms with the remote system. */
9808 CATCH (ex, RETURN_MASK_ERROR)
9810 if (ex.error == TARGET_CLOSE_ERROR)
9812 /* If we got an (EOF) error that caused the target
9813 to go away, then we're done, that's what we wanted.
9814 "k" is susceptible to cause a premature EOF, given
9815 that the remote server isn't actually required to
9816 reply to "k", and it can happen that it doesn't
9817 even get to reply ACK to the "k". */
9821 /* Otherwise, something went wrong. We didn't actually kill
9822 the target. Just propagate the exception, and let the
9823 user or higher layers decide what to do. */
9824 throw_exception (ex);
9830 remote_target::mourn_inferior ()
9832 struct remote_state *rs = get_remote_state ();
9834 /* We're no longer interested in notification events of an inferior
9835 that exited or was killed/detached. */
9836 discard_pending_stop_replies (current_inferior ());
9838 /* In 'target remote' mode with one inferior, we close the connection. */
9839 if (!rs->extended && number_of_live_inferiors () <= 1)
9841 unpush_target (this);
9843 /* remote_close takes care of doing most of the clean up. */
9844 generic_mourn_inferior ();
9848 /* In case we got here due to an error, but we're going to stay
9850 rs->waiting_for_stop_reply = 0;
9852 /* If the current general thread belonged to the process we just
9853 detached from or has exited, the remote side current general
9854 thread becomes undefined. Considering a case like this:
9856 - We just got here due to a detach.
9857 - The process that we're detaching from happens to immediately
9858 report a global breakpoint being hit in non-stop mode, in the
9859 same thread we had selected before.
9860 - GDB attaches to this process again.
9861 - This event happens to be the next event we handle.
9863 GDB would consider that the current general thread didn't need to
9864 be set on the stub side (with Hg), since for all it knew,
9865 GENERAL_THREAD hadn't changed.
9867 Notice that although in all-stop mode, the remote server always
9868 sets the current thread to the thread reporting the stop event,
9869 that doesn't happen in non-stop mode; in non-stop, the stub *must
9870 not* change the current thread when reporting a breakpoint hit,
9871 due to the decoupling of event reporting and event handling.
9873 To keep things simple, we always invalidate our notion of the
9875 record_currthread (rs, minus_one_ptid);
9877 /* Call common code to mark the inferior as not running. */
9878 generic_mourn_inferior ();
9880 if (!have_inferiors ())
9882 if (!remote_multi_process_p (rs))
9884 /* Check whether the target is running now - some remote stubs
9885 automatically restart after kill. */
9887 getpkt (&rs->buf, &rs->buf_size, 0);
9889 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
9891 /* Assume that the target has been restarted. Set
9892 inferior_ptid so that bits of core GDB realizes
9893 there's something here, e.g., so that the user can
9894 say "kill" again. */
9895 inferior_ptid = magic_null_ptid;
9902 extended_remote_target::supports_disable_randomization ()
9904 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
9908 remote_target::extended_remote_disable_randomization (int val)
9910 struct remote_state *rs = get_remote_state ();
9913 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
9916 reply = remote_get_noisy_reply ();
9918 error (_("Target does not support QDisableRandomization."));
9919 if (strcmp (reply, "OK") != 0)
9920 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
9924 remote_target::extended_remote_run (const std::string &args)
9926 struct remote_state *rs = get_remote_state ();
9928 const char *remote_exec_file = get_remote_exec_file ();
9930 /* If the user has disabled vRun support, or we have detected that
9931 support is not available, do not try it. */
9932 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
9935 strcpy (rs->buf, "vRun;");
9936 len = strlen (rs->buf);
9938 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
9939 error (_("Remote file name too long for run packet"));
9940 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
9941 strlen (remote_exec_file));
9947 gdb_argv argv (args.c_str ());
9948 for (i = 0; argv[i] != NULL; i++)
9950 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
9951 error (_("Argument list too long for run packet"));
9952 rs->buf[len++] = ';';
9953 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
9958 rs->buf[len++] = '\0';
9961 getpkt (&rs->buf, &rs->buf_size, 0);
9963 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
9966 /* We have a wait response. All is well. */
9968 case PACKET_UNKNOWN:
9971 if (remote_exec_file[0] == '\0')
9972 error (_("Running the default executable on the remote target failed; "
9973 "try \"set remote exec-file\"?"));
9975 error (_("Running \"%s\" on the remote target failed"),
9978 gdb_assert_not_reached (_("bad switch"));
9982 /* Helper function to send set/unset environment packets. ACTION is
9983 either "set" or "unset". PACKET is either "QEnvironmentHexEncoded"
9984 or "QEnvironmentUnsetVariable". VALUE is the variable to be
9988 remote_target::send_environment_packet (const char *action,
9992 remote_state *rs = get_remote_state ();
9994 /* Convert the environment variable to an hex string, which
9995 is the best format to be transmitted over the wire. */
9996 std::string encoded_value = bin2hex ((const gdb_byte *) value,
9999 xsnprintf (rs->buf, get_remote_packet_size (),
10000 "%s:%s", packet, encoded_value.c_str ());
10003 getpkt (&rs->buf, &rs->buf_size, 0);
10004 if (strcmp (rs->buf, "OK") != 0)
10005 warning (_("Unable to %s environment variable '%s' on remote."),
10009 /* Helper function to handle the QEnvironment* packets. */
10012 remote_target::extended_remote_environment_support ()
10014 remote_state *rs = get_remote_state ();
10016 if (packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
10018 putpkt ("QEnvironmentReset");
10019 getpkt (&rs->buf, &rs->buf_size, 0);
10020 if (strcmp (rs->buf, "OK") != 0)
10021 warning (_("Unable to reset environment on remote."));
10024 gdb_environ *e = ¤t_inferior ()->environment;
10026 if (packet_support (PACKET_QEnvironmentHexEncoded) != PACKET_DISABLE)
10027 for (const std::string &el : e->user_set_env ())
10028 send_environment_packet ("set", "QEnvironmentHexEncoded",
10031 if (packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
10032 for (const std::string &el : e->user_unset_env ())
10033 send_environment_packet ("unset", "QEnvironmentUnset", el.c_str ());
10036 /* Helper function to set the current working directory for the
10037 inferior in the remote target. */
10040 remote_target::extended_remote_set_inferior_cwd ()
10042 if (packet_support (PACKET_QSetWorkingDir) != PACKET_DISABLE)
10044 const char *inferior_cwd = get_inferior_cwd ();
10045 remote_state *rs = get_remote_state ();
10047 if (inferior_cwd != NULL)
10049 std::string hexpath = bin2hex ((const gdb_byte *) inferior_cwd,
10050 strlen (inferior_cwd));
10052 xsnprintf (rs->buf, get_remote_packet_size (),
10053 "QSetWorkingDir:%s", hexpath.c_str ());
10057 /* An empty inferior_cwd means that the user wants us to
10058 reset the remote server's inferior's cwd. */
10059 xsnprintf (rs->buf, get_remote_packet_size (),
10060 "QSetWorkingDir:");
10064 getpkt (&rs->buf, &rs->buf_size, 0);
10065 if (packet_ok (rs->buf,
10066 &remote_protocol_packets[PACKET_QSetWorkingDir])
10069 Remote replied unexpectedly while setting the inferior's working\n\
10076 /* In the extended protocol we want to be able to do things like
10077 "run" and have them basically work as expected. So we need
10078 a special create_inferior function. We support changing the
10079 executable file and the command line arguments, but not the
10083 extended_remote_target::create_inferior (const char *exec_file,
10084 const std::string &args,
10085 char **env, int from_tty)
10089 struct remote_state *rs = get_remote_state ();
10090 const char *remote_exec_file = get_remote_exec_file ();
10092 /* If running asynchronously, register the target file descriptor
10093 with the event loop. */
10094 if (target_can_async_p ())
10097 /* Disable address space randomization if requested (and supported). */
10098 if (supports_disable_randomization ())
10099 extended_remote_disable_randomization (disable_randomization);
10101 /* If startup-with-shell is on, we inform gdbserver to start the
10102 remote inferior using a shell. */
10103 if (packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
10105 xsnprintf (rs->buf, get_remote_packet_size (),
10106 "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
10108 getpkt (&rs->buf, &rs->buf_size, 0);
10109 if (strcmp (rs->buf, "OK") != 0)
10111 Remote replied unexpectedly while setting startup-with-shell: %s"),
10115 extended_remote_environment_support ();
10117 extended_remote_set_inferior_cwd ();
10119 /* Now restart the remote server. */
10120 run_worked = extended_remote_run (args) != -1;
10123 /* vRun was not supported. Fail if we need it to do what the
10125 if (remote_exec_file[0])
10126 error (_("Remote target does not support \"set remote exec-file\""));
10127 if (!args.empty ())
10128 error (_("Remote target does not support \"set args\" or run <ARGS>"));
10130 /* Fall back to "R". */
10131 extended_remote_restart ();
10134 if (!have_inferiors ())
10136 /* Clean up from the last time we ran, before we mark the target
10137 running again. This will mark breakpoints uninserted, and
10138 get_offsets may insert breakpoints. */
10139 init_thread_list ();
10140 init_wait_for_inferior ();
10143 /* vRun's success return is a stop reply. */
10144 stop_reply = run_worked ? rs->buf : NULL;
10145 add_current_inferior_and_thread (stop_reply);
10147 /* Get updated offsets, if the stub uses qOffsets. */
10152 /* Given a location's target info BP_TGT and the packet buffer BUF, output
10153 the list of conditions (in agent expression bytecode format), if any, the
10154 target needs to evaluate. The output is placed into the packet buffer
10155 started from BUF and ended at BUF_END. */
10158 remote_add_target_side_condition (struct gdbarch *gdbarch,
10159 struct bp_target_info *bp_tgt, char *buf,
10162 if (bp_tgt->conditions.empty ())
10165 buf += strlen (buf);
10166 xsnprintf (buf, buf_end - buf, "%s", ";");
10169 /* Send conditions to the target. */
10170 for (agent_expr *aexpr : bp_tgt->conditions)
10172 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
10173 buf += strlen (buf);
10174 for (int i = 0; i < aexpr->len; ++i)
10175 buf = pack_hex_byte (buf, aexpr->buf[i]);
10182 remote_add_target_side_commands (struct gdbarch *gdbarch,
10183 struct bp_target_info *bp_tgt, char *buf)
10185 if (bp_tgt->tcommands.empty ())
10188 buf += strlen (buf);
10190 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
10191 buf += strlen (buf);
10193 /* Concatenate all the agent expressions that are commands into the
10195 for (agent_expr *aexpr : bp_tgt->tcommands)
10197 sprintf (buf, "X%x,", aexpr->len);
10198 buf += strlen (buf);
10199 for (int i = 0; i < aexpr->len; ++i)
10200 buf = pack_hex_byte (buf, aexpr->buf[i]);
10205 /* Insert a breakpoint. On targets that have software breakpoint
10206 support, we ask the remote target to do the work; on targets
10207 which don't, we insert a traditional memory breakpoint. */
10210 remote_target::insert_breakpoint (struct gdbarch *gdbarch,
10211 struct bp_target_info *bp_tgt)
10213 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
10214 If it succeeds, then set the support to PACKET_ENABLE. If it
10215 fails, and the user has explicitly requested the Z support then
10216 report an error, otherwise, mark it disabled and go on. */
10218 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
10220 CORE_ADDR addr = bp_tgt->reqstd_address;
10221 struct remote_state *rs;
10224 /* Make sure the remote is pointing at the right process, if
10226 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10227 set_general_process ();
10229 rs = get_remote_state ();
10231 endbuf = rs->buf + get_remote_packet_size ();
10236 addr = (ULONGEST) remote_address_masked (addr);
10237 p += hexnumstr (p, addr);
10238 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10240 if (supports_evaluation_of_breakpoint_conditions ())
10241 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10243 if (can_run_breakpoint_commands ())
10244 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10247 getpkt (&rs->buf, &rs->buf_size, 0);
10249 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
10255 case PACKET_UNKNOWN:
10260 /* If this breakpoint has target-side commands but this stub doesn't
10261 support Z0 packets, throw error. */
10262 if (!bp_tgt->tcommands.empty ())
10263 throw_error (NOT_SUPPORTED_ERROR, _("\
10264 Target doesn't support breakpoints that have target side commands."));
10266 return memory_insert_breakpoint (this, gdbarch, bp_tgt);
10270 remote_target::remove_breakpoint (struct gdbarch *gdbarch,
10271 struct bp_target_info *bp_tgt,
10272 enum remove_bp_reason reason)
10274 CORE_ADDR addr = bp_tgt->placed_address;
10275 struct remote_state *rs = get_remote_state ();
10277 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
10280 char *endbuf = rs->buf + get_remote_packet_size ();
10282 /* Make sure the remote is pointing at the right process, if
10284 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10285 set_general_process ();
10291 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
10292 p += hexnumstr (p, addr);
10293 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10296 getpkt (&rs->buf, &rs->buf_size, 0);
10298 return (rs->buf[0] == 'E');
10301 return memory_remove_breakpoint (this, gdbarch, bp_tgt, reason);
10304 static enum Z_packet_type
10305 watchpoint_to_Z_packet (int type)
10310 return Z_PACKET_WRITE_WP;
10313 return Z_PACKET_READ_WP;
10316 return Z_PACKET_ACCESS_WP;
10319 internal_error (__FILE__, __LINE__,
10320 _("hw_bp_to_z: bad watchpoint type %d"), type);
10325 remote_target::insert_watchpoint (CORE_ADDR addr, int len,
10326 enum target_hw_bp_type type, struct expression *cond)
10328 struct remote_state *rs = get_remote_state ();
10329 char *endbuf = rs->buf + get_remote_packet_size ();
10331 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10333 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
10336 /* Make sure the remote is pointing at the right process, if
10338 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10339 set_general_process ();
10341 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
10342 p = strchr (rs->buf, '\0');
10343 addr = remote_address_masked (addr);
10344 p += hexnumstr (p, (ULONGEST) addr);
10345 xsnprintf (p, endbuf - p, ",%x", len);
10348 getpkt (&rs->buf, &rs->buf_size, 0);
10350 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
10354 case PACKET_UNKNOWN:
10359 internal_error (__FILE__, __LINE__,
10360 _("remote_insert_watchpoint: reached end of function"));
10364 remote_target::watchpoint_addr_within_range (CORE_ADDR addr,
10365 CORE_ADDR start, int length)
10367 CORE_ADDR diff = remote_address_masked (addr - start);
10369 return diff < length;
10374 remote_target::remove_watchpoint (CORE_ADDR addr, int len,
10375 enum target_hw_bp_type type, struct expression *cond)
10377 struct remote_state *rs = get_remote_state ();
10378 char *endbuf = rs->buf + get_remote_packet_size ();
10380 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10382 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
10385 /* Make sure the remote is pointing at the right process, if
10387 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10388 set_general_process ();
10390 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
10391 p = strchr (rs->buf, '\0');
10392 addr = remote_address_masked (addr);
10393 p += hexnumstr (p, (ULONGEST) addr);
10394 xsnprintf (p, endbuf - p, ",%x", len);
10396 getpkt (&rs->buf, &rs->buf_size, 0);
10398 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
10401 case PACKET_UNKNOWN:
10406 internal_error (__FILE__, __LINE__,
10407 _("remote_remove_watchpoint: reached end of function"));
10411 int remote_hw_watchpoint_limit = -1;
10412 int remote_hw_watchpoint_length_limit = -1;
10413 int remote_hw_breakpoint_limit = -1;
10416 remote_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
10418 if (remote_hw_watchpoint_length_limit == 0)
10420 else if (remote_hw_watchpoint_length_limit < 0)
10422 else if (len <= remote_hw_watchpoint_length_limit)
10429 remote_target::can_use_hw_breakpoint (enum bptype type, int cnt, int ot)
10431 if (type == bp_hardware_breakpoint)
10433 if (remote_hw_breakpoint_limit == 0)
10435 else if (remote_hw_breakpoint_limit < 0)
10437 else if (cnt <= remote_hw_breakpoint_limit)
10442 if (remote_hw_watchpoint_limit == 0)
10444 else if (remote_hw_watchpoint_limit < 0)
10448 else if (cnt <= remote_hw_watchpoint_limit)
10454 /* The to_stopped_by_sw_breakpoint method of target remote. */
10457 remote_target::stopped_by_sw_breakpoint ()
10459 struct thread_info *thread = inferior_thread ();
10461 return (thread->priv != NULL
10462 && (get_remote_thread_info (thread)->stop_reason
10463 == TARGET_STOPPED_BY_SW_BREAKPOINT));
10466 /* The to_supports_stopped_by_sw_breakpoint method of target
10470 remote_target::supports_stopped_by_sw_breakpoint ()
10472 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
10475 /* The to_stopped_by_hw_breakpoint method of target remote. */
10478 remote_target::stopped_by_hw_breakpoint ()
10480 struct thread_info *thread = inferior_thread ();
10482 return (thread->priv != NULL
10483 && (get_remote_thread_info (thread)->stop_reason
10484 == TARGET_STOPPED_BY_HW_BREAKPOINT));
10487 /* The to_supports_stopped_by_hw_breakpoint method of target
10491 remote_target::supports_stopped_by_hw_breakpoint ()
10493 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
10497 remote_target::stopped_by_watchpoint ()
10499 struct thread_info *thread = inferior_thread ();
10501 return (thread->priv != NULL
10502 && (get_remote_thread_info (thread)->stop_reason
10503 == TARGET_STOPPED_BY_WATCHPOINT));
10507 remote_target::stopped_data_address (CORE_ADDR *addr_p)
10509 struct thread_info *thread = inferior_thread ();
10511 if (thread->priv != NULL
10512 && (get_remote_thread_info (thread)->stop_reason
10513 == TARGET_STOPPED_BY_WATCHPOINT))
10515 *addr_p = get_remote_thread_info (thread)->watch_data_address;
10524 remote_target::insert_hw_breakpoint (struct gdbarch *gdbarch,
10525 struct bp_target_info *bp_tgt)
10527 CORE_ADDR addr = bp_tgt->reqstd_address;
10528 struct remote_state *rs;
10532 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10535 /* Make sure the remote is pointing at the right process, if
10537 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10538 set_general_process ();
10540 rs = get_remote_state ();
10542 endbuf = rs->buf + get_remote_packet_size ();
10548 addr = remote_address_masked (addr);
10549 p += hexnumstr (p, (ULONGEST) addr);
10550 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
10552 if (supports_evaluation_of_breakpoint_conditions ())
10553 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10555 if (can_run_breakpoint_commands ())
10556 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10559 getpkt (&rs->buf, &rs->buf_size, 0);
10561 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10564 if (rs->buf[1] == '.')
10566 message = strchr (rs->buf + 2, '.');
10568 error (_("Remote failure reply: %s"), message + 1);
10571 case PACKET_UNKNOWN:
10576 internal_error (__FILE__, __LINE__,
10577 _("remote_insert_hw_breakpoint: reached end of function"));
10582 remote_target::remove_hw_breakpoint (struct gdbarch *gdbarch,
10583 struct bp_target_info *bp_tgt)
10586 struct remote_state *rs = get_remote_state ();
10588 char *endbuf = rs->buf + get_remote_packet_size ();
10590 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10593 /* Make sure the remote is pointing at the right process, if
10595 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10596 set_general_process ();
10602 addr = remote_address_masked (bp_tgt->placed_address);
10603 p += hexnumstr (p, (ULONGEST) addr);
10604 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
10607 getpkt (&rs->buf, &rs->buf_size, 0);
10609 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10612 case PACKET_UNKNOWN:
10617 internal_error (__FILE__, __LINE__,
10618 _("remote_remove_hw_breakpoint: reached end of function"));
10621 /* Verify memory using the "qCRC:" request. */
10624 remote_target::verify_memory (const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
10626 struct remote_state *rs = get_remote_state ();
10627 unsigned long host_crc, target_crc;
10630 /* It doesn't make sense to use qCRC if the remote target is
10631 connected but not running. */
10632 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
10634 enum packet_result result;
10636 /* Make sure the remote is pointing at the right process. */
10637 set_general_process ();
10639 /* FIXME: assumes lma can fit into long. */
10640 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
10641 (long) lma, (long) size);
10644 /* Be clever; compute the host_crc before waiting for target
10646 host_crc = xcrc32 (data, size, 0xffffffff);
10648 getpkt (&rs->buf, &rs->buf_size, 0);
10650 result = packet_ok (rs->buf,
10651 &remote_protocol_packets[PACKET_qCRC]);
10652 if (result == PACKET_ERROR)
10654 else if (result == PACKET_OK)
10656 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
10657 target_crc = target_crc * 16 + fromhex (*tmp);
10659 return (host_crc == target_crc);
10663 return simple_verify_memory (this, data, lma, size);
10666 /* compare-sections command
10668 With no arguments, compares each loadable section in the exec bfd
10669 with the same memory range on the target, and reports mismatches.
10670 Useful for verifying the image on the target against the exec file. */
10673 compare_sections_command (const char *args, int from_tty)
10676 const char *sectname;
10677 bfd_size_type size;
10680 int mismatched = 0;
10685 error (_("command cannot be used without an exec file"));
10687 if (args != NULL && strcmp (args, "-r") == 0)
10693 for (s = exec_bfd->sections; s; s = s->next)
10695 if (!(s->flags & SEC_LOAD))
10696 continue; /* Skip non-loadable section. */
10698 if (read_only && (s->flags & SEC_READONLY) == 0)
10699 continue; /* Skip writeable sections */
10701 size = bfd_get_section_size (s);
10703 continue; /* Skip zero-length section. */
10705 sectname = bfd_get_section_name (exec_bfd, s);
10706 if (args && strcmp (args, sectname) != 0)
10707 continue; /* Not the section selected by user. */
10709 matched = 1; /* Do this section. */
10712 gdb::byte_vector sectdata (size);
10713 bfd_get_section_contents (exec_bfd, s, sectdata.data (), 0, size);
10715 res = target_verify_memory (sectdata.data (), lma, size);
10718 error (_("target memory fault, section %s, range %s -- %s"), sectname,
10719 paddress (target_gdbarch (), lma),
10720 paddress (target_gdbarch (), lma + size));
10722 printf_filtered ("Section %s, range %s -- %s: ", sectname,
10723 paddress (target_gdbarch (), lma),
10724 paddress (target_gdbarch (), lma + size));
10726 printf_filtered ("matched.\n");
10729 printf_filtered ("MIS-MATCHED!\n");
10733 if (mismatched > 0)
10734 warning (_("One or more sections of the target image does not match\n\
10735 the loaded file\n"));
10736 if (args && !matched)
10737 printf_filtered (_("No loaded section named '%s'.\n"), args);
10740 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
10741 into remote target. The number of bytes written to the remote
10742 target is returned, or -1 for error. */
10745 remote_target::remote_write_qxfer (const char *object_name,
10746 const char *annex, const gdb_byte *writebuf,
10747 ULONGEST offset, LONGEST len,
10748 ULONGEST *xfered_len,
10749 struct packet_config *packet)
10753 struct remote_state *rs = get_remote_state ();
10754 int max_size = get_memory_write_packet_size ();
10756 if (packet_config_support (packet) == PACKET_DISABLE)
10757 return TARGET_XFER_E_IO;
10759 /* Insert header. */
10760 i = snprintf (rs->buf, max_size,
10761 "qXfer:%s:write:%s:%s:",
10762 object_name, annex ? annex : "",
10763 phex_nz (offset, sizeof offset));
10764 max_size -= (i + 1);
10766 /* Escape as much data as fits into rs->buf. */
10767 buf_len = remote_escape_output
10768 (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
10770 if (putpkt_binary (rs->buf, i + buf_len) < 0
10771 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10772 || packet_ok (rs->buf, packet) != PACKET_OK)
10773 return TARGET_XFER_E_IO;
10775 unpack_varlen_hex (rs->buf, &n);
10778 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
10781 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
10782 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
10783 number of bytes read is returned, or 0 for EOF, or -1 for error.
10784 The number of bytes read may be less than LEN without indicating an
10785 EOF. PACKET is checked and updated to indicate whether the remote
10786 target supports this object. */
10789 remote_target::remote_read_qxfer (const char *object_name,
10791 gdb_byte *readbuf, ULONGEST offset,
10793 ULONGEST *xfered_len,
10794 struct packet_config *packet)
10796 struct remote_state *rs = get_remote_state ();
10797 LONGEST i, n, packet_len;
10799 if (packet_config_support (packet) == PACKET_DISABLE)
10800 return TARGET_XFER_E_IO;
10802 /* Check whether we've cached an end-of-object packet that matches
10804 if (rs->finished_object)
10806 if (strcmp (object_name, rs->finished_object) == 0
10807 && strcmp (annex ? annex : "", rs->finished_annex) == 0
10808 && offset == rs->finished_offset)
10809 return TARGET_XFER_EOF;
10812 /* Otherwise, we're now reading something different. Discard
10814 xfree (rs->finished_object);
10815 xfree (rs->finished_annex);
10816 rs->finished_object = NULL;
10817 rs->finished_annex = NULL;
10820 /* Request only enough to fit in a single packet. The actual data
10821 may not, since we don't know how much of it will need to be escaped;
10822 the target is free to respond with slightly less data. We subtract
10823 five to account for the response type and the protocol frame. */
10824 n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
10825 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
10826 object_name, annex ? annex : "",
10827 phex_nz (offset, sizeof offset),
10828 phex_nz (n, sizeof n));
10829 i = putpkt (rs->buf);
10831 return TARGET_XFER_E_IO;
10834 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10835 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
10836 return TARGET_XFER_E_IO;
10838 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
10839 error (_("Unknown remote qXfer reply: %s"), rs->buf);
10841 /* 'm' means there is (or at least might be) more data after this
10842 batch. That does not make sense unless there's at least one byte
10843 of data in this reply. */
10844 if (rs->buf[0] == 'm' && packet_len == 1)
10845 error (_("Remote qXfer reply contained no data."));
10847 /* Got some data. */
10848 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
10849 packet_len - 1, readbuf, n);
10851 /* 'l' is an EOF marker, possibly including a final block of data,
10852 or possibly empty. If we have the final block of a non-empty
10853 object, record this fact to bypass a subsequent partial read. */
10854 if (rs->buf[0] == 'l' && offset + i > 0)
10856 rs->finished_object = xstrdup (object_name);
10857 rs->finished_annex = xstrdup (annex ? annex : "");
10858 rs->finished_offset = offset + i;
10862 return TARGET_XFER_EOF;
10866 return TARGET_XFER_OK;
10870 enum target_xfer_status
10871 remote_target::xfer_partial (enum target_object object,
10872 const char *annex, gdb_byte *readbuf,
10873 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
10874 ULONGEST *xfered_len)
10876 struct remote_state *rs;
10880 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
10882 set_remote_traceframe ();
10883 set_general_thread (inferior_ptid);
10885 rs = get_remote_state ();
10887 /* Handle memory using the standard memory routines. */
10888 if (object == TARGET_OBJECT_MEMORY)
10890 /* If the remote target is connected but not running, we should
10891 pass this request down to a lower stratum (e.g. the executable
10893 if (!target_has_execution)
10894 return TARGET_XFER_EOF;
10896 if (writebuf != NULL)
10897 return remote_write_bytes (offset, writebuf, len, unit_size,
10900 return remote_read_bytes (offset, readbuf, len, unit_size,
10904 /* Handle SPU memory using qxfer packets. */
10905 if (object == TARGET_OBJECT_SPU)
10908 return remote_read_qxfer ("spu", annex, readbuf, offset, len,
10909 xfered_len, &remote_protocol_packets
10910 [PACKET_qXfer_spu_read]);
10912 return remote_write_qxfer ("spu", annex, writebuf, offset, len,
10913 xfered_len, &remote_protocol_packets
10914 [PACKET_qXfer_spu_write]);
10917 /* Handle extra signal info using qxfer packets. */
10918 if (object == TARGET_OBJECT_SIGNAL_INFO)
10921 return remote_read_qxfer ("siginfo", annex, readbuf, offset, len,
10922 xfered_len, &remote_protocol_packets
10923 [PACKET_qXfer_siginfo_read]);
10925 return remote_write_qxfer ("siginfo", annex,
10926 writebuf, offset, len, xfered_len,
10927 &remote_protocol_packets
10928 [PACKET_qXfer_siginfo_write]);
10931 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
10934 return remote_read_qxfer ("statictrace", annex,
10935 readbuf, offset, len, xfered_len,
10936 &remote_protocol_packets
10937 [PACKET_qXfer_statictrace_read]);
10939 return TARGET_XFER_E_IO;
10942 /* Only handle flash writes. */
10943 if (writebuf != NULL)
10947 case TARGET_OBJECT_FLASH:
10948 return remote_flash_write (offset, len, xfered_len,
10952 return TARGET_XFER_E_IO;
10956 /* Map pre-existing objects onto letters. DO NOT do this for new
10957 objects!!! Instead specify new query packets. */
10960 case TARGET_OBJECT_AVR:
10964 case TARGET_OBJECT_AUXV:
10965 gdb_assert (annex == NULL);
10966 return remote_read_qxfer ("auxv", annex, readbuf, offset, len,
10968 &remote_protocol_packets[PACKET_qXfer_auxv]);
10970 case TARGET_OBJECT_AVAILABLE_FEATURES:
10971 return remote_read_qxfer
10972 ("features", annex, readbuf, offset, len, xfered_len,
10973 &remote_protocol_packets[PACKET_qXfer_features]);
10975 case TARGET_OBJECT_LIBRARIES:
10976 return remote_read_qxfer
10977 ("libraries", annex, readbuf, offset, len, xfered_len,
10978 &remote_protocol_packets[PACKET_qXfer_libraries]);
10980 case TARGET_OBJECT_LIBRARIES_SVR4:
10981 return remote_read_qxfer
10982 ("libraries-svr4", annex, readbuf, offset, len, xfered_len,
10983 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
10985 case TARGET_OBJECT_MEMORY_MAP:
10986 gdb_assert (annex == NULL);
10987 return remote_read_qxfer ("memory-map", annex, readbuf, offset, len,
10989 &remote_protocol_packets[PACKET_qXfer_memory_map]);
10991 case TARGET_OBJECT_OSDATA:
10992 /* Should only get here if we're connected. */
10993 gdb_assert (rs->remote_desc);
10994 return remote_read_qxfer
10995 ("osdata", annex, readbuf, offset, len, xfered_len,
10996 &remote_protocol_packets[PACKET_qXfer_osdata]);
10998 case TARGET_OBJECT_THREADS:
10999 gdb_assert (annex == NULL);
11000 return remote_read_qxfer ("threads", annex, readbuf, offset, len,
11002 &remote_protocol_packets[PACKET_qXfer_threads]);
11004 case TARGET_OBJECT_TRACEFRAME_INFO:
11005 gdb_assert (annex == NULL);
11006 return remote_read_qxfer
11007 ("traceframe-info", annex, readbuf, offset, len, xfered_len,
11008 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
11010 case TARGET_OBJECT_FDPIC:
11011 return remote_read_qxfer ("fdpic", annex, readbuf, offset, len,
11013 &remote_protocol_packets[PACKET_qXfer_fdpic]);
11015 case TARGET_OBJECT_OPENVMS_UIB:
11016 return remote_read_qxfer ("uib", annex, readbuf, offset, len,
11018 &remote_protocol_packets[PACKET_qXfer_uib]);
11020 case TARGET_OBJECT_BTRACE:
11021 return remote_read_qxfer ("btrace", annex, readbuf, offset, len,
11023 &remote_protocol_packets[PACKET_qXfer_btrace]);
11025 case TARGET_OBJECT_BTRACE_CONF:
11026 return remote_read_qxfer ("btrace-conf", annex, readbuf, offset,
11028 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
11030 case TARGET_OBJECT_EXEC_FILE:
11031 return remote_read_qxfer ("exec-file", annex, readbuf, offset,
11033 &remote_protocol_packets[PACKET_qXfer_exec_file]);
11036 return TARGET_XFER_E_IO;
11039 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
11040 large enough let the caller deal with it. */
11041 if (len < get_remote_packet_size ())
11042 return TARGET_XFER_E_IO;
11043 len = get_remote_packet_size ();
11045 /* Except for querying the minimum buffer size, target must be open. */
11046 if (!rs->remote_desc)
11047 error (_("remote query is only available after target open"));
11049 gdb_assert (annex != NULL);
11050 gdb_assert (readbuf != NULL);
11054 *p2++ = query_type;
11056 /* We used one buffer char for the remote protocol q command and
11057 another for the query type. As the remote protocol encapsulation
11058 uses 4 chars plus one extra in case we are debugging
11059 (remote_debug), we have PBUFZIZ - 7 left to pack the query
11062 while (annex[i] && (i < (get_remote_packet_size () - 8)))
11064 /* Bad caller may have sent forbidden characters. */
11065 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
11070 gdb_assert (annex[i] == '\0');
11072 i = putpkt (rs->buf);
11074 return TARGET_XFER_E_IO;
11076 getpkt (&rs->buf, &rs->buf_size, 0);
11077 strcpy ((char *) readbuf, rs->buf);
11079 *xfered_len = strlen ((char *) readbuf);
11080 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
11083 /* Implementation of to_get_memory_xfer_limit. */
11086 remote_target::get_memory_xfer_limit ()
11088 return get_memory_write_packet_size ();
11092 remote_target::search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
11093 const gdb_byte *pattern, ULONGEST pattern_len,
11094 CORE_ADDR *found_addrp)
11096 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
11097 struct remote_state *rs = get_remote_state ();
11098 int max_size = get_memory_write_packet_size ();
11099 struct packet_config *packet =
11100 &remote_protocol_packets[PACKET_qSearch_memory];
11101 /* Number of packet bytes used to encode the pattern;
11102 this could be more than PATTERN_LEN due to escape characters. */
11103 int escaped_pattern_len;
11104 /* Amount of pattern that was encodable in the packet. */
11105 int used_pattern_len;
11108 ULONGEST found_addr;
11110 /* Don't go to the target if we don't have to. This is done before
11111 checking packet_config_support to avoid the possibility that a
11112 success for this edge case means the facility works in
11114 if (pattern_len > search_space_len)
11116 if (pattern_len == 0)
11118 *found_addrp = start_addr;
11122 /* If we already know the packet isn't supported, fall back to the simple
11123 way of searching memory. */
11125 if (packet_config_support (packet) == PACKET_DISABLE)
11127 /* Target doesn't provided special support, fall back and use the
11128 standard support (copy memory and do the search here). */
11129 return simple_search_memory (this, start_addr, search_space_len,
11130 pattern, pattern_len, found_addrp);
11133 /* Make sure the remote is pointing at the right process. */
11134 set_general_process ();
11136 /* Insert header. */
11137 i = snprintf (rs->buf, max_size,
11138 "qSearch:memory:%s;%s;",
11139 phex_nz (start_addr, addr_size),
11140 phex_nz (search_space_len, sizeof (search_space_len)));
11141 max_size -= (i + 1);
11143 /* Escape as much data as fits into rs->buf. */
11144 escaped_pattern_len =
11145 remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
11146 &used_pattern_len, max_size);
11148 /* Bail if the pattern is too large. */
11149 if (used_pattern_len != pattern_len)
11150 error (_("Pattern is too large to transmit to remote target."));
11152 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
11153 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
11154 || packet_ok (rs->buf, packet) != PACKET_OK)
11156 /* The request may not have worked because the command is not
11157 supported. If so, fall back to the simple way. */
11158 if (packet_config_support (packet) == PACKET_DISABLE)
11160 return simple_search_memory (this, start_addr, search_space_len,
11161 pattern, pattern_len, found_addrp);
11166 if (rs->buf[0] == '0')
11168 else if (rs->buf[0] == '1')
11171 if (rs->buf[1] != ',')
11172 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
11173 unpack_varlen_hex (rs->buf + 2, &found_addr);
11174 *found_addrp = found_addr;
11177 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
11183 remote_target::rcmd (const char *command, struct ui_file *outbuf)
11185 struct remote_state *rs = get_remote_state ();
11188 if (!rs->remote_desc)
11189 error (_("remote rcmd is only available after target open"));
11191 /* Send a NULL command across as an empty command. */
11192 if (command == NULL)
11195 /* The query prefix. */
11196 strcpy (rs->buf, "qRcmd,");
11197 p = strchr (rs->buf, '\0');
11199 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
11200 > get_remote_packet_size ())
11201 error (_("\"monitor\" command ``%s'' is too long."), command);
11203 /* Encode the actual command. */
11204 bin2hex ((const gdb_byte *) command, p, strlen (command));
11206 if (putpkt (rs->buf) < 0)
11207 error (_("Communication problem with target."));
11209 /* get/display the response */
11214 /* XXX - see also remote_get_noisy_reply(). */
11215 QUIT; /* Allow user to bail out with ^C. */
11217 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
11219 /* Timeout. Continue to (try to) read responses.
11220 This is better than stopping with an error, assuming the stub
11221 is still executing the (long) monitor command.
11222 If needed, the user can interrupt gdb using C-c, obtaining
11223 an effect similar to stop on timeout. */
11227 if (buf[0] == '\0')
11228 error (_("Target does not support this command."));
11229 if (buf[0] == 'O' && buf[1] != 'K')
11231 remote_console_output (buf + 1); /* 'O' message from stub. */
11234 if (strcmp (buf, "OK") == 0)
11236 if (strlen (buf) == 3 && buf[0] == 'E'
11237 && isdigit (buf[1]) && isdigit (buf[2]))
11239 error (_("Protocol error with Rcmd"));
11241 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
11243 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
11245 fputc_unfiltered (c, outbuf);
11251 std::vector<mem_region>
11252 remote_target::memory_map ()
11254 std::vector<mem_region> result;
11255 gdb::optional<gdb::char_vector> text
11256 = target_read_stralloc (current_top_target (), TARGET_OBJECT_MEMORY_MAP, NULL);
11259 result = parse_memory_map (text->data ());
11265 packet_command (const char *args, int from_tty)
11267 remote_target *remote = get_current_remote_target ();
11269 if (remote == nullptr)
11270 error (_("command can only be used with remote target"));
11272 remote->packet_command (args, from_tty);
11276 remote_target::packet_command (const char *args, int from_tty)
11279 error (_("remote-packet command requires packet text as argument"));
11281 puts_filtered ("sending: ");
11282 print_packet (args);
11283 puts_filtered ("\n");
11286 remote_state *rs = get_remote_state ();
11288 getpkt (&rs->buf, &rs->buf_size, 0);
11289 puts_filtered ("received: ");
11290 print_packet (rs->buf);
11291 puts_filtered ("\n");
11295 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
11297 static void display_thread_info (struct gdb_ext_thread_info *info);
11299 static void threadset_test_cmd (char *cmd, int tty);
11301 static void threadalive_test (char *cmd, int tty);
11303 static void threadlist_test_cmd (char *cmd, int tty);
11305 int get_and_display_threadinfo (threadref *ref);
11307 static void threadinfo_test_cmd (char *cmd, int tty);
11309 static int thread_display_step (threadref *ref, void *context);
11311 static void threadlist_update_test_cmd (char *cmd, int tty);
11313 static void init_remote_threadtests (void);
11315 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
11318 threadset_test_cmd (const char *cmd, int tty)
11320 int sample_thread = SAMPLE_THREAD;
11322 printf_filtered (_("Remote threadset test\n"));
11323 set_general_thread (sample_thread);
11328 threadalive_test (const char *cmd, int tty)
11330 int sample_thread = SAMPLE_THREAD;
11331 int pid = inferior_ptid.pid ();
11332 ptid_t ptid = ptid_t (pid, sample_thread, 0);
11334 if (remote_thread_alive (ptid))
11335 printf_filtered ("PASS: Thread alive test\n");
11337 printf_filtered ("FAIL: Thread alive test\n");
11340 void output_threadid (char *title, threadref *ref);
11343 output_threadid (char *title, threadref *ref)
11347 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
11349 printf_filtered ("%s %s\n", title, (&hexid[0]));
11353 threadlist_test_cmd (const char *cmd, int tty)
11356 threadref nextthread;
11357 int done, result_count;
11358 threadref threadlist[3];
11360 printf_filtered ("Remote Threadlist test\n");
11361 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
11362 &result_count, &threadlist[0]))
11363 printf_filtered ("FAIL: threadlist test\n");
11366 threadref *scan = threadlist;
11367 threadref *limit = scan + result_count;
11369 while (scan < limit)
11370 output_threadid (" thread ", scan++);
11375 display_thread_info (struct gdb_ext_thread_info *info)
11377 output_threadid ("Threadid: ", &info->threadid);
11378 printf_filtered ("Name: %s\n ", info->shortname);
11379 printf_filtered ("State: %s\n", info->display);
11380 printf_filtered ("other: %s\n\n", info->more_display);
11384 get_and_display_threadinfo (threadref *ref)
11388 struct gdb_ext_thread_info threadinfo;
11390 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
11391 | TAG_MOREDISPLAY | TAG_DISPLAY;
11392 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
11393 display_thread_info (&threadinfo);
11398 threadinfo_test_cmd (const char *cmd, int tty)
11400 int athread = SAMPLE_THREAD;
11404 int_to_threadref (&thread, athread);
11405 printf_filtered ("Remote Threadinfo test\n");
11406 if (!get_and_display_threadinfo (&thread))
11407 printf_filtered ("FAIL cannot get thread info\n");
11411 thread_display_step (threadref *ref, void *context)
11413 /* output_threadid(" threadstep ",ref); *//* simple test */
11414 return get_and_display_threadinfo (ref);
11418 threadlist_update_test_cmd (const char *cmd, int tty)
11420 printf_filtered ("Remote Threadlist update test\n");
11421 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
11425 init_remote_threadtests (void)
11427 add_com ("tlist", class_obscure, threadlist_test_cmd,
11428 _("Fetch and print the remote list of "
11429 "thread identifiers, one pkt only"));
11430 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
11431 _("Fetch and display info about one thread"));
11432 add_com ("tset", class_obscure, threadset_test_cmd,
11433 _("Test setting to a different thread"));
11434 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
11435 _("Iterate through updating all remote thread info"));
11436 add_com ("talive", class_obscure, threadalive_test,
11437 _(" Remote thread alive test "));
11442 /* Convert a thread ID to a string. Returns the string in a static
11446 remote_target::pid_to_str (ptid_t ptid)
11448 static char buf[64];
11449 struct remote_state *rs = get_remote_state ();
11451 if (ptid == null_ptid)
11452 return normal_pid_to_str (ptid);
11453 else if (ptid.is_pid ())
11455 /* Printing an inferior target id. */
11457 /* When multi-process extensions are off, there's no way in the
11458 remote protocol to know the remote process id, if there's any
11459 at all. There's one exception --- when we're connected with
11460 target extended-remote, and we manually attached to a process
11461 with "attach PID". We don't record anywhere a flag that
11462 allows us to distinguish that case from the case of
11463 connecting with extended-remote and the stub already being
11464 attached to a process, and reporting yes to qAttached, hence
11465 no smart special casing here. */
11466 if (!remote_multi_process_p (rs))
11468 xsnprintf (buf, sizeof buf, "Remote target");
11472 return normal_pid_to_str (ptid);
11476 if (magic_null_ptid == ptid)
11477 xsnprintf (buf, sizeof buf, "Thread <main>");
11478 else if (remote_multi_process_p (rs))
11479 if (ptid.lwp () == 0)
11480 return normal_pid_to_str (ptid);
11482 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
11483 ptid.pid (), ptid.lwp ());
11485 xsnprintf (buf, sizeof buf, "Thread %ld",
11491 /* Get the address of the thread local variable in OBJFILE which is
11492 stored at OFFSET within the thread local storage for thread PTID. */
11495 remote_target::get_thread_local_address (ptid_t ptid, CORE_ADDR lm,
11498 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
11500 struct remote_state *rs = get_remote_state ();
11502 char *endp = rs->buf + get_remote_packet_size ();
11503 enum packet_result result;
11505 strcpy (p, "qGetTLSAddr:");
11507 p = write_ptid (p, endp, ptid);
11509 p += hexnumstr (p, offset);
11511 p += hexnumstr (p, lm);
11515 getpkt (&rs->buf, &rs->buf_size, 0);
11516 result = packet_ok (rs->buf,
11517 &remote_protocol_packets[PACKET_qGetTLSAddr]);
11518 if (result == PACKET_OK)
11522 unpack_varlen_hex (rs->buf, &result);
11525 else if (result == PACKET_UNKNOWN)
11526 throw_error (TLS_GENERIC_ERROR,
11527 _("Remote target doesn't support qGetTLSAddr packet"));
11529 throw_error (TLS_GENERIC_ERROR,
11530 _("Remote target failed to process qGetTLSAddr request"));
11533 throw_error (TLS_GENERIC_ERROR,
11534 _("TLS not supported or disabled on this target"));
11539 /* Provide thread local base, i.e. Thread Information Block address.
11540 Returns 1 if ptid is found and thread_local_base is non zero. */
11543 remote_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
11545 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
11547 struct remote_state *rs = get_remote_state ();
11549 char *endp = rs->buf + get_remote_packet_size ();
11550 enum packet_result result;
11552 strcpy (p, "qGetTIBAddr:");
11554 p = write_ptid (p, endp, ptid);
11558 getpkt (&rs->buf, &rs->buf_size, 0);
11559 result = packet_ok (rs->buf,
11560 &remote_protocol_packets[PACKET_qGetTIBAddr]);
11561 if (result == PACKET_OK)
11565 unpack_varlen_hex (rs->buf, &result);
11567 *addr = (CORE_ADDR) result;
11570 else if (result == PACKET_UNKNOWN)
11571 error (_("Remote target doesn't support qGetTIBAddr packet"));
11573 error (_("Remote target failed to process qGetTIBAddr request"));
11576 error (_("qGetTIBAddr not supported or disabled on this target"));
11581 /* Support for inferring a target description based on the current
11582 architecture and the size of a 'g' packet. While the 'g' packet
11583 can have any size (since optional registers can be left off the
11584 end), some sizes are easily recognizable given knowledge of the
11585 approximate architecture. */
11587 struct remote_g_packet_guess
11590 const struct target_desc *tdesc;
11592 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
11593 DEF_VEC_O(remote_g_packet_guess_s);
11595 struct remote_g_packet_data
11597 VEC(remote_g_packet_guess_s) *guesses;
11600 static struct gdbarch_data *remote_g_packet_data_handle;
11603 remote_g_packet_data_init (struct obstack *obstack)
11605 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
11609 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
11610 const struct target_desc *tdesc)
11612 struct remote_g_packet_data *data
11613 = ((struct remote_g_packet_data *)
11614 gdbarch_data (gdbarch, remote_g_packet_data_handle));
11615 struct remote_g_packet_guess new_guess, *guess;
11618 gdb_assert (tdesc != NULL);
11621 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
11623 if (guess->bytes == bytes)
11624 internal_error (__FILE__, __LINE__,
11625 _("Duplicate g packet description added for size %d"),
11628 new_guess.bytes = bytes;
11629 new_guess.tdesc = tdesc;
11630 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
11633 /* Return 1 if remote_read_description would do anything on this target
11634 and architecture, 0 otherwise. */
11637 remote_read_description_p (struct target_ops *target)
11639 struct remote_g_packet_data *data
11640 = ((struct remote_g_packet_data *)
11641 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
11643 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
11649 const struct target_desc *
11650 remote_target::read_description ()
11652 struct remote_g_packet_data *data
11653 = ((struct remote_g_packet_data *)
11654 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
11656 /* Do not try this during initial connection, when we do not know
11657 whether there is a running but stopped thread. */
11658 if (!target_has_execution || inferior_ptid == null_ptid)
11659 return beneath ()->read_description ();
11661 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
11663 struct remote_g_packet_guess *guess;
11665 int bytes = send_g_packet ();
11668 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
11670 if (guess->bytes == bytes)
11671 return guess->tdesc;
11673 /* We discard the g packet. A minor optimization would be to
11674 hold on to it, and fill the register cache once we have selected
11675 an architecture, but it's too tricky to do safely. */
11678 return beneath ()->read_description ();
11681 /* Remote file transfer support. This is host-initiated I/O, not
11682 target-initiated; for target-initiated, see remote-fileio.c. */
11684 /* If *LEFT is at least the length of STRING, copy STRING to
11685 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11686 decrease *LEFT. Otherwise raise an error. */
11689 remote_buffer_add_string (char **buffer, int *left, const char *string)
11691 int len = strlen (string);
11694 error (_("Packet too long for target."));
11696 memcpy (*buffer, string, len);
11700 /* NUL-terminate the buffer as a convenience, if there is
11706 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
11707 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11708 decrease *LEFT. Otherwise raise an error. */
11711 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
11714 if (2 * len > *left)
11715 error (_("Packet too long for target."));
11717 bin2hex (bytes, *buffer, len);
11718 *buffer += 2 * len;
11721 /* NUL-terminate the buffer as a convenience, if there is
11727 /* If *LEFT is large enough, convert VALUE to hex and add it to
11728 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11729 decrease *LEFT. Otherwise raise an error. */
11732 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
11734 int len = hexnumlen (value);
11737 error (_("Packet too long for target."));
11739 hexnumstr (*buffer, value);
11743 /* NUL-terminate the buffer as a convenience, if there is
11749 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
11750 value, *REMOTE_ERRNO to the remote error number or zero if none
11751 was included, and *ATTACHMENT to point to the start of the annex
11752 if any. The length of the packet isn't needed here; there may
11753 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
11755 Return 0 if the packet could be parsed, -1 if it could not. If
11756 -1 is returned, the other variables may not be initialized. */
11759 remote_hostio_parse_result (char *buffer, int *retcode,
11760 int *remote_errno, char **attachment)
11765 *attachment = NULL;
11767 if (buffer[0] != 'F')
11771 *retcode = strtol (&buffer[1], &p, 16);
11772 if (errno != 0 || p == &buffer[1])
11775 /* Check for ",errno". */
11779 *remote_errno = strtol (p + 1, &p2, 16);
11780 if (errno != 0 || p + 1 == p2)
11785 /* Check for ";attachment". If there is no attachment, the
11786 packet should end here. */
11789 *attachment = p + 1;
11792 else if (*p == '\0')
11798 /* Send a prepared I/O packet to the target and read its response.
11799 The prepared packet is in the global RS->BUF before this function
11800 is called, and the answer is there when we return.
11802 COMMAND_BYTES is the length of the request to send, which may include
11803 binary data. WHICH_PACKET is the packet configuration to check
11804 before attempting a packet. If an error occurs, *REMOTE_ERRNO
11805 is set to the error number and -1 is returned. Otherwise the value
11806 returned by the function is returned.
11808 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
11809 attachment is expected; an error will be reported if there's a
11810 mismatch. If one is found, *ATTACHMENT will be set to point into
11811 the packet buffer and *ATTACHMENT_LEN will be set to the
11812 attachment's length. */
11815 remote_target::remote_hostio_send_command (int command_bytes, int which_packet,
11816 int *remote_errno, char **attachment,
11817 int *attachment_len)
11819 struct remote_state *rs = get_remote_state ();
11820 int ret, bytes_read;
11821 char *attachment_tmp;
11823 if (packet_support (which_packet) == PACKET_DISABLE)
11825 *remote_errno = FILEIO_ENOSYS;
11829 putpkt_binary (rs->buf, command_bytes);
11830 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
11832 /* If it timed out, something is wrong. Don't try to parse the
11834 if (bytes_read < 0)
11836 *remote_errno = FILEIO_EINVAL;
11840 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
11843 *remote_errno = FILEIO_EINVAL;
11845 case PACKET_UNKNOWN:
11846 *remote_errno = FILEIO_ENOSYS;
11852 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
11855 *remote_errno = FILEIO_EINVAL;
11859 /* Make sure we saw an attachment if and only if we expected one. */
11860 if ((attachment_tmp == NULL && attachment != NULL)
11861 || (attachment_tmp != NULL && attachment == NULL))
11863 *remote_errno = FILEIO_EINVAL;
11867 /* If an attachment was found, it must point into the packet buffer;
11868 work out how many bytes there were. */
11869 if (attachment_tmp != NULL)
11871 *attachment = attachment_tmp;
11872 *attachment_len = bytes_read - (*attachment - rs->buf);
11878 /* See declaration.h. */
11881 readahead_cache::invalidate ()
11886 /* See declaration.h. */
11889 readahead_cache::invalidate_fd (int fd)
11891 if (this->fd == fd)
11895 /* Set the filesystem remote_hostio functions that take FILENAME
11896 arguments will use. Return 0 on success, or -1 if an error
11897 occurs (and set *REMOTE_ERRNO). */
11900 remote_target::remote_hostio_set_filesystem (struct inferior *inf,
11903 struct remote_state *rs = get_remote_state ();
11904 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
11906 int left = get_remote_packet_size () - 1;
11910 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11913 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
11916 remote_buffer_add_string (&p, &left, "vFile:setfs:");
11918 xsnprintf (arg, sizeof (arg), "%x", required_pid);
11919 remote_buffer_add_string (&p, &left, arg);
11921 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
11922 remote_errno, NULL, NULL);
11924 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11928 rs->fs_pid = required_pid;
11933 /* Implementation of to_fileio_open. */
11936 remote_target::remote_hostio_open (inferior *inf, const char *filename,
11937 int flags, int mode, int warn_if_slow,
11940 struct remote_state *rs = get_remote_state ();
11942 int left = get_remote_packet_size () - 1;
11946 static int warning_issued = 0;
11948 printf_unfiltered (_("Reading %s from remote target...\n"),
11951 if (!warning_issued)
11953 warning (_("File transfers from remote targets can be slow."
11954 " Use \"set sysroot\" to access files locally"
11956 warning_issued = 1;
11960 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11963 remote_buffer_add_string (&p, &left, "vFile:open:");
11965 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11966 strlen (filename));
11967 remote_buffer_add_string (&p, &left, ",");
11969 remote_buffer_add_int (&p, &left, flags);
11970 remote_buffer_add_string (&p, &left, ",");
11972 remote_buffer_add_int (&p, &left, mode);
11974 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
11975 remote_errno, NULL, NULL);
11979 remote_target::fileio_open (struct inferior *inf, const char *filename,
11980 int flags, int mode, int warn_if_slow,
11983 return remote_hostio_open (inf, filename, flags, mode, warn_if_slow,
11987 /* Implementation of to_fileio_pwrite. */
11990 remote_target::remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
11991 ULONGEST offset, int *remote_errno)
11993 struct remote_state *rs = get_remote_state ();
11995 int left = get_remote_packet_size ();
11998 rs->readahead_cache.invalidate_fd (fd);
12000 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
12002 remote_buffer_add_int (&p, &left, fd);
12003 remote_buffer_add_string (&p, &left, ",");
12005 remote_buffer_add_int (&p, &left, offset);
12006 remote_buffer_add_string (&p, &left, ",");
12008 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
12009 get_remote_packet_size () - (p - rs->buf));
12011 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
12012 remote_errno, NULL, NULL);
12016 remote_target::fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
12017 ULONGEST offset, int *remote_errno)
12019 return remote_hostio_pwrite (fd, write_buf, len, offset, remote_errno);
12022 /* Helper for the implementation of to_fileio_pread. Read the file
12023 from the remote side with vFile:pread. */
12026 remote_target::remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
12027 ULONGEST offset, int *remote_errno)
12029 struct remote_state *rs = get_remote_state ();
12032 int left = get_remote_packet_size ();
12033 int ret, attachment_len;
12036 remote_buffer_add_string (&p, &left, "vFile:pread:");
12038 remote_buffer_add_int (&p, &left, fd);
12039 remote_buffer_add_string (&p, &left, ",");
12041 remote_buffer_add_int (&p, &left, len);
12042 remote_buffer_add_string (&p, &left, ",");
12044 remote_buffer_add_int (&p, &left, offset);
12046 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
12047 remote_errno, &attachment,
12053 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12055 if (read_len != ret)
12056 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
12061 /* See declaration.h. */
12064 readahead_cache::pread (int fd, gdb_byte *read_buf, size_t len,
12068 && this->offset <= offset
12069 && offset < this->offset + this->bufsize)
12071 ULONGEST max = this->offset + this->bufsize;
12073 if (offset + len > max)
12074 len = max - offset;
12076 memcpy (read_buf, this->buf + offset - this->offset, len);
12083 /* Implementation of to_fileio_pread. */
12086 remote_target::remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
12087 ULONGEST offset, int *remote_errno)
12090 struct remote_state *rs = get_remote_state ();
12091 readahead_cache *cache = &rs->readahead_cache;
12093 ret = cache->pread (fd, read_buf, len, offset);
12096 cache->hit_count++;
12099 fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
12100 pulongest (cache->hit_count));
12104 cache->miss_count++;
12106 fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
12107 pulongest (cache->miss_count));
12110 cache->offset = offset;
12111 cache->bufsize = get_remote_packet_size ();
12112 cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
12114 ret = remote_hostio_pread_vFile (cache->fd, cache->buf, cache->bufsize,
12115 cache->offset, remote_errno);
12118 cache->invalidate_fd (fd);
12122 cache->bufsize = ret;
12123 return cache->pread (fd, read_buf, len, offset);
12127 remote_target::fileio_pread (int fd, gdb_byte *read_buf, int len,
12128 ULONGEST offset, int *remote_errno)
12130 return remote_hostio_pread (fd, read_buf, len, offset, remote_errno);
12133 /* Implementation of to_fileio_close. */
12136 remote_target::remote_hostio_close (int fd, int *remote_errno)
12138 struct remote_state *rs = get_remote_state ();
12140 int left = get_remote_packet_size () - 1;
12142 rs->readahead_cache.invalidate_fd (fd);
12144 remote_buffer_add_string (&p, &left, "vFile:close:");
12146 remote_buffer_add_int (&p, &left, fd);
12148 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
12149 remote_errno, NULL, NULL);
12153 remote_target::fileio_close (int fd, int *remote_errno)
12155 return remote_hostio_close (fd, remote_errno);
12158 /* Implementation of to_fileio_unlink. */
12161 remote_target::remote_hostio_unlink (inferior *inf, const char *filename,
12164 struct remote_state *rs = get_remote_state ();
12166 int left = get_remote_packet_size () - 1;
12168 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12171 remote_buffer_add_string (&p, &left, "vFile:unlink:");
12173 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12174 strlen (filename));
12176 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
12177 remote_errno, NULL, NULL);
12181 remote_target::fileio_unlink (struct inferior *inf, const char *filename,
12184 return remote_hostio_unlink (inf, filename, remote_errno);
12187 /* Implementation of to_fileio_readlink. */
12189 gdb::optional<std::string>
12190 remote_target::fileio_readlink (struct inferior *inf, const char *filename,
12193 struct remote_state *rs = get_remote_state ();
12196 int left = get_remote_packet_size ();
12197 int len, attachment_len;
12200 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12203 remote_buffer_add_string (&p, &left, "vFile:readlink:");
12205 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12206 strlen (filename));
12208 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
12209 remote_errno, &attachment,
12215 std::string ret (len, '\0');
12217 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12218 (gdb_byte *) &ret[0], len);
12219 if (read_len != len)
12220 error (_("Readlink returned %d, but %d bytes."), len, read_len);
12225 /* Implementation of to_fileio_fstat. */
12228 remote_target::fileio_fstat (int fd, struct stat *st, int *remote_errno)
12230 struct remote_state *rs = get_remote_state ();
12232 int left = get_remote_packet_size ();
12233 int attachment_len, ret;
12235 struct fio_stat fst;
12238 remote_buffer_add_string (&p, &left, "vFile:fstat:");
12240 remote_buffer_add_int (&p, &left, fd);
12242 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
12243 remote_errno, &attachment,
12247 if (*remote_errno != FILEIO_ENOSYS)
12250 /* Strictly we should return -1, ENOSYS here, but when
12251 "set sysroot remote:" was implemented in August 2008
12252 BFD's need for a stat function was sidestepped with
12253 this hack. This was not remedied until March 2015
12254 so we retain the previous behavior to avoid breaking
12257 Note that the memset is a March 2015 addition; older
12258 GDBs set st_size *and nothing else* so the structure
12259 would have garbage in all other fields. This might
12260 break something but retaining the previous behavior
12261 here would be just too wrong. */
12263 memset (st, 0, sizeof (struct stat));
12264 st->st_size = INT_MAX;
12268 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12269 (gdb_byte *) &fst, sizeof (fst));
12271 if (read_len != ret)
12272 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
12274 if (read_len != sizeof (fst))
12275 error (_("vFile:fstat returned %d bytes, but expecting %d."),
12276 read_len, (int) sizeof (fst));
12278 remote_fileio_to_host_stat (&fst, st);
12283 /* Implementation of to_filesystem_is_local. */
12286 remote_target::filesystem_is_local ()
12288 /* Valgrind GDB presents itself as a remote target but works
12289 on the local filesystem: it does not implement remote get
12290 and users are not expected to set a sysroot. To handle
12291 this case we treat the remote filesystem as local if the
12292 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
12293 does not support vFile:open. */
12294 if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
12296 enum packet_support ps = packet_support (PACKET_vFile_open);
12298 if (ps == PACKET_SUPPORT_UNKNOWN)
12300 int fd, remote_errno;
12302 /* Try opening a file to probe support. The supplied
12303 filename is irrelevant, we only care about whether
12304 the stub recognizes the packet or not. */
12305 fd = remote_hostio_open (NULL, "just probing",
12306 FILEIO_O_RDONLY, 0700, 0,
12310 remote_hostio_close (fd, &remote_errno);
12312 ps = packet_support (PACKET_vFile_open);
12315 if (ps == PACKET_DISABLE)
12317 static int warning_issued = 0;
12319 if (!warning_issued)
12321 warning (_("remote target does not support file"
12322 " transfer, attempting to access files"
12323 " from local filesystem."));
12324 warning_issued = 1;
12335 remote_fileio_errno_to_host (int errnum)
12341 case FILEIO_ENOENT:
12349 case FILEIO_EACCES:
12351 case FILEIO_EFAULT:
12355 case FILEIO_EEXIST:
12357 case FILEIO_ENODEV:
12359 case FILEIO_ENOTDIR:
12361 case FILEIO_EISDIR:
12363 case FILEIO_EINVAL:
12365 case FILEIO_ENFILE:
12367 case FILEIO_EMFILE:
12371 case FILEIO_ENOSPC:
12373 case FILEIO_ESPIPE:
12377 case FILEIO_ENOSYS:
12379 case FILEIO_ENAMETOOLONG:
12380 return ENAMETOOLONG;
12386 remote_hostio_error (int errnum)
12388 int host_error = remote_fileio_errno_to_host (errnum);
12390 if (host_error == -1)
12391 error (_("Unknown remote I/O error %d"), errnum);
12393 error (_("Remote I/O error: %s"), safe_strerror (host_error));
12396 /* A RAII wrapper around a remote file descriptor. */
12398 class scoped_remote_fd
12401 scoped_remote_fd (remote_target *remote, int fd)
12402 : m_remote (remote), m_fd (fd)
12406 ~scoped_remote_fd ()
12413 m_remote->remote_hostio_close (m_fd, &remote_errno);
12417 /* Swallow exception before it escapes the dtor. If
12418 something goes wrong, likely the connection is gone,
12419 and there's nothing else that can be done. */
12424 DISABLE_COPY_AND_ASSIGN (scoped_remote_fd);
12426 /* Release ownership of the file descriptor, and return it. */
12427 int release () noexcept
12434 /* Return the owned file descriptor. */
12435 int get () const noexcept
12441 /* The remote target. */
12442 remote_target *m_remote;
12444 /* The owned remote I/O file descriptor. */
12449 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
12451 remote_target *remote = get_current_remote_target ();
12453 if (remote == nullptr)
12454 error (_("command can only be used with remote target"));
12456 remote->remote_file_put (local_file, remote_file, from_tty);
12460 remote_target::remote_file_put (const char *local_file, const char *remote_file,
12463 int retcode, remote_errno, bytes, io_size;
12464 int bytes_in_buffer;
12468 gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
12470 perror_with_name (local_file);
12472 scoped_remote_fd fd
12473 (this, remote_hostio_open (NULL,
12474 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
12476 0700, 0, &remote_errno));
12477 if (fd.get () == -1)
12478 remote_hostio_error (remote_errno);
12480 /* Send up to this many bytes at once. They won't all fit in the
12481 remote packet limit, so we'll transfer slightly fewer. */
12482 io_size = get_remote_packet_size ();
12483 gdb::byte_vector buffer (io_size);
12485 bytes_in_buffer = 0;
12488 while (bytes_in_buffer || !saw_eof)
12492 bytes = fread (buffer.data () + bytes_in_buffer, 1,
12493 io_size - bytes_in_buffer,
12497 if (ferror (file.get ()))
12498 error (_("Error reading %s."), local_file);
12501 /* EOF. Unless there is something still in the
12502 buffer from the last iteration, we are done. */
12504 if (bytes_in_buffer == 0)
12512 bytes += bytes_in_buffer;
12513 bytes_in_buffer = 0;
12515 retcode = remote_hostio_pwrite (fd.get (), buffer.data (), bytes,
12516 offset, &remote_errno);
12519 remote_hostio_error (remote_errno);
12520 else if (retcode == 0)
12521 error (_("Remote write of %d bytes returned 0!"), bytes);
12522 else if (retcode < bytes)
12524 /* Short write. Save the rest of the read data for the next
12526 bytes_in_buffer = bytes - retcode;
12527 memmove (buffer.data (), buffer.data () + retcode, bytes_in_buffer);
12533 if (remote_hostio_close (fd.release (), &remote_errno))
12534 remote_hostio_error (remote_errno);
12537 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
12541 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
12543 remote_target *remote = get_current_remote_target ();
12545 if (remote == nullptr)
12546 error (_("command can only be used with remote target"));
12548 remote->remote_file_get (remote_file, local_file, from_tty);
12552 remote_target::remote_file_get (const char *remote_file, const char *local_file,
12555 int remote_errno, bytes, io_size;
12558 scoped_remote_fd fd
12559 (this, remote_hostio_open (NULL,
12560 remote_file, FILEIO_O_RDONLY, 0, 0,
12562 if (fd.get () == -1)
12563 remote_hostio_error (remote_errno);
12565 gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
12567 perror_with_name (local_file);
12569 /* Send up to this many bytes at once. They won't all fit in the
12570 remote packet limit, so we'll transfer slightly fewer. */
12571 io_size = get_remote_packet_size ();
12572 gdb::byte_vector buffer (io_size);
12577 bytes = remote_hostio_pread (fd.get (), buffer.data (), io_size, offset,
12580 /* Success, but no bytes, means end-of-file. */
12583 remote_hostio_error (remote_errno);
12587 bytes = fwrite (buffer.data (), 1, bytes, file.get ());
12589 perror_with_name (local_file);
12592 if (remote_hostio_close (fd.release (), &remote_errno))
12593 remote_hostio_error (remote_errno);
12596 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
12600 remote_file_delete (const char *remote_file, int from_tty)
12602 remote_target *remote = get_current_remote_target ();
12604 if (remote == nullptr)
12605 error (_("command can only be used with remote target"));
12607 remote->remote_file_delete (remote_file, from_tty);
12611 remote_target::remote_file_delete (const char *remote_file, int from_tty)
12613 int retcode, remote_errno;
12615 retcode = remote_hostio_unlink (NULL, remote_file, &remote_errno);
12617 remote_hostio_error (remote_errno);
12620 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
12624 remote_put_command (const char *args, int from_tty)
12627 error_no_arg (_("file to put"));
12629 gdb_argv argv (args);
12630 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12631 error (_("Invalid parameters to remote put"));
12633 remote_file_put (argv[0], argv[1], from_tty);
12637 remote_get_command (const char *args, int from_tty)
12640 error_no_arg (_("file to get"));
12642 gdb_argv argv (args);
12643 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12644 error (_("Invalid parameters to remote get"));
12646 remote_file_get (argv[0], argv[1], from_tty);
12650 remote_delete_command (const char *args, int from_tty)
12653 error_no_arg (_("file to delete"));
12655 gdb_argv argv (args);
12656 if (argv[0] == NULL || argv[1] != NULL)
12657 error (_("Invalid parameters to remote delete"));
12659 remote_file_delete (argv[0], from_tty);
12663 remote_command (const char *args, int from_tty)
12665 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
12669 remote_target::can_execute_reverse ()
12671 if (packet_support (PACKET_bs) == PACKET_ENABLE
12672 || packet_support (PACKET_bc) == PACKET_ENABLE)
12679 remote_target::supports_non_stop ()
12685 remote_target::supports_disable_randomization ()
12687 /* Only supported in extended mode. */
12692 remote_target::supports_multi_process ()
12694 struct remote_state *rs = get_remote_state ();
12696 return remote_multi_process_p (rs);
12700 remote_supports_cond_tracepoints ()
12702 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
12706 remote_target::supports_evaluation_of_breakpoint_conditions ()
12708 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
12712 remote_supports_fast_tracepoints ()
12714 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
12718 remote_supports_static_tracepoints ()
12720 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
12724 remote_supports_install_in_trace ()
12726 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
12730 remote_target::supports_enable_disable_tracepoint ()
12732 return (packet_support (PACKET_EnableDisableTracepoints_feature)
12737 remote_target::supports_string_tracing ()
12739 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
12743 remote_target::can_run_breakpoint_commands ()
12745 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
12749 remote_target::trace_init ()
12751 struct remote_state *rs = get_remote_state ();
12754 remote_get_noisy_reply ();
12755 if (strcmp (rs->buf, "OK") != 0)
12756 error (_("Target does not support this command."));
12759 /* Recursive routine to walk through command list including loops, and
12760 download packets for each command. */
12763 remote_target::remote_download_command_source (int num, ULONGEST addr,
12764 struct command_line *cmds)
12766 struct remote_state *rs = get_remote_state ();
12767 struct command_line *cmd;
12769 for (cmd = cmds; cmd; cmd = cmd->next)
12771 QUIT; /* Allow user to bail out with ^C. */
12772 strcpy (rs->buf, "QTDPsrc:");
12773 encode_source_string (num, addr, "cmd", cmd->line,
12774 rs->buf + strlen (rs->buf),
12775 rs->buf_size - strlen (rs->buf));
12777 remote_get_noisy_reply ();
12778 if (strcmp (rs->buf, "OK"))
12779 warning (_("Target does not support source download."));
12781 if (cmd->control_type == while_control
12782 || cmd->control_type == while_stepping_control)
12784 remote_download_command_source (num, addr, cmd->body_list_0.get ());
12786 QUIT; /* Allow user to bail out with ^C. */
12787 strcpy (rs->buf, "QTDPsrc:");
12788 encode_source_string (num, addr, "cmd", "end",
12789 rs->buf + strlen (rs->buf),
12790 rs->buf_size - strlen (rs->buf));
12792 remote_get_noisy_reply ();
12793 if (strcmp (rs->buf, "OK"))
12794 warning (_("Target does not support source download."));
12800 remote_target::download_tracepoint (struct bp_location *loc)
12802 #define BUF_SIZE 2048
12806 char buf[BUF_SIZE];
12807 std::vector<std::string> tdp_actions;
12808 std::vector<std::string> stepping_actions;
12810 struct breakpoint *b = loc->owner;
12811 struct tracepoint *t = (struct tracepoint *) b;
12812 struct remote_state *rs = get_remote_state ();
12814 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
12816 tpaddr = loc->address;
12817 sprintf_vma (addrbuf, tpaddr);
12818 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
12819 addrbuf, /* address */
12820 (b->enable_state == bp_enabled ? 'E' : 'D'),
12821 t->step_count, t->pass_count);
12822 /* Fast tracepoints are mostly handled by the target, but we can
12823 tell the target how big of an instruction block should be moved
12825 if (b->type == bp_fast_tracepoint)
12827 /* Only test for support at download time; we may not know
12828 target capabilities at definition time. */
12829 if (remote_supports_fast_tracepoints ())
12831 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
12833 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
12834 gdb_insn_length (loc->gdbarch, tpaddr));
12836 /* If it passed validation at definition but fails now,
12837 something is very wrong. */
12838 internal_error (__FILE__, __LINE__,
12839 _("Fast tracepoint not "
12840 "valid during download"));
12843 /* Fast tracepoints are functionally identical to regular
12844 tracepoints, so don't take lack of support as a reason to
12845 give up on the trace run. */
12846 warning (_("Target does not support fast tracepoints, "
12847 "downloading %d as regular tracepoint"), b->number);
12849 else if (b->type == bp_static_tracepoint)
12851 /* Only test for support at download time; we may not know
12852 target capabilities at definition time. */
12853 if (remote_supports_static_tracepoints ())
12855 struct static_tracepoint_marker marker;
12857 if (target_static_tracepoint_marker_at (tpaddr, &marker))
12858 strcat (buf, ":S");
12860 error (_("Static tracepoint not valid during download"));
12863 /* Fast tracepoints are functionally identical to regular
12864 tracepoints, so don't take lack of support as a reason
12865 to give up on the trace run. */
12866 error (_("Target does not support static tracepoints"));
12868 /* If the tracepoint has a conditional, make it into an agent
12869 expression and append to the definition. */
12872 /* Only test support at download time, we may not know target
12873 capabilities at definition time. */
12874 if (remote_supports_cond_tracepoints ())
12876 agent_expr_up aexpr = gen_eval_for_expr (tpaddr, loc->cond.get ());
12877 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
12879 pkt = buf + strlen (buf);
12880 for (int ndx = 0; ndx < aexpr->len; ++ndx)
12881 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
12885 warning (_("Target does not support conditional tracepoints, "
12886 "ignoring tp %d cond"), b->number);
12889 if (b->commands || *default_collect)
12892 remote_get_noisy_reply ();
12893 if (strcmp (rs->buf, "OK"))
12894 error (_("Target does not support tracepoints."));
12896 /* do_single_steps (t); */
12897 for (auto action_it = tdp_actions.begin ();
12898 action_it != tdp_actions.end (); action_it++)
12900 QUIT; /* Allow user to bail out with ^C. */
12902 bool has_more = (action_it != tdp_actions.end ()
12903 || !stepping_actions.empty ());
12905 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
12906 b->number, addrbuf, /* address */
12907 action_it->c_str (),
12908 has_more ? '-' : 0);
12910 remote_get_noisy_reply ();
12911 if (strcmp (rs->buf, "OK"))
12912 error (_("Error on target while setting tracepoints."));
12915 for (auto action_it = stepping_actions.begin ();
12916 action_it != stepping_actions.end (); action_it++)
12918 QUIT; /* Allow user to bail out with ^C. */
12920 bool is_first = action_it == stepping_actions.begin ();
12921 bool has_more = action_it != stepping_actions.end ();
12923 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
12924 b->number, addrbuf, /* address */
12925 is_first ? "S" : "",
12926 action_it->c_str (),
12927 has_more ? "-" : "");
12929 remote_get_noisy_reply ();
12930 if (strcmp (rs->buf, "OK"))
12931 error (_("Error on target while setting tracepoints."));
12934 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
12936 if (b->location != NULL)
12938 strcpy (buf, "QTDPsrc:");
12939 encode_source_string (b->number, loc->address, "at",
12940 event_location_to_string (b->location.get ()),
12941 buf + strlen (buf), 2048 - strlen (buf));
12943 remote_get_noisy_reply ();
12944 if (strcmp (rs->buf, "OK"))
12945 warning (_("Target does not support source download."));
12947 if (b->cond_string)
12949 strcpy (buf, "QTDPsrc:");
12950 encode_source_string (b->number, loc->address,
12951 "cond", b->cond_string, buf + strlen (buf),
12952 2048 - strlen (buf));
12954 remote_get_noisy_reply ();
12955 if (strcmp (rs->buf, "OK"))
12956 warning (_("Target does not support source download."));
12958 remote_download_command_source (b->number, loc->address,
12959 breakpoint_commands (b));
12964 remote_target::can_download_tracepoint ()
12966 struct remote_state *rs = get_remote_state ();
12967 struct trace_status *ts;
12970 /* Don't try to install tracepoints until we've relocated our
12971 symbols, and fetched and merged the target's tracepoint list with
12973 if (rs->starting_up)
12976 ts = current_trace_status ();
12977 status = get_trace_status (ts);
12979 if (status == -1 || !ts->running_known || !ts->running)
12982 /* If we are in a tracing experiment, but remote stub doesn't support
12983 installing tracepoint in trace, we have to return. */
12984 if (!remote_supports_install_in_trace ())
12992 remote_target::download_trace_state_variable (const trace_state_variable &tsv)
12994 struct remote_state *rs = get_remote_state ();
12997 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
12998 tsv.number, phex ((ULONGEST) tsv.initial_value, 8),
13000 p = rs->buf + strlen (rs->buf);
13001 if ((p - rs->buf) + tsv.name.length () * 2 >= get_remote_packet_size ())
13002 error (_("Trace state variable name too long for tsv definition packet"));
13003 p += 2 * bin2hex ((gdb_byte *) (tsv.name.data ()), p, tsv.name.length ());
13006 remote_get_noisy_reply ();
13007 if (*rs->buf == '\0')
13008 error (_("Target does not support this command."));
13009 if (strcmp (rs->buf, "OK") != 0)
13010 error (_("Error on target while downloading trace state variable."));
13014 remote_target::enable_tracepoint (struct bp_location *location)
13016 struct remote_state *rs = get_remote_state ();
13019 sprintf_vma (addr_buf, location->address);
13020 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
13021 location->owner->number, addr_buf);
13023 remote_get_noisy_reply ();
13024 if (*rs->buf == '\0')
13025 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
13026 if (strcmp (rs->buf, "OK") != 0)
13027 error (_("Error on target while enabling tracepoint."));
13031 remote_target::disable_tracepoint (struct bp_location *location)
13033 struct remote_state *rs = get_remote_state ();
13036 sprintf_vma (addr_buf, location->address);
13037 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
13038 location->owner->number, addr_buf);
13040 remote_get_noisy_reply ();
13041 if (*rs->buf == '\0')
13042 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
13043 if (strcmp (rs->buf, "OK") != 0)
13044 error (_("Error on target while disabling tracepoint."));
13048 remote_target::trace_set_readonly_regions ()
13052 bfd_size_type size;
13058 return; /* No information to give. */
13060 struct remote_state *rs = get_remote_state ();
13062 strcpy (rs->buf, "QTro");
13063 offset = strlen (rs->buf);
13064 for (s = exec_bfd->sections; s; s = s->next)
13066 char tmp1[40], tmp2[40];
13069 if ((s->flags & SEC_LOAD) == 0 ||
13070 /* (s->flags & SEC_CODE) == 0 || */
13071 (s->flags & SEC_READONLY) == 0)
13075 vma = bfd_get_section_vma (abfd, s);
13076 size = bfd_get_section_size (s);
13077 sprintf_vma (tmp1, vma);
13078 sprintf_vma (tmp2, vma + size);
13079 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
13080 if (offset + sec_length + 1 > rs->buf_size)
13082 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
13084 Too many sections for read-only sections definition packet."));
13087 xsnprintf (rs->buf + offset, rs->buf_size - offset, ":%s,%s",
13089 offset += sec_length;
13094 getpkt (&rs->buf, &rs->buf_size, 0);
13099 remote_target::trace_start ()
13101 struct remote_state *rs = get_remote_state ();
13103 putpkt ("QTStart");
13104 remote_get_noisy_reply ();
13105 if (*rs->buf == '\0')
13106 error (_("Target does not support this command."));
13107 if (strcmp (rs->buf, "OK") != 0)
13108 error (_("Bogus reply from target: %s"), rs->buf);
13112 remote_target::get_trace_status (struct trace_status *ts)
13114 /* Initialize it just to avoid a GCC false warning. */
13116 /* FIXME we need to get register block size some other way. */
13117 extern int trace_regblock_size;
13118 enum packet_result result;
13119 struct remote_state *rs = get_remote_state ();
13121 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
13124 trace_regblock_size
13125 = rs->get_remote_arch_state (target_gdbarch ())->sizeof_g_packet;
13127 putpkt ("qTStatus");
13131 p = remote_get_noisy_reply ();
13133 CATCH (ex, RETURN_MASK_ERROR)
13135 if (ex.error != TARGET_CLOSE_ERROR)
13137 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
13140 throw_exception (ex);
13144 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
13146 /* If the remote target doesn't do tracing, flag it. */
13147 if (result == PACKET_UNKNOWN)
13150 /* We're working with a live target. */
13151 ts->filename = NULL;
13154 error (_("Bogus trace status reply from target: %s"), rs->buf);
13156 /* Function 'parse_trace_status' sets default value of each field of
13157 'ts' at first, so we don't have to do it here. */
13158 parse_trace_status (p, ts);
13160 return ts->running;
13164 remote_target::get_tracepoint_status (struct breakpoint *bp,
13165 struct uploaded_tp *utp)
13167 struct remote_state *rs = get_remote_state ();
13169 struct bp_location *loc;
13170 struct tracepoint *tp = (struct tracepoint *) bp;
13171 size_t size = get_remote_packet_size ();
13176 tp->traceframe_usage = 0;
13177 for (loc = tp->loc; loc; loc = loc->next)
13179 /* If the tracepoint was never downloaded, don't go asking for
13181 if (tp->number_on_target == 0)
13183 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
13184 phex_nz (loc->address, 0));
13186 reply = remote_get_noisy_reply ();
13187 if (reply && *reply)
13190 parse_tracepoint_status (reply + 1, bp, utp);
13196 utp->hit_count = 0;
13197 utp->traceframe_usage = 0;
13198 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
13199 phex_nz (utp->addr, 0));
13201 reply = remote_get_noisy_reply ();
13202 if (reply && *reply)
13205 parse_tracepoint_status (reply + 1, bp, utp);
13211 remote_target::trace_stop ()
13213 struct remote_state *rs = get_remote_state ();
13216 remote_get_noisy_reply ();
13217 if (*rs->buf == '\0')
13218 error (_("Target does not support this command."));
13219 if (strcmp (rs->buf, "OK") != 0)
13220 error (_("Bogus reply from target: %s"), rs->buf);
13224 remote_target::trace_find (enum trace_find_type type, int num,
13225 CORE_ADDR addr1, CORE_ADDR addr2,
13228 struct remote_state *rs = get_remote_state ();
13229 char *endbuf = rs->buf + get_remote_packet_size ();
13231 int target_frameno = -1, target_tracept = -1;
13233 /* Lookups other than by absolute frame number depend on the current
13234 trace selected, so make sure it is correct on the remote end
13236 if (type != tfind_number)
13237 set_remote_traceframe ();
13240 strcpy (p, "QTFrame:");
13241 p = strchr (p, '\0');
13245 xsnprintf (p, endbuf - p, "%x", num);
13248 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
13251 xsnprintf (p, endbuf - p, "tdp:%x", num);
13254 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
13255 phex_nz (addr2, 0));
13257 case tfind_outside:
13258 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
13259 phex_nz (addr2, 0));
13262 error (_("Unknown trace find type %d"), type);
13266 reply = remote_get_noisy_reply ();
13267 if (*reply == '\0')
13268 error (_("Target does not support this command."));
13270 while (reply && *reply)
13275 target_frameno = (int) strtol (p, &reply, 16);
13277 error (_("Unable to parse trace frame number"));
13278 /* Don't update our remote traceframe number cache on failure
13279 to select a remote traceframe. */
13280 if (target_frameno == -1)
13285 target_tracept = (int) strtol (p, &reply, 16);
13287 error (_("Unable to parse tracepoint number"));
13289 case 'O': /* "OK"? */
13290 if (reply[1] == 'K' && reply[2] == '\0')
13293 error (_("Bogus reply from target: %s"), reply);
13296 error (_("Bogus reply from target: %s"), reply);
13299 *tpp = target_tracept;
13301 rs->remote_traceframe_number = target_frameno;
13302 return target_frameno;
13306 remote_target::get_trace_state_variable_value (int tsvnum, LONGEST *val)
13308 struct remote_state *rs = get_remote_state ();
13312 set_remote_traceframe ();
13314 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
13316 reply = remote_get_noisy_reply ();
13317 if (reply && *reply)
13321 unpack_varlen_hex (reply + 1, &uval);
13322 *val = (LONGEST) uval;
13330 remote_target::save_trace_data (const char *filename)
13332 struct remote_state *rs = get_remote_state ();
13336 strcpy (p, "QTSave:");
13338 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
13339 error (_("Remote file name too long for trace save packet"));
13340 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
13343 reply = remote_get_noisy_reply ();
13344 if (*reply == '\0')
13345 error (_("Target does not support this command."));
13346 if (strcmp (reply, "OK") != 0)
13347 error (_("Bogus reply from target: %s"), reply);
13351 /* This is basically a memory transfer, but needs to be its own packet
13352 because we don't know how the target actually organizes its trace
13353 memory, plus we want to be able to ask for as much as possible, but
13354 not be unhappy if we don't get as much as we ask for. */
13357 remote_target::get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
13359 struct remote_state *rs = get_remote_state ();
13365 strcpy (p, "qTBuffer:");
13367 p += hexnumstr (p, offset);
13369 p += hexnumstr (p, len);
13373 reply = remote_get_noisy_reply ();
13374 if (reply && *reply)
13376 /* 'l' by itself means we're at the end of the buffer and
13377 there is nothing more to get. */
13381 /* Convert the reply into binary. Limit the number of bytes to
13382 convert according to our passed-in buffer size, rather than
13383 what was returned in the packet; if the target is
13384 unexpectedly generous and gives us a bigger reply than we
13385 asked for, we don't want to crash. */
13386 rslt = hex2bin (reply, buf, len);
13390 /* Something went wrong, flag as an error. */
13395 remote_target::set_disconnected_tracing (int val)
13397 struct remote_state *rs = get_remote_state ();
13399 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
13403 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
13405 reply = remote_get_noisy_reply ();
13406 if (*reply == '\0')
13407 error (_("Target does not support this command."));
13408 if (strcmp (reply, "OK") != 0)
13409 error (_("Bogus reply from target: %s"), reply);
13412 warning (_("Target does not support disconnected tracing."));
13416 remote_target::core_of_thread (ptid_t ptid)
13418 struct thread_info *info = find_thread_ptid (ptid);
13420 if (info != NULL && info->priv != NULL)
13421 return get_remote_thread_info (info)->core;
13427 remote_target::set_circular_trace_buffer (int val)
13429 struct remote_state *rs = get_remote_state ();
13432 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
13434 reply = remote_get_noisy_reply ();
13435 if (*reply == '\0')
13436 error (_("Target does not support this command."));
13437 if (strcmp (reply, "OK") != 0)
13438 error (_("Bogus reply from target: %s"), reply);
13442 remote_target::traceframe_info ()
13444 gdb::optional<gdb::char_vector> text
13445 = target_read_stralloc (current_top_target (), TARGET_OBJECT_TRACEFRAME_INFO,
13448 return parse_traceframe_info (text->data ());
13453 /* Handle the qTMinFTPILen packet. Returns the minimum length of
13454 instruction on which a fast tracepoint may be placed. Returns -1
13455 if the packet is not supported, and 0 if the minimum instruction
13456 length is unknown. */
13459 remote_target::get_min_fast_tracepoint_insn_len ()
13461 struct remote_state *rs = get_remote_state ();
13464 /* If we're not debugging a process yet, the IPA can't be
13466 if (!target_has_execution)
13469 /* Make sure the remote is pointing at the right process. */
13470 set_general_process ();
13472 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
13474 reply = remote_get_noisy_reply ();
13475 if (*reply == '\0')
13479 ULONGEST min_insn_len;
13481 unpack_varlen_hex (reply, &min_insn_len);
13483 return (int) min_insn_len;
13488 remote_target::set_trace_buffer_size (LONGEST val)
13490 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
13492 struct remote_state *rs = get_remote_state ();
13493 char *buf = rs->buf;
13494 char *endbuf = rs->buf + get_remote_packet_size ();
13495 enum packet_result result;
13497 gdb_assert (val >= 0 || val == -1);
13498 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
13499 /* Send -1 as literal "-1" to avoid host size dependency. */
13503 buf += hexnumstr (buf, (ULONGEST) -val);
13506 buf += hexnumstr (buf, (ULONGEST) val);
13509 remote_get_noisy_reply ();
13510 result = packet_ok (rs->buf,
13511 &remote_protocol_packets[PACKET_QTBuffer_size]);
13513 if (result != PACKET_OK)
13514 warning (_("Bogus reply from target: %s"), rs->buf);
13519 remote_target::set_trace_notes (const char *user, const char *notes,
13520 const char *stop_notes)
13522 struct remote_state *rs = get_remote_state ();
13524 char *buf = rs->buf;
13525 char *endbuf = rs->buf + get_remote_packet_size ();
13528 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
13531 buf += xsnprintf (buf, endbuf - buf, "user:");
13532 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
13538 buf += xsnprintf (buf, endbuf - buf, "notes:");
13539 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
13545 buf += xsnprintf (buf, endbuf - buf, "tstop:");
13546 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
13550 /* Ensure the buffer is terminated. */
13554 reply = remote_get_noisy_reply ();
13555 if (*reply == '\0')
13558 if (strcmp (reply, "OK") != 0)
13559 error (_("Bogus reply from target: %s"), reply);
13565 remote_target::use_agent (bool use)
13567 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
13569 struct remote_state *rs = get_remote_state ();
13571 /* If the stub supports QAgent. */
13572 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
13574 getpkt (&rs->buf, &rs->buf_size, 0);
13576 if (strcmp (rs->buf, "OK") == 0)
13587 remote_target::can_use_agent ()
13589 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
13592 struct btrace_target_info
13594 /* The ptid of the traced thread. */
13597 /* The obtained branch trace configuration. */
13598 struct btrace_config conf;
13601 /* Reset our idea of our target's btrace configuration. */
13604 remote_btrace_reset (remote_state *rs)
13606 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
13609 /* Synchronize the configuration with the target. */
13612 remote_target::btrace_sync_conf (const btrace_config *conf)
13614 struct packet_config *packet;
13615 struct remote_state *rs;
13616 char *buf, *pos, *endbuf;
13618 rs = get_remote_state ();
13620 endbuf = buf + get_remote_packet_size ();
13622 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
13623 if (packet_config_support (packet) == PACKET_ENABLE
13624 && conf->bts.size != rs->btrace_config.bts.size)
13627 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13631 getpkt (&buf, &rs->buf_size, 0);
13633 if (packet_ok (buf, packet) == PACKET_ERROR)
13635 if (buf[0] == 'E' && buf[1] == '.')
13636 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
13638 error (_("Failed to configure the BTS buffer size."));
13641 rs->btrace_config.bts.size = conf->bts.size;
13644 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
13645 if (packet_config_support (packet) == PACKET_ENABLE
13646 && conf->pt.size != rs->btrace_config.pt.size)
13649 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13653 getpkt (&buf, &rs->buf_size, 0);
13655 if (packet_ok (buf, packet) == PACKET_ERROR)
13657 if (buf[0] == 'E' && buf[1] == '.')
13658 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
13660 error (_("Failed to configure the trace buffer size."));
13663 rs->btrace_config.pt.size = conf->pt.size;
13667 /* Read the current thread's btrace configuration from the target and
13668 store it into CONF. */
13671 btrace_read_config (struct btrace_config *conf)
13673 gdb::optional<gdb::char_vector> xml
13674 = target_read_stralloc (current_top_target (), TARGET_OBJECT_BTRACE_CONF, "");
13676 parse_xml_btrace_conf (conf, xml->data ());
13679 /* Maybe reopen target btrace. */
13682 remote_target::remote_btrace_maybe_reopen ()
13684 struct remote_state *rs = get_remote_state ();
13685 struct thread_info *tp;
13686 int btrace_target_pushed = 0;
13689 scoped_restore_current_thread restore_thread;
13691 ALL_NON_EXITED_THREADS (tp)
13693 set_general_thread (tp->ptid);
13695 memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
13696 btrace_read_config (&rs->btrace_config);
13698 if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
13701 #if !defined (HAVE_LIBIPT)
13702 if (rs->btrace_config.format == BTRACE_FORMAT_PT)
13707 warning (_("Target is recording using Intel Processor Trace "
13708 "but support was disabled at compile time."));
13713 #endif /* !defined (HAVE_LIBIPT) */
13715 /* Push target, once, but before anything else happens. This way our
13716 changes to the threads will be cleaned up by unpushing the target
13717 in case btrace_read_config () throws. */
13718 if (!btrace_target_pushed)
13720 btrace_target_pushed = 1;
13721 record_btrace_push_target ();
13722 printf_filtered (_("Target is recording using %s.\n"),
13723 btrace_format_string (rs->btrace_config.format));
13726 tp->btrace.target = XCNEW (struct btrace_target_info);
13727 tp->btrace.target->ptid = tp->ptid;
13728 tp->btrace.target->conf = rs->btrace_config;
13732 /* Enable branch tracing. */
13734 struct btrace_target_info *
13735 remote_target::enable_btrace (ptid_t ptid, const struct btrace_config *conf)
13737 struct btrace_target_info *tinfo = NULL;
13738 struct packet_config *packet = NULL;
13739 struct remote_state *rs = get_remote_state ();
13740 char *buf = rs->buf;
13741 char *endbuf = rs->buf + get_remote_packet_size ();
13743 switch (conf->format)
13745 case BTRACE_FORMAT_BTS:
13746 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
13749 case BTRACE_FORMAT_PT:
13750 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
13754 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
13755 error (_("Target does not support branch tracing."));
13757 btrace_sync_conf (conf);
13759 set_general_thread (ptid);
13761 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13763 getpkt (&rs->buf, &rs->buf_size, 0);
13765 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13767 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13768 error (_("Could not enable branch tracing for %s: %s"),
13769 target_pid_to_str (ptid), rs->buf + 2);
13771 error (_("Could not enable branch tracing for %s."),
13772 target_pid_to_str (ptid));
13775 tinfo = XCNEW (struct btrace_target_info);
13776 tinfo->ptid = ptid;
13778 /* If we fail to read the configuration, we lose some information, but the
13779 tracing itself is not impacted. */
13782 btrace_read_config (&tinfo->conf);
13784 CATCH (err, RETURN_MASK_ERROR)
13786 if (err.message != NULL)
13787 warning ("%s", err.message);
13794 /* Disable branch tracing. */
13797 remote_target::disable_btrace (struct btrace_target_info *tinfo)
13799 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
13800 struct remote_state *rs = get_remote_state ();
13801 char *buf = rs->buf;
13802 char *endbuf = rs->buf + get_remote_packet_size ();
13804 if (packet_config_support (packet) != PACKET_ENABLE)
13805 error (_("Target does not support branch tracing."));
13807 set_general_thread (tinfo->ptid);
13809 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13811 getpkt (&rs->buf, &rs->buf_size, 0);
13813 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13815 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13816 error (_("Could not disable branch tracing for %s: %s"),
13817 target_pid_to_str (tinfo->ptid), rs->buf + 2);
13819 error (_("Could not disable branch tracing for %s."),
13820 target_pid_to_str (tinfo->ptid));
13826 /* Teardown branch tracing. */
13829 remote_target::teardown_btrace (struct btrace_target_info *tinfo)
13831 /* We must not talk to the target during teardown. */
13835 /* Read the branch trace. */
13838 remote_target::read_btrace (struct btrace_data *btrace,
13839 struct btrace_target_info *tinfo,
13840 enum btrace_read_type type)
13842 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
13845 if (packet_config_support (packet) != PACKET_ENABLE)
13846 error (_("Target does not support branch tracing."));
13848 #if !defined(HAVE_LIBEXPAT)
13849 error (_("Cannot process branch tracing result. XML parsing not supported."));
13854 case BTRACE_READ_ALL:
13857 case BTRACE_READ_NEW:
13860 case BTRACE_READ_DELTA:
13864 internal_error (__FILE__, __LINE__,
13865 _("Bad branch tracing read type: %u."),
13866 (unsigned int) type);
13869 gdb::optional<gdb::char_vector> xml
13870 = target_read_stralloc (current_top_target (), TARGET_OBJECT_BTRACE, annex);
13872 return BTRACE_ERR_UNKNOWN;
13874 parse_xml_btrace (btrace, xml->data ());
13876 return BTRACE_ERR_NONE;
13879 const struct btrace_config *
13880 remote_target::btrace_conf (const struct btrace_target_info *tinfo)
13882 return &tinfo->conf;
13886 remote_target::augmented_libraries_svr4_read ()
13888 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
13892 /* Implementation of to_load. */
13895 remote_target::load (const char *name, int from_tty)
13897 generic_load (name, from_tty);
13900 /* Accepts an integer PID; returns a string representing a file that
13901 can be opened on the remote side to get the symbols for the child
13902 process. Returns NULL if the operation is not supported. */
13905 remote_target::pid_to_exec_file (int pid)
13907 static gdb::optional<gdb::char_vector> filename;
13908 struct inferior *inf;
13909 char *annex = NULL;
13911 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
13914 inf = find_inferior_pid (pid);
13916 internal_error (__FILE__, __LINE__,
13917 _("not currently attached to process %d"), pid);
13919 if (!inf->fake_pid_p)
13921 const int annex_size = 9;
13923 annex = (char *) alloca (annex_size);
13924 xsnprintf (annex, annex_size, "%x", pid);
13927 filename = target_read_stralloc (current_top_target (),
13928 TARGET_OBJECT_EXEC_FILE, annex);
13930 return filename ? filename->data () : nullptr;
13933 /* Implement the to_can_do_single_step target_ops method. */
13936 remote_target::can_do_single_step ()
13938 /* We can only tell whether target supports single step or not by
13939 supported s and S vCont actions if the stub supports vContSupported
13940 feature. If the stub doesn't support vContSupported feature,
13941 we have conservatively to think target doesn't supports single
13943 if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
13945 struct remote_state *rs = get_remote_state ();
13947 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
13948 remote_vcont_probe ();
13950 return rs->supports_vCont.s && rs->supports_vCont.S;
13956 /* Implementation of the to_execution_direction method for the remote
13959 enum exec_direction_kind
13960 remote_target::execution_direction ()
13962 struct remote_state *rs = get_remote_state ();
13964 return rs->last_resume_exec_dir;
13967 /* Return pointer to the thread_info struct which corresponds to
13968 THREAD_HANDLE (having length HANDLE_LEN). */
13971 remote_target::thread_handle_to_thread_info (const gdb_byte *thread_handle,
13975 struct thread_info *tp;
13977 ALL_NON_EXITED_THREADS (tp)
13979 remote_thread_info *priv = get_remote_thread_info (tp);
13981 if (tp->inf == inf && priv != NULL)
13983 if (handle_len != priv->thread_handle.size ())
13984 error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
13985 handle_len, priv->thread_handle.size ());
13986 if (memcmp (thread_handle, priv->thread_handle.data (),
13996 remote_target::can_async_p ()
13998 struct remote_state *rs = get_remote_state ();
14000 /* We don't go async if the user has explicitly prevented it with the
14001 "maint set target-async" command. */
14002 if (!target_async_permitted)
14005 /* We're async whenever the serial device is. */
14006 return serial_can_async_p (rs->remote_desc);
14010 remote_target::is_async_p ()
14012 struct remote_state *rs = get_remote_state ();
14014 if (!target_async_permitted)
14015 /* We only enable async when the user specifically asks for it. */
14018 /* We're async whenever the serial device is. */
14019 return serial_is_async_p (rs->remote_desc);
14022 /* Pass the SERIAL event on and up to the client. One day this code
14023 will be able to delay notifying the client of an event until the
14024 point where an entire packet has been received. */
14026 static serial_event_ftype remote_async_serial_handler;
14029 remote_async_serial_handler (struct serial *scb, void *context)
14031 /* Don't propogate error information up to the client. Instead let
14032 the client find out about the error by querying the target. */
14033 inferior_event_handler (INF_REG_EVENT, NULL);
14037 remote_async_inferior_event_handler (gdb_client_data data)
14039 inferior_event_handler (INF_REG_EVENT, data);
14043 remote_target::async (int enable)
14045 struct remote_state *rs = get_remote_state ();
14049 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
14051 /* If there are pending events in the stop reply queue tell the
14052 event loop to process them. */
14053 if (!rs->stop_reply_queue.empty ())
14054 mark_async_event_handler (rs->remote_async_inferior_event_token);
14055 /* For simplicity, below we clear the pending events token
14056 without remembering whether it is marked, so here we always
14057 mark it. If there's actually no pending notification to
14058 process, this ends up being a no-op (other than a spurious
14059 event-loop wakeup). */
14060 if (target_is_non_stop_p ())
14061 mark_async_event_handler (rs->notif_state->get_pending_events_token);
14065 serial_async (rs->remote_desc, NULL, NULL);
14066 /* If the core is disabling async, it doesn't want to be
14067 disturbed with target events. Clear all async event sources
14069 clear_async_event_handler (rs->remote_async_inferior_event_token);
14070 if (target_is_non_stop_p ())
14071 clear_async_event_handler (rs->notif_state->get_pending_events_token);
14075 /* Implementation of the to_thread_events method. */
14078 remote_target::thread_events (int enable)
14080 struct remote_state *rs = get_remote_state ();
14081 size_t size = get_remote_packet_size ();
14083 if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
14086 xsnprintf (rs->buf, size, "QThreadEvents:%x", enable ? 1 : 0);
14088 getpkt (&rs->buf, &rs->buf_size, 0);
14090 switch (packet_ok (rs->buf,
14091 &remote_protocol_packets[PACKET_QThreadEvents]))
14094 if (strcmp (rs->buf, "OK") != 0)
14095 error (_("Remote refused setting thread events: %s"), rs->buf);
14098 warning (_("Remote failure reply: %s"), rs->buf);
14100 case PACKET_UNKNOWN:
14106 set_remote_cmd (const char *args, int from_tty)
14108 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
14112 show_remote_cmd (const char *args, int from_tty)
14114 /* We can't just use cmd_show_list here, because we want to skip
14115 the redundant "show remote Z-packet" and the legacy aliases. */
14116 struct cmd_list_element *list = remote_show_cmdlist;
14117 struct ui_out *uiout = current_uiout;
14119 ui_out_emit_tuple tuple_emitter (uiout, "showlist");
14120 for (; list != NULL; list = list->next)
14121 if (strcmp (list->name, "Z-packet") == 0)
14123 else if (list->type == not_set_cmd)
14124 /* Alias commands are exactly like the original, except they
14125 don't have the normal type. */
14129 ui_out_emit_tuple option_emitter (uiout, "option");
14131 uiout->field_string ("name", list->name);
14132 uiout->text (": ");
14133 if (list->type == show_cmd)
14134 do_show_command (NULL, from_tty, list);
14136 cmd_func (list, NULL, from_tty);
14141 /* Function to be called whenever a new objfile (shlib) is detected. */
14143 remote_new_objfile (struct objfile *objfile)
14145 remote_target *remote = get_current_remote_target ();
14147 if (remote != NULL) /* Have a remote connection. */
14148 remote->remote_check_symbols ();
14151 /* Pull all the tracepoints defined on the target and create local
14152 data structures representing them. We don't want to create real
14153 tracepoints yet, we don't want to mess up the user's existing
14157 remote_target::upload_tracepoints (struct uploaded_tp **utpp)
14159 struct remote_state *rs = get_remote_state ();
14162 /* Ask for a first packet of tracepoint definition. */
14164 getpkt (&rs->buf, &rs->buf_size, 0);
14166 while (*p && *p != 'l')
14168 parse_tracepoint_definition (p, utpp);
14169 /* Ask for another packet of tracepoint definition. */
14171 getpkt (&rs->buf, &rs->buf_size, 0);
14178 remote_target::upload_trace_state_variables (struct uploaded_tsv **utsvp)
14180 struct remote_state *rs = get_remote_state ();
14183 /* Ask for a first packet of variable definition. */
14185 getpkt (&rs->buf, &rs->buf_size, 0);
14187 while (*p && *p != 'l')
14189 parse_tsv_definition (p, utsvp);
14190 /* Ask for another packet of variable definition. */
14192 getpkt (&rs->buf, &rs->buf_size, 0);
14198 /* The "set/show range-stepping" show hook. */
14201 show_range_stepping (struct ui_file *file, int from_tty,
14202 struct cmd_list_element *c,
14205 fprintf_filtered (file,
14206 _("Debugger's willingness to use range stepping "
14207 "is %s.\n"), value);
14210 /* Return true if the vCont;r action is supported by the remote
14214 remote_target::vcont_r_supported ()
14216 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
14217 remote_vcont_probe ();
14219 return (packet_support (PACKET_vCont) == PACKET_ENABLE
14220 && get_remote_state ()->supports_vCont.r);
14223 /* The "set/show range-stepping" set hook. */
14226 set_range_stepping (const char *ignore_args, int from_tty,
14227 struct cmd_list_element *c)
14229 /* When enabling, check whether range stepping is actually supported
14230 by the target, and warn if not. */
14231 if (use_range_stepping)
14233 remote_target *remote = get_current_remote_target ();
14235 || !remote->vcont_r_supported ())
14236 warning (_("Range stepping is not supported by the current target"));
14241 _initialize_remote (void)
14243 struct cmd_list_element *cmd;
14244 const char *cmd_name;
14246 /* architecture specific data */
14247 remote_g_packet_data_handle =
14248 gdbarch_data_register_pre_init (remote_g_packet_data_init);
14251 = register_program_space_data_with_cleanup (NULL,
14252 remote_pspace_data_cleanup);
14254 add_target (remote_target_info, remote_target::open);
14255 add_target (extended_remote_target_info, extended_remote_target::open);
14257 /* Hook into new objfile notification. */
14258 gdb::observers::new_objfile.attach (remote_new_objfile);
14261 init_remote_threadtests ();
14264 /* set/show remote ... */
14266 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
14267 Remote protocol specific variables\n\
14268 Configure various remote-protocol specific variables such as\n\
14269 the packets being used"),
14270 &remote_set_cmdlist, "set remote ",
14271 0 /* allow-unknown */, &setlist);
14272 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
14273 Remote protocol specific variables\n\
14274 Configure various remote-protocol specific variables such as\n\
14275 the packets being used"),
14276 &remote_show_cmdlist, "show remote ",
14277 0 /* allow-unknown */, &showlist);
14279 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
14280 Compare section data on target to the exec file.\n\
14281 Argument is a single section name (default: all loaded sections).\n\
14282 To compare only read-only loaded sections, specify the -r option."),
14285 add_cmd ("packet", class_maintenance, packet_command, _("\
14286 Send an arbitrary packet to a remote target.\n\
14287 maintenance packet TEXT\n\
14288 If GDB is talking to an inferior via the GDB serial protocol, then\n\
14289 this command sends the string TEXT to the inferior, and displays the\n\
14290 response packet. GDB supplies the initial `$' character, and the\n\
14291 terminating `#' character and checksum."),
14294 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
14295 Set whether to send break if interrupted."), _("\
14296 Show whether to send break if interrupted."), _("\
14297 If set, a break, instead of a cntrl-c, is sent to the remote target."),
14298 set_remotebreak, show_remotebreak,
14299 &setlist, &showlist);
14300 cmd_name = "remotebreak";
14301 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
14302 deprecate_cmd (cmd, "set remote interrupt-sequence");
14303 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
14304 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
14305 deprecate_cmd (cmd, "show remote interrupt-sequence");
14307 add_setshow_enum_cmd ("interrupt-sequence", class_support,
14308 interrupt_sequence_modes, &interrupt_sequence_mode,
14310 Set interrupt sequence to remote target."), _("\
14311 Show interrupt sequence to remote target."), _("\
14312 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
14313 NULL, show_interrupt_sequence,
14314 &remote_set_cmdlist,
14315 &remote_show_cmdlist);
14317 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
14318 &interrupt_on_connect, _("\
14319 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
14320 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
14321 If set, interrupt sequence is sent to remote target."),
14323 &remote_set_cmdlist, &remote_show_cmdlist);
14325 /* Install commands for configuring memory read/write packets. */
14327 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
14328 Set the maximum number of bytes per memory write packet (deprecated)."),
14330 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
14331 Show the maximum number of bytes per memory write packet (deprecated)."),
14333 add_cmd ("memory-write-packet-size", no_class,
14334 set_memory_write_packet_size, _("\
14335 Set the maximum number of bytes per memory-write packet.\n\
14336 Specify the number of bytes in a packet or 0 (zero) for the\n\
14337 default packet size. The actual limit is further reduced\n\
14338 dependent on the target. Specify ``fixed'' to disable the\n\
14339 further restriction and ``limit'' to enable that restriction."),
14340 &remote_set_cmdlist);
14341 add_cmd ("memory-read-packet-size", no_class,
14342 set_memory_read_packet_size, _("\
14343 Set the maximum number of bytes per memory-read packet.\n\
14344 Specify the number of bytes in a packet or 0 (zero) for the\n\
14345 default packet size. The actual limit is further reduced\n\
14346 dependent on the target. Specify ``fixed'' to disable the\n\
14347 further restriction and ``limit'' to enable that restriction."),
14348 &remote_set_cmdlist);
14349 add_cmd ("memory-write-packet-size", no_class,
14350 show_memory_write_packet_size,
14351 _("Show the maximum number of bytes per memory-write packet."),
14352 &remote_show_cmdlist);
14353 add_cmd ("memory-read-packet-size", no_class,
14354 show_memory_read_packet_size,
14355 _("Show the maximum number of bytes per memory-read packet."),
14356 &remote_show_cmdlist);
14358 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
14359 &remote_hw_watchpoint_limit, _("\
14360 Set the maximum number of target hardware watchpoints."), _("\
14361 Show the maximum number of target hardware watchpoints."), _("\
14362 Specify a negative limit for unlimited."),
14363 NULL, NULL, /* FIXME: i18n: The maximum
14364 number of target hardware
14365 watchpoints is %s. */
14366 &remote_set_cmdlist, &remote_show_cmdlist);
14367 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
14368 &remote_hw_watchpoint_length_limit, _("\
14369 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
14370 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
14371 Specify a negative limit for unlimited."),
14372 NULL, NULL, /* FIXME: i18n: The maximum
14373 length (in bytes) of a target
14374 hardware watchpoint is %s. */
14375 &remote_set_cmdlist, &remote_show_cmdlist);
14376 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
14377 &remote_hw_breakpoint_limit, _("\
14378 Set the maximum number of target hardware breakpoints."), _("\
14379 Show the maximum number of target hardware breakpoints."), _("\
14380 Specify a negative limit for unlimited."),
14381 NULL, NULL, /* FIXME: i18n: The maximum
14382 number of target hardware
14383 breakpoints is %s. */
14384 &remote_set_cmdlist, &remote_show_cmdlist);
14386 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
14387 &remote_address_size, _("\
14388 Set the maximum size of the address (in bits) in a memory packet."), _("\
14389 Show the maximum size of the address (in bits) in a memory packet."), NULL,
14391 NULL, /* FIXME: i18n: */
14392 &setlist, &showlist);
14394 init_all_packet_configs ();
14396 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
14397 "X", "binary-download", 1);
14399 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
14400 "vCont", "verbose-resume", 0);
14402 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
14403 "QPassSignals", "pass-signals", 0);
14405 add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
14406 "QCatchSyscalls", "catch-syscalls", 0);
14408 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
14409 "QProgramSignals", "program-signals", 0);
14411 add_packet_config_cmd (&remote_protocol_packets[PACKET_QSetWorkingDir],
14412 "QSetWorkingDir", "set-working-dir", 0);
14414 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartupWithShell],
14415 "QStartupWithShell", "startup-with-shell", 0);
14417 add_packet_config_cmd (&remote_protocol_packets
14418 [PACKET_QEnvironmentHexEncoded],
14419 "QEnvironmentHexEncoded", "environment-hex-encoded",
14422 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentReset],
14423 "QEnvironmentReset", "environment-reset",
14426 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentUnset],
14427 "QEnvironmentUnset", "environment-unset",
14430 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
14431 "qSymbol", "symbol-lookup", 0);
14433 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
14434 "P", "set-register", 1);
14436 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
14437 "p", "fetch-register", 1);
14439 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
14440 "Z0", "software-breakpoint", 0);
14442 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
14443 "Z1", "hardware-breakpoint", 0);
14445 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
14446 "Z2", "write-watchpoint", 0);
14448 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
14449 "Z3", "read-watchpoint", 0);
14451 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
14452 "Z4", "access-watchpoint", 0);
14454 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
14455 "qXfer:auxv:read", "read-aux-vector", 0);
14457 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
14458 "qXfer:exec-file:read", "pid-to-exec-file", 0);
14460 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
14461 "qXfer:features:read", "target-features", 0);
14463 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
14464 "qXfer:libraries:read", "library-info", 0);
14466 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
14467 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
14469 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
14470 "qXfer:memory-map:read", "memory-map", 0);
14472 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
14473 "qXfer:spu:read", "read-spu-object", 0);
14475 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
14476 "qXfer:spu:write", "write-spu-object", 0);
14478 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
14479 "qXfer:osdata:read", "osdata", 0);
14481 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
14482 "qXfer:threads:read", "threads", 0);
14484 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
14485 "qXfer:siginfo:read", "read-siginfo-object", 0);
14487 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
14488 "qXfer:siginfo:write", "write-siginfo-object", 0);
14490 add_packet_config_cmd
14491 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
14492 "qXfer:traceframe-info:read", "traceframe-info", 0);
14494 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
14495 "qXfer:uib:read", "unwind-info-block", 0);
14497 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
14498 "qGetTLSAddr", "get-thread-local-storage-address",
14501 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
14502 "qGetTIBAddr", "get-thread-information-block-address",
14505 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
14506 "bc", "reverse-continue", 0);
14508 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
14509 "bs", "reverse-step", 0);
14511 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
14512 "qSupported", "supported-packets", 0);
14514 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
14515 "qSearch:memory", "search-memory", 0);
14517 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
14518 "qTStatus", "trace-status", 0);
14520 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
14521 "vFile:setfs", "hostio-setfs", 0);
14523 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
14524 "vFile:open", "hostio-open", 0);
14526 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
14527 "vFile:pread", "hostio-pread", 0);
14529 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
14530 "vFile:pwrite", "hostio-pwrite", 0);
14532 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
14533 "vFile:close", "hostio-close", 0);
14535 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
14536 "vFile:unlink", "hostio-unlink", 0);
14538 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
14539 "vFile:readlink", "hostio-readlink", 0);
14541 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
14542 "vFile:fstat", "hostio-fstat", 0);
14544 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
14545 "vAttach", "attach", 0);
14547 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
14550 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
14551 "QStartNoAckMode", "noack", 0);
14553 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
14554 "vKill", "kill", 0);
14556 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
14557 "qAttached", "query-attached", 0);
14559 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
14560 "ConditionalTracepoints",
14561 "conditional-tracepoints", 0);
14563 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
14564 "ConditionalBreakpoints",
14565 "conditional-breakpoints", 0);
14567 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
14568 "BreakpointCommands",
14569 "breakpoint-commands", 0);
14571 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
14572 "FastTracepoints", "fast-tracepoints", 0);
14574 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
14575 "TracepointSource", "TracepointSource", 0);
14577 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
14578 "QAllow", "allow", 0);
14580 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
14581 "StaticTracepoints", "static-tracepoints", 0);
14583 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
14584 "InstallInTrace", "install-in-trace", 0);
14586 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
14587 "qXfer:statictrace:read", "read-sdata-object", 0);
14589 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
14590 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
14592 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
14593 "QDisableRandomization", "disable-randomization", 0);
14595 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
14596 "QAgent", "agent", 0);
14598 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
14599 "QTBuffer:size", "trace-buffer-size", 0);
14601 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
14602 "Qbtrace:off", "disable-btrace", 0);
14604 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
14605 "Qbtrace:bts", "enable-btrace-bts", 0);
14607 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
14608 "Qbtrace:pt", "enable-btrace-pt", 0);
14610 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
14611 "qXfer:btrace", "read-btrace", 0);
14613 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
14614 "qXfer:btrace-conf", "read-btrace-conf", 0);
14616 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
14617 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
14619 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
14620 "multiprocess-feature", "multiprocess-feature", 0);
14622 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
14623 "swbreak-feature", "swbreak-feature", 0);
14625 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
14626 "hwbreak-feature", "hwbreak-feature", 0);
14628 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
14629 "fork-event-feature", "fork-event-feature", 0);
14631 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
14632 "vfork-event-feature", "vfork-event-feature", 0);
14634 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
14635 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
14637 add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
14638 "vContSupported", "verbose-resume-supported", 0);
14640 add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
14641 "exec-event-feature", "exec-event-feature", 0);
14643 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
14644 "vCtrlC", "ctrl-c", 0);
14646 add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
14647 "QThreadEvents", "thread-events", 0);
14649 add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
14650 "N stop reply", "no-resumed-stop-reply", 0);
14652 /* Assert that we've registered "set remote foo-packet" commands
14653 for all packet configs. */
14657 for (i = 0; i < PACKET_MAX; i++)
14659 /* Ideally all configs would have a command associated. Some
14660 still don't though. */
14665 case PACKET_QNonStop:
14666 case PACKET_EnableDisableTracepoints_feature:
14667 case PACKET_tracenz_feature:
14668 case PACKET_DisconnectedTracing_feature:
14669 case PACKET_augmented_libraries_svr4_read_feature:
14671 /* Additions to this list need to be well justified:
14672 pre-existing packets are OK; new packets are not. */
14680 /* This catches both forgetting to add a config command, and
14681 forgetting to remove a packet from the exception list. */
14682 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
14686 /* Keep the old ``set remote Z-packet ...'' working. Each individual
14687 Z sub-packet has its own set and show commands, but users may
14688 have sets to this variable in their .gdbinit files (or in their
14690 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
14691 &remote_Z_packet_detect, _("\
14692 Set use of remote protocol `Z' packets"), _("\
14693 Show use of remote protocol `Z' packets "), _("\
14694 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
14696 set_remote_protocol_Z_packet_cmd,
14697 show_remote_protocol_Z_packet_cmd,
14698 /* FIXME: i18n: Use of remote protocol
14699 `Z' packets is %s. */
14700 &remote_set_cmdlist, &remote_show_cmdlist);
14702 add_prefix_cmd ("remote", class_files, remote_command, _("\
14703 Manipulate files on the remote system\n\
14704 Transfer files to and from the remote target system."),
14705 &remote_cmdlist, "remote ",
14706 0 /* allow-unknown */, &cmdlist);
14708 add_cmd ("put", class_files, remote_put_command,
14709 _("Copy a local file to the remote system."),
14712 add_cmd ("get", class_files, remote_get_command,
14713 _("Copy a remote file to the local system."),
14716 add_cmd ("delete", class_files, remote_delete_command,
14717 _("Delete a remote file."),
14720 add_setshow_string_noescape_cmd ("exec-file", class_files,
14721 &remote_exec_file_var, _("\
14722 Set the remote pathname for \"run\""), _("\
14723 Show the remote pathname for \"run\""), NULL,
14724 set_remote_exec_file,
14725 show_remote_exec_file,
14726 &remote_set_cmdlist,
14727 &remote_show_cmdlist);
14729 add_setshow_boolean_cmd ("range-stepping", class_run,
14730 &use_range_stepping, _("\
14731 Enable or disable range stepping."), _("\
14732 Show whether target-assisted range stepping is enabled."), _("\
14733 If on, and the target supports it, when stepping a source line, GDB\n\
14734 tells the target to step the corresponding range of addresses itself instead\n\
14735 of issuing multiple single-steps. This speeds up source level\n\
14736 stepping. If off, GDB always issues single-steps, even if range\n\
14737 stepping is supported by the target. The default is on."),
14738 set_range_stepping,
14739 show_range_stepping,
14743 /* Eventually initialize fileio. See fileio.c */
14744 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
14746 /* Take advantage of the fact that the TID field is not used, to tag
14747 special ptids with it set to != 0. */
14748 magic_null_ptid = ptid_t (42000, -1, 1);
14749 not_sent_ptid = ptid_t (42000, -2, 1);
14750 any_thread_ptid = ptid_t (42000, 0, 1);