1 /* Remote target communications for serial-line targets in custom GDB protocol
3 Copyright (C) 1988-2018 Free Software Foundation, Inc.
5 This file is part of GDB.
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
20 /* See the GDB User Guide for details of the GDB remote protocol. */
30 /*#include "terminal.h" */
33 #include "gdb-stabs.h"
34 #include "gdbthread.h"
36 #include "remote-notif.h"
39 #include "observable.h"
41 #include "cli/cli-decode.h"
42 #include "cli/cli-setshow.h"
43 #include "target-descriptions.h"
45 #include "filestuff.h"
50 #include "gdb_sys_time.h"
52 #include "event-loop.h"
53 #include "event-top.h"
59 #include "gdbcore.h" /* for exec_bfd */
61 #include "remote-fileio.h"
62 #include "gdb/fileio.h"
64 #include "xml-support.h"
66 #include "memory-map.h"
68 #include "tracepoint.h"
73 #include "record-btrace.h"
75 #include "common/scoped_restore.h"
77 #include "common/byte-vector.h"
79 /* The remote target. */
81 static const char remote_doc[] = N_("\
82 Use a remote computer via a serial line, using a gdb-specific protocol.\n\
83 Specify the serial device it is connected to\n\
84 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).");
86 static const target_info remote_target_info = {
88 N_("Remote serial target in gdb-specific protocol"),
92 class remote_target : public target_ops
97 to_stratum = process_stratum;
100 const target_info &info () const override
101 { return remote_target_info; }
103 thread_control_capabilities get_thread_control_capabilities () override
104 { return tc_schedlock; }
106 /* Open a remote connection. */
107 static void open (const char *, int);
109 void close () override;
111 void detach (inferior *, int) override;
112 void disconnect (const char *, int) override;
114 void commit_resume () override;
115 void resume (ptid_t, int, enum gdb_signal) override;
116 ptid_t wait (ptid_t, struct target_waitstatus *, int) override;
118 void fetch_registers (struct regcache *, int) override;
119 void store_registers (struct regcache *, int) override;
120 void prepare_to_store (struct regcache *) override;
122 void files_info () override;
124 int insert_breakpoint (struct gdbarch *, struct bp_target_info *) override;
126 int remove_breakpoint (struct gdbarch *, struct bp_target_info *,
127 enum remove_bp_reason) override;
130 bool stopped_by_sw_breakpoint () override;
131 bool supports_stopped_by_sw_breakpoint () override;
133 bool stopped_by_hw_breakpoint () override;
135 bool supports_stopped_by_hw_breakpoint () override;
137 bool stopped_by_watchpoint () override;
139 bool stopped_data_address (CORE_ADDR *) override;
141 bool watchpoint_addr_within_range (CORE_ADDR, CORE_ADDR, int) override;
143 int can_use_hw_breakpoint (enum bptype, int, int) override;
145 int insert_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
147 int remove_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
149 int region_ok_for_hw_watchpoint (CORE_ADDR, int) override;
151 int insert_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
152 struct expression *) override;
154 int remove_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
155 struct expression *) override;
157 void kill () override;
159 void load (const char *, int) override;
161 void mourn_inferior () override;
163 void pass_signals (int, unsigned char *) override;
165 int set_syscall_catchpoint (int, bool, int,
166 gdb::array_view<const int>) override;
168 void program_signals (int, unsigned char *) override;
170 bool thread_alive (ptid_t ptid) override;
172 const char *thread_name (struct thread_info *) override;
174 void update_thread_list () override;
176 const char *pid_to_str (ptid_t) override;
178 const char *extra_thread_info (struct thread_info *) override;
180 ptid_t get_ada_task_ptid (long lwp, long thread) override;
182 thread_info *thread_handle_to_thread_info (const gdb_byte *thread_handle,
184 inferior *inf) override;
186 void stop (ptid_t) override;
188 void interrupt () override;
190 void pass_ctrlc () override;
192 enum target_xfer_status xfer_partial (enum target_object object,
195 const gdb_byte *writebuf,
196 ULONGEST offset, ULONGEST len,
197 ULONGEST *xfered_len) override;
199 ULONGEST get_memory_xfer_limit () override;
201 void rcmd (const char *command, struct ui_file *output) override;
203 char *pid_to_exec_file (int pid) override;
205 void log_command (const char *cmd) override
207 serial_log_command (this, cmd);
210 CORE_ADDR get_thread_local_address (ptid_t ptid,
211 CORE_ADDR load_module_addr,
212 CORE_ADDR offset) override;
214 bool has_all_memory () override { return default_child_has_all_memory (); }
215 bool has_memory () override { return default_child_has_memory (); }
216 bool has_stack () override { return default_child_has_stack (); }
217 bool has_registers () override { return default_child_has_registers (); }
218 bool has_execution (ptid_t ptid) override { return default_child_has_execution (ptid); }
220 bool can_execute_reverse () override;
222 std::vector<mem_region> memory_map () override;
224 void flash_erase (ULONGEST address, LONGEST length) override;
226 void flash_done () override;
228 const struct target_desc *read_description () override;
230 int search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
231 const gdb_byte *pattern, ULONGEST pattern_len,
232 CORE_ADDR *found_addrp) override;
234 bool can_async_p () override;
236 bool is_async_p () override;
238 void async (int) override;
240 void thread_events (int) override;
242 int can_do_single_step () override;
244 void terminal_inferior () override;
246 void terminal_ours () override;
248 bool supports_non_stop () override;
250 bool supports_multi_process () override;
252 bool supports_disable_randomization () override;
254 bool filesystem_is_local () override;
257 int fileio_open (struct inferior *inf, const char *filename,
258 int flags, int mode, int warn_if_slow,
259 int *target_errno) override;
261 int fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
262 ULONGEST offset, int *target_errno) override;
264 int fileio_pread (int fd, gdb_byte *read_buf, int len,
265 ULONGEST offset, int *target_errno) override;
267 int fileio_fstat (int fd, struct stat *sb, int *target_errno) override;
269 int fileio_close (int fd, int *target_errno) override;
271 int fileio_unlink (struct inferior *inf,
272 const char *filename,
273 int *target_errno) override;
275 gdb::optional<std::string>
276 fileio_readlink (struct inferior *inf,
277 const char *filename,
278 int *target_errno) override;
280 bool supports_enable_disable_tracepoint () override;
282 bool supports_string_tracing () override;
284 bool supports_evaluation_of_breakpoint_conditions () override;
286 bool can_run_breakpoint_commands () override;
288 void trace_init () override;
290 void download_tracepoint (struct bp_location *location) override;
292 bool can_download_tracepoint () override;
294 void download_trace_state_variable (const trace_state_variable &tsv) override;
296 void enable_tracepoint (struct bp_location *location) override;
298 void disable_tracepoint (struct bp_location *location) override;
300 void trace_set_readonly_regions () override;
302 void trace_start () override;
304 int get_trace_status (struct trace_status *ts) override;
306 void get_tracepoint_status (struct breakpoint *tp, struct uploaded_tp *utp)
309 void trace_stop () override;
311 int trace_find (enum trace_find_type type, int num,
312 CORE_ADDR addr1, CORE_ADDR addr2, int *tpp) override;
314 bool get_trace_state_variable_value (int tsv, LONGEST *val) override;
316 int save_trace_data (const char *filename) override;
318 int upload_tracepoints (struct uploaded_tp **utpp) override;
320 int upload_trace_state_variables (struct uploaded_tsv **utsvp) override;
322 LONGEST get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len) override;
324 int get_min_fast_tracepoint_insn_len () override;
326 void set_disconnected_tracing (int val) override;
328 void set_circular_trace_buffer (int val) override;
330 void set_trace_buffer_size (LONGEST val) override;
332 bool set_trace_notes (const char *user, const char *notes,
333 const char *stopnotes) override;
335 int core_of_thread (ptid_t ptid) override;
337 int verify_memory (const gdb_byte *data,
338 CORE_ADDR memaddr, ULONGEST size) override;
341 bool get_tib_address (ptid_t ptid, CORE_ADDR *addr) override;
343 void set_permissions () override;
345 bool static_tracepoint_marker_at (CORE_ADDR,
346 struct static_tracepoint_marker *marker)
349 std::vector<static_tracepoint_marker>
350 static_tracepoint_markers_by_strid (const char *id) override;
352 traceframe_info_up traceframe_info () override;
354 bool use_agent (bool use) override;
355 bool can_use_agent () override;
357 struct btrace_target_info *enable_btrace (ptid_t ptid,
358 const struct btrace_config *conf) override;
360 void disable_btrace (struct btrace_target_info *tinfo) override;
362 void teardown_btrace (struct btrace_target_info *tinfo) override;
364 enum btrace_error read_btrace (struct btrace_data *data,
365 struct btrace_target_info *btinfo,
366 enum btrace_read_type type) override;
368 const struct btrace_config *btrace_conf (const struct btrace_target_info *) override;
369 bool augmented_libraries_svr4_read () override;
370 int follow_fork (int, int) override;
371 void follow_exec (struct inferior *, char *) override;
372 int insert_fork_catchpoint (int) override;
373 int remove_fork_catchpoint (int) override;
374 int insert_vfork_catchpoint (int) override;
375 int remove_vfork_catchpoint (int) override;
376 int insert_exec_catchpoint (int) override;
377 int remove_exec_catchpoint (int) override;
378 enum exec_direction_kind execution_direction () override;
381 static void open_1 (const char *name, int from_tty, int extended_p);
382 void start_remote (int from_tty, int extended_p);
385 static const target_info extended_remote_target_info = {
387 N_("Extended remote serial target in gdb-specific protocol"),
391 /* Set up the extended remote target by extending the standard remote
392 target and adding to it. */
394 class extended_remote_target final : public remote_target
397 const target_info &info () const override
398 { return extended_remote_target_info; }
400 /* Open an extended-remote connection. */
401 static void open (const char *, int);
403 bool can_create_inferior () override { return true; }
404 void create_inferior (const char *, const std::string &,
405 char **, int) override;
407 void detach (inferior *, int) override;
409 bool can_attach () override { return true; }
410 void attach (const char *, int) override;
412 void post_attach (int) override;
413 bool supports_disable_randomization () override;
416 /* Per-program-space data key. */
417 static const struct program_space_data *remote_pspace_data;
419 /* The variable registered as the control variable used by the
420 remote exec-file commands. While the remote exec-file setting is
421 per-program-space, the set/show machinery uses this as the
422 location of the remote exec-file value. */
423 static char *remote_exec_file_var;
425 /* The size to align memory write packets, when practical. The protocol
426 does not guarantee any alignment, and gdb will generate short
427 writes and unaligned writes, but even as a best-effort attempt this
428 can improve bulk transfers. For instance, if a write is misaligned
429 relative to the target's data bus, the stub may need to make an extra
430 round trip fetching data from the target. This doesn't make a
431 huge difference, but it's easy to do, so we try to be helpful.
433 The alignment chosen is arbitrary; usually data bus width is
434 important here, not the possibly larger cache line size. */
435 enum { REMOTE_ALIGN_WRITES = 16 };
437 /* Prototypes for local functions. */
438 static int getpkt_sane (char **buf, long *sizeof_buf, int forever);
439 static int getpkt_or_notif_sane (char **buf, long *sizeof_buf,
440 int forever, int *is_notif);
444 static int remote_vkill (int pid, struct remote_state *rs);
446 static void remote_kill_k (void);
448 static int readchar (int timeout);
450 static void remote_serial_write (const char *str, int len);
452 static void interrupt_query (void);
454 static void set_general_thread (ptid_t ptid);
455 static void set_continue_thread (ptid_t ptid);
457 static void get_offsets (void);
459 static void skip_frame (void);
461 static long read_frame (char **buf_p, long *sizeof_buf);
463 static int hexnumlen (ULONGEST num);
465 static int stubhex (int ch);
467 static int hexnumstr (char *, ULONGEST);
469 static int hexnumnstr (char *, ULONGEST, int);
471 static CORE_ADDR remote_address_masked (CORE_ADDR);
473 static void print_packet (const char *);
475 static int stub_unpack_int (char *buff, int fieldlength);
477 static ptid_t remote_current_thread (ptid_t oldptid);
479 static int putpkt_binary (const char *buf, int cnt);
481 static void check_binary_download (CORE_ADDR addr);
483 struct packet_config;
485 static void show_packet_config_cmd (struct packet_config *config);
487 static void show_remote_protocol_packet_cmd (struct ui_file *file,
489 struct cmd_list_element *c,
492 static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
493 static ptid_t read_ptid (const char *buf, const char **obuf);
495 static void remote_query_supported (void);
497 static void remote_check_symbols (void);
500 static void stop_reply_xfree (struct stop_reply *);
501 static void remote_parse_stop_reply (char *, struct stop_reply *);
502 static void push_stop_reply (struct stop_reply *);
503 static void discard_pending_stop_replies_in_queue (struct remote_state *);
504 static int peek_stop_reply (ptid_t ptid);
506 struct threads_listing_context;
507 static void remove_new_fork_children (struct threads_listing_context *);
509 static void remote_async_inferior_event_handler (gdb_client_data);
511 static int remote_read_description_p (struct target_ops *target);
513 static void remote_console_output (char *msg);
515 static void remote_btrace_reset (void);
517 static void remote_btrace_maybe_reopen (void);
519 static int stop_reply_queue_length (void);
521 static void readahead_cache_invalidate (void);
523 static void remote_unpush_and_throw (void);
525 static struct remote_state *get_remote_state (void);
529 static struct cmd_list_element *remote_cmdlist;
531 /* For "set remote" and "show remote". */
533 static struct cmd_list_element *remote_set_cmdlist;
534 static struct cmd_list_element *remote_show_cmdlist;
536 /* Stub vCont actions support.
538 Each field is a boolean flag indicating whether the stub reports
539 support for the corresponding action. */
541 struct vCont_action_support
556 /* Controls whether GDB is willing to use range stepping. */
558 static int use_range_stepping = 1;
560 #define OPAQUETHREADBYTES 8
562 /* a 64 bit opaque identifier */
563 typedef unsigned char threadref[OPAQUETHREADBYTES];
565 /* About this many threadisds fit in a packet. */
567 #define MAXTHREADLISTRESULTS 32
569 /* The max number of chars in debug output. The rest of chars are
572 #define REMOTE_DEBUG_MAX_CHAR 512
574 /* Data for the vFile:pread readahead cache. */
576 struct readahead_cache
578 /* The file descriptor for the file that is being cached. -1 if the
582 /* The offset into the file that the cache buffer corresponds
586 /* The buffer holding the cache contents. */
588 /* The buffer's size. We try to read as much as fits into a packet
592 /* Cache hit and miss counters. */
597 /* Description of the remote protocol state for the currently
598 connected target. This is per-target state, and independent of the
599 selected architecture. */
603 /* A buffer to use for incoming packets, and its current size. The
604 buffer is grown dynamically for larger incoming packets.
605 Outgoing packets may also be constructed in this buffer.
606 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
607 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
612 /* True if we're going through initial connection setup (finding out
613 about the remote side's threads, relocating symbols, etc.). */
616 /* If we negotiated packet size explicitly (and thus can bypass
617 heuristics for the largest packet size that will not overflow
618 a buffer in the stub), this will be set to that packet size.
619 Otherwise zero, meaning to use the guessed size. */
620 long explicit_packet_size;
622 /* remote_wait is normally called when the target is running and
623 waits for a stop reply packet. But sometimes we need to call it
624 when the target is already stopped. We can send a "?" packet
625 and have remote_wait read the response. Or, if we already have
626 the response, we can stash it in BUF and tell remote_wait to
627 skip calling getpkt. This flag is set when BUF contains a
628 stop reply packet and the target is not waiting. */
629 int cached_wait_status;
631 /* True, if in no ack mode. That is, neither GDB nor the stub will
632 expect acks from each other. The connection is assumed to be
636 /* True if we're connected in extended remote mode. */
639 /* True if we resumed the target and we're waiting for the target to
640 stop. In the mean time, we can't start another command/query.
641 The remote server wouldn't be ready to process it, so we'd
642 timeout waiting for a reply that would never come and eventually
643 we'd close the connection. This can happen in asynchronous mode
644 because we allow GDB commands while the target is running. */
645 int waiting_for_stop_reply;
647 /* The status of the stub support for the various vCont actions. */
648 struct vCont_action_support supports_vCont;
650 /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
651 responded to that. */
654 /* True if we saw a Ctrl-C while reading or writing from/to the
655 remote descriptor. At that point it is not safe to send a remote
656 interrupt packet, so we instead remember we saw the Ctrl-C and
657 process it once we're done with sending/receiving the current
658 packet, which should be shortly. If however that takes too long,
659 and the user presses Ctrl-C again, we offer to disconnect. */
660 int got_ctrlc_during_io;
662 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
663 remote_open knows that we don't have a file open when the program
665 struct serial *remote_desc;
667 /* These are the threads which we last sent to the remote system. The
668 TID member will be -1 for all or -2 for not sent yet. */
669 ptid_t general_thread;
670 ptid_t continue_thread;
672 /* This is the traceframe which we last selected on the remote system.
673 It will be -1 if no traceframe is selected. */
674 int remote_traceframe_number;
676 char *last_pass_packet;
678 /* The last QProgramSignals packet sent to the target. We bypass
679 sending a new program signals list down to the target if the new
680 packet is exactly the same as the last we sent. IOW, we only let
681 the target know about program signals list changes. */
682 char *last_program_signals_packet;
684 enum gdb_signal last_sent_signal;
688 /* The execution direction of the last resume we got. */
689 enum exec_direction_kind last_resume_exec_dir;
691 char *finished_object;
692 char *finished_annex;
693 ULONGEST finished_offset;
695 /* Should we try the 'ThreadInfo' query packet?
697 This variable (NOT available to the user: auto-detect only!)
698 determines whether GDB will use the new, simpler "ThreadInfo"
699 query or the older, more complex syntax for thread queries.
700 This is an auto-detect variable (set to true at each connect,
701 and set to false when the target fails to recognize it). */
702 int use_threadinfo_query;
703 int use_threadextra_query;
705 threadref echo_nextthread;
706 threadref nextthread;
707 threadref resultthreadlist[MAXTHREADLISTRESULTS];
709 /* The state of remote notification. */
710 struct remote_notif_state *notif_state;
712 /* The branch trace configuration. */
713 struct btrace_config btrace_config;
715 /* The argument to the last "vFile:setfs:" packet we sent, used
716 to avoid sending repeated unnecessary "vFile:setfs:" packets.
717 Initialized to -1 to indicate that no "vFile:setfs:" packet
718 has yet been sent. */
721 /* A readahead cache for vFile:pread. Often, reading a binary
722 involves a sequence of small reads. E.g., when parsing an ELF
723 file. A readahead cache helps mostly the case of remote
724 debugging on a connection with higher latency, due to the
725 request/reply nature of the RSP. We only cache data for a single
726 file descriptor at a time. */
727 struct readahead_cache readahead_cache;
730 /* Private data that we'll store in (struct thread_info)->priv. */
731 struct remote_thread_info : public private_thread_info
737 /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
738 sequence of bytes. */
739 gdb::byte_vector thread_handle;
741 /* Whether the target stopped for a breakpoint/watchpoint. */
742 enum target_stop_reason stop_reason = TARGET_STOPPED_BY_NO_REASON;
744 /* This is set to the data address of the access causing the target
745 to stop for a watchpoint. */
746 CORE_ADDR watch_data_address = 0;
748 /* Fields used by the vCont action coalescing implemented in
749 remote_resume / remote_commit_resume. remote_resume stores each
750 thread's last resume request in these fields, so that a later
751 remote_commit_resume knows which is the proper action for this
752 thread to include in the vCont packet. */
754 /* True if the last target_resume call for this thread was a step
755 request, false if a continue request. */
756 int last_resume_step = 0;
758 /* The signal specified in the last target_resume call for this
760 gdb_signal last_resume_sig = GDB_SIGNAL_0;
762 /* Whether this thread was already vCont-resumed on the remote
764 int vcont_resumed = 0;
767 /* This data could be associated with a target, but we do not always
768 have access to the current target when we need it, so for now it is
769 static. This will be fine for as long as only one target is in use
771 static struct remote_state *remote_state;
773 static struct remote_state *
774 get_remote_state_raw (void)
779 /* Allocate a new struct remote_state with xmalloc, initialize it, and
782 static struct remote_state *
783 new_remote_state (void)
785 struct remote_state *result = XCNEW (struct remote_state);
787 /* The default buffer size is unimportant; it will be expanded
788 whenever a larger buffer is needed. */
789 result->buf_size = 400;
790 result->buf = (char *) xmalloc (result->buf_size);
791 result->remote_traceframe_number = -1;
792 result->last_sent_signal = GDB_SIGNAL_0;
793 result->last_resume_exec_dir = EXEC_FORWARD;
799 /* Description of the remote protocol for a given architecture. */
803 long offset; /* Offset into G packet. */
804 long regnum; /* GDB's internal register number. */
805 LONGEST pnum; /* Remote protocol register number. */
806 int in_g_packet; /* Always part of G packet. */
807 /* long size in bytes; == register_size (target_gdbarch (), regnum);
809 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
813 struct remote_arch_state
815 /* Description of the remote protocol registers. */
816 long sizeof_g_packet;
818 /* Description of the remote protocol registers indexed by REGNUM
819 (making an array gdbarch_num_regs in size). */
820 struct packet_reg *regs;
822 /* This is the size (in chars) of the first response to the ``g''
823 packet. It is used as a heuristic when determining the maximum
824 size of memory-read and memory-write packets. A target will
825 typically only reserve a buffer large enough to hold the ``g''
826 packet. The size does not include packet overhead (headers and
828 long actual_register_packet_size;
830 /* This is the maximum size (in chars) of a non read/write packet.
831 It is also used as a cap on the size of read/write packets. */
832 long remote_packet_size;
835 /* Utility: generate error from an incoming stub packet. */
837 trace_error (char *buf)
840 return; /* not an error msg */
843 case '1': /* malformed packet error */
844 if (*++buf == '0') /* general case: */
845 error (_("remote.c: error in outgoing packet."));
847 error (_("remote.c: error in outgoing packet at field #%ld."),
848 strtol (buf, NULL, 16));
850 error (_("Target returns error code '%s'."), buf);
854 /* Utility: wait for reply from stub, while accepting "O" packets. */
857 remote_get_noisy_reply ()
859 struct remote_state *rs = get_remote_state ();
861 do /* Loop on reply from remote stub. */
865 QUIT; /* Allow user to bail out with ^C. */
866 getpkt (&rs->buf, &rs->buf_size, 0);
870 else if (startswith (buf, "qRelocInsn:"))
873 CORE_ADDR from, to, org_to;
875 int adjusted_size = 0;
878 p = buf + strlen ("qRelocInsn:");
879 pp = unpack_varlen_hex (p, &ul);
881 error (_("invalid qRelocInsn packet: %s"), buf);
885 unpack_varlen_hex (p, &ul);
892 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
895 CATCH (ex, RETURN_MASK_ALL)
897 if (ex.error == MEMORY_ERROR)
899 /* Propagate memory errors silently back to the
900 target. The stub may have limited the range of
901 addresses we can write to, for example. */
905 /* Something unexpectedly bad happened. Be verbose
906 so we can tell what, and propagate the error back
907 to the stub, so it doesn't get stuck waiting for
909 exception_fprintf (gdb_stderr, ex,
910 _("warning: relocating instruction: "));
918 adjusted_size = to - org_to;
920 xsnprintf (buf, rs->buf_size, "qRelocInsn:%x", adjusted_size);
924 else if (buf[0] == 'O' && buf[1] != 'K')
925 remote_console_output (buf + 1); /* 'O' message from stub */
927 return buf; /* Here's the actual reply. */
932 /* Handle for retreving the remote protocol data from gdbarch. */
933 static struct gdbarch_data *remote_gdbarch_data_handle;
935 static struct remote_arch_state *
936 get_remote_arch_state (struct gdbarch *gdbarch)
938 gdb_assert (gdbarch != NULL);
939 return ((struct remote_arch_state *)
940 gdbarch_data (gdbarch, remote_gdbarch_data_handle));
943 /* Fetch the global remote target state. */
945 static struct remote_state *
946 get_remote_state (void)
948 /* Make sure that the remote architecture state has been
949 initialized, because doing so might reallocate rs->buf. Any
950 function which calls getpkt also needs to be mindful of changes
951 to rs->buf, but this call limits the number of places which run
953 get_remote_arch_state (target_gdbarch ());
955 return get_remote_state_raw ();
958 /* Cleanup routine for the remote module's pspace data. */
961 remote_pspace_data_cleanup (struct program_space *pspace, void *arg)
963 char *remote_exec_file = (char *) arg;
965 xfree (remote_exec_file);
968 /* Fetch the remote exec-file from the current program space. */
971 get_remote_exec_file (void)
973 char *remote_exec_file;
976 = (char *) program_space_data (current_program_space,
978 if (remote_exec_file == NULL)
981 return remote_exec_file;
984 /* Set the remote exec file for PSPACE. */
987 set_pspace_remote_exec_file (struct program_space *pspace,
988 char *remote_exec_file)
990 char *old_file = (char *) program_space_data (pspace, remote_pspace_data);
993 set_program_space_data (pspace, remote_pspace_data,
994 xstrdup (remote_exec_file));
997 /* The "set/show remote exec-file" set command hook. */
1000 set_remote_exec_file (const char *ignored, int from_tty,
1001 struct cmd_list_element *c)
1003 gdb_assert (remote_exec_file_var != NULL);
1004 set_pspace_remote_exec_file (current_program_space, remote_exec_file_var);
1007 /* The "set/show remote exec-file" show command hook. */
1010 show_remote_exec_file (struct ui_file *file, int from_tty,
1011 struct cmd_list_element *cmd, const char *value)
1013 fprintf_filtered (file, "%s\n", remote_exec_file_var);
1017 compare_pnums (const void *lhs_, const void *rhs_)
1019 const struct packet_reg * const *lhs
1020 = (const struct packet_reg * const *) lhs_;
1021 const struct packet_reg * const *rhs
1022 = (const struct packet_reg * const *) rhs_;
1024 if ((*lhs)->pnum < (*rhs)->pnum)
1026 else if ((*lhs)->pnum == (*rhs)->pnum)
1033 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
1035 int regnum, num_remote_regs, offset;
1036 struct packet_reg **remote_regs;
1038 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
1040 struct packet_reg *r = ®s[regnum];
1042 if (register_size (gdbarch, regnum) == 0)
1043 /* Do not try to fetch zero-sized (placeholder) registers. */
1046 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
1051 /* Define the g/G packet format as the contents of each register
1052 with a remote protocol number, in order of ascending protocol
1055 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
1056 for (num_remote_regs = 0, regnum = 0;
1057 regnum < gdbarch_num_regs (gdbarch);
1059 if (regs[regnum].pnum != -1)
1060 remote_regs[num_remote_regs++] = ®s[regnum];
1062 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
1065 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
1067 remote_regs[regnum]->in_g_packet = 1;
1068 remote_regs[regnum]->offset = offset;
1069 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
1075 /* Given the architecture described by GDBARCH, return the remote
1076 protocol register's number and the register's offset in the g/G
1077 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
1078 If the target does not have a mapping for REGNUM, return false,
1079 otherwise, return true. */
1082 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
1083 int *pnum, int *poffset)
1085 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
1087 std::vector<packet_reg> regs (gdbarch_num_regs (gdbarch));
1089 map_regcache_remote_table (gdbarch, regs.data ());
1091 *pnum = regs[regnum].pnum;
1092 *poffset = regs[regnum].offset;
1098 init_remote_state (struct gdbarch *gdbarch)
1100 struct remote_state *rs = get_remote_state_raw ();
1101 struct remote_arch_state *rsa;
1103 rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
1105 /* Use the architecture to build a regnum<->pnum table, which will be
1106 1:1 unless a feature set specifies otherwise. */
1107 rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
1108 gdbarch_num_regs (gdbarch),
1111 /* Record the maximum possible size of the g packet - it may turn out
1113 rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
1115 /* Default maximum number of characters in a packet body. Many
1116 remote stubs have a hardwired buffer size of 400 bytes
1117 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
1118 as the maximum packet-size to ensure that the packet and an extra
1119 NUL character can always fit in the buffer. This stops GDB
1120 trashing stubs that try to squeeze an extra NUL into what is
1121 already a full buffer (As of 1999-12-04 that was most stubs). */
1122 rsa->remote_packet_size = 400 - 1;
1124 /* This one is filled in when a ``g'' packet is received. */
1125 rsa->actual_register_packet_size = 0;
1127 /* Should rsa->sizeof_g_packet needs more space than the
1128 default, adjust the size accordingly. Remember that each byte is
1129 encoded as two characters. 32 is the overhead for the packet
1130 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
1131 (``$NN:G...#NN'') is a better guess, the below has been padded a
1133 if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
1134 rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
1136 /* Make sure that the packet buffer is plenty big enough for
1137 this architecture. */
1138 if (rs->buf_size < rsa->remote_packet_size)
1140 rs->buf_size = 2 * rsa->remote_packet_size;
1141 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
1147 /* Return the current allowed size of a remote packet. This is
1148 inferred from the current architecture, and should be used to
1149 limit the length of outgoing packets. */
1151 get_remote_packet_size (void)
1153 struct remote_state *rs = get_remote_state ();
1154 remote_arch_state *rsa = get_remote_arch_state (target_gdbarch ());
1156 if (rs->explicit_packet_size)
1157 return rs->explicit_packet_size;
1159 return rsa->remote_packet_size;
1162 static struct packet_reg *
1163 packet_reg_from_regnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1166 if (regnum < 0 && regnum >= gdbarch_num_regs (gdbarch))
1170 struct packet_reg *r = &rsa->regs[regnum];
1172 gdb_assert (r->regnum == regnum);
1177 static struct packet_reg *
1178 packet_reg_from_pnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1183 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
1185 struct packet_reg *r = &rsa->regs[i];
1187 if (r->pnum == pnum)
1193 static remote_target remote_ops;
1195 static extended_remote_target extended_remote_ops;
1197 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
1198 ``forever'' still use the normal timeout mechanism. This is
1199 currently used by the ASYNC code to guarentee that target reads
1200 during the initial connect always time-out. Once getpkt has been
1201 modified to return a timeout indication and, in turn
1202 remote_wait()/wait_for_inferior() have gained a timeout parameter
1203 this can go away. */
1204 static int wait_forever_enabled_p = 1;
1206 /* Allow the user to specify what sequence to send to the remote
1207 when he requests a program interruption: Although ^C is usually
1208 what remote systems expect (this is the default, here), it is
1209 sometimes preferable to send a break. On other systems such
1210 as the Linux kernel, a break followed by g, which is Magic SysRq g
1211 is required in order to interrupt the execution. */
1212 const char interrupt_sequence_control_c[] = "Ctrl-C";
1213 const char interrupt_sequence_break[] = "BREAK";
1214 const char interrupt_sequence_break_g[] = "BREAK-g";
1215 static const char *const interrupt_sequence_modes[] =
1217 interrupt_sequence_control_c,
1218 interrupt_sequence_break,
1219 interrupt_sequence_break_g,
1222 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
1225 show_interrupt_sequence (struct ui_file *file, int from_tty,
1226 struct cmd_list_element *c,
1229 if (interrupt_sequence_mode == interrupt_sequence_control_c)
1230 fprintf_filtered (file,
1231 _("Send the ASCII ETX character (Ctrl-c) "
1232 "to the remote target to interrupt the "
1233 "execution of the program.\n"));
1234 else if (interrupt_sequence_mode == interrupt_sequence_break)
1235 fprintf_filtered (file,
1236 _("send a break signal to the remote target "
1237 "to interrupt the execution of the program.\n"));
1238 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
1239 fprintf_filtered (file,
1240 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
1241 "the remote target to interrupt the execution "
1242 "of Linux kernel.\n"));
1244 internal_error (__FILE__, __LINE__,
1245 _("Invalid value for interrupt_sequence_mode: %s."),
1246 interrupt_sequence_mode);
1249 /* This boolean variable specifies whether interrupt_sequence is sent
1250 to the remote target when gdb connects to it.
1251 This is mostly needed when you debug the Linux kernel: The Linux kernel
1252 expects BREAK g which is Magic SysRq g for connecting gdb. */
1253 static int interrupt_on_connect = 0;
1255 /* This variable is used to implement the "set/show remotebreak" commands.
1256 Since these commands are now deprecated in favor of "set/show remote
1257 interrupt-sequence", it no longer has any effect on the code. */
1258 static int remote_break;
1261 set_remotebreak (const char *args, int from_tty, struct cmd_list_element *c)
1264 interrupt_sequence_mode = interrupt_sequence_break;
1266 interrupt_sequence_mode = interrupt_sequence_control_c;
1270 show_remotebreak (struct ui_file *file, int from_tty,
1271 struct cmd_list_element *c,
1276 /* This variable sets the number of bits in an address that are to be
1277 sent in a memory ("M" or "m") packet. Normally, after stripping
1278 leading zeros, the entire address would be sent. This variable
1279 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
1280 initial implementation of remote.c restricted the address sent in
1281 memory packets to ``host::sizeof long'' bytes - (typically 32
1282 bits). Consequently, for 64 bit targets, the upper 32 bits of an
1283 address was never sent. Since fixing this bug may cause a break in
1284 some remote targets this variable is principly provided to
1285 facilitate backward compatibility. */
1287 static unsigned int remote_address_size;
1290 /* User configurable variables for the number of characters in a
1291 memory read/write packet. MIN (rsa->remote_packet_size,
1292 rsa->sizeof_g_packet) is the default. Some targets need smaller
1293 values (fifo overruns, et.al.) and some users need larger values
1294 (speed up transfers). The variables ``preferred_*'' (the user
1295 request), ``current_*'' (what was actually set) and ``forced_*''
1296 (Positive - a soft limit, negative - a hard limit). */
1298 struct memory_packet_config
1305 /* The default max memory-write-packet-size. The 16k is historical.
1306 (It came from older GDB's using alloca for buffers and the
1307 knowledge (folklore?) that some hosts don't cope very well with
1308 large alloca calls.) */
1309 #define DEFAULT_MAX_MEMORY_PACKET_SIZE 16384
1311 /* The minimum remote packet size for memory transfers. Ensures we
1312 can write at least one byte. */
1313 #define MIN_MEMORY_PACKET_SIZE 20
1315 /* Compute the current size of a read/write packet. Since this makes
1316 use of ``actual_register_packet_size'' the computation is dynamic. */
1319 get_memory_packet_size (struct memory_packet_config *config)
1321 struct remote_state *rs = get_remote_state ();
1322 remote_arch_state *rsa = get_remote_arch_state (target_gdbarch ());
1325 if (config->fixed_p)
1327 if (config->size <= 0)
1328 what_they_get = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1330 what_they_get = config->size;
1334 what_they_get = get_remote_packet_size ();
1335 /* Limit the packet to the size specified by the user. */
1336 if (config->size > 0
1337 && what_they_get > config->size)
1338 what_they_get = config->size;
1340 /* Limit it to the size of the targets ``g'' response unless we have
1341 permission from the stub to use a larger packet size. */
1342 if (rs->explicit_packet_size == 0
1343 && rsa->actual_register_packet_size > 0
1344 && what_they_get > rsa->actual_register_packet_size)
1345 what_they_get = rsa->actual_register_packet_size;
1347 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1348 what_they_get = MIN_MEMORY_PACKET_SIZE;
1350 /* Make sure there is room in the global buffer for this packet
1351 (including its trailing NUL byte). */
1352 if (rs->buf_size < what_they_get + 1)
1354 rs->buf_size = 2 * what_they_get;
1355 rs->buf = (char *) xrealloc (rs->buf, 2 * what_they_get);
1358 return what_they_get;
1361 /* Update the size of a read/write packet. If they user wants
1362 something really big then do a sanity check. */
1365 set_memory_packet_size (const char *args, struct memory_packet_config *config)
1367 int fixed_p = config->fixed_p;
1368 long size = config->size;
1371 error (_("Argument required (integer, `fixed' or `limited')."));
1372 else if (strcmp (args, "hard") == 0
1373 || strcmp (args, "fixed") == 0)
1375 else if (strcmp (args, "soft") == 0
1376 || strcmp (args, "limit") == 0)
1382 size = strtoul (args, &end, 0);
1384 error (_("Invalid %s (bad syntax)."), config->name);
1386 /* Instead of explicitly capping the size of a packet to or
1387 disallowing it, the user is allowed to set the size to
1388 something arbitrarily large. */
1391 /* So that the query shows the correct value. */
1393 size = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1396 if (fixed_p && !config->fixed_p)
1398 if (! query (_("The target may not be able to correctly handle a %s\n"
1399 "of %ld bytes. Change the packet size? "),
1400 config->name, size))
1401 error (_("Packet size not changed."));
1403 /* Update the config. */
1404 config->fixed_p = fixed_p;
1405 config->size = size;
1409 show_memory_packet_size (struct memory_packet_config *config)
1411 printf_filtered (_("The %s is %ld. "), config->name, config->size);
1412 if (config->fixed_p)
1413 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
1414 get_memory_packet_size (config));
1416 printf_filtered (_("Packets are limited to %ld bytes.\n"),
1417 get_memory_packet_size (config));
1420 static struct memory_packet_config memory_write_packet_config =
1422 "memory-write-packet-size",
1426 set_memory_write_packet_size (const char *args, int from_tty)
1428 set_memory_packet_size (args, &memory_write_packet_config);
1432 show_memory_write_packet_size (const char *args, int from_tty)
1434 show_memory_packet_size (&memory_write_packet_config);
1438 get_memory_write_packet_size (void)
1440 return get_memory_packet_size (&memory_write_packet_config);
1443 static struct memory_packet_config memory_read_packet_config =
1445 "memory-read-packet-size",
1449 set_memory_read_packet_size (const char *args, int from_tty)
1451 set_memory_packet_size (args, &memory_read_packet_config);
1455 show_memory_read_packet_size (const char *args, int from_tty)
1457 show_memory_packet_size (&memory_read_packet_config);
1461 get_memory_read_packet_size (void)
1463 long size = get_memory_packet_size (&memory_read_packet_config);
1465 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1466 extra buffer size argument before the memory read size can be
1467 increased beyond this. */
1468 if (size > get_remote_packet_size ())
1469 size = get_remote_packet_size ();
1474 /* Generic configuration support for packets the stub optionally
1475 supports. Allows the user to specify the use of the packet as well
1476 as allowing GDB to auto-detect support in the remote stub. */
1480 PACKET_SUPPORT_UNKNOWN = 0,
1485 struct packet_config
1490 /* If auto, GDB auto-detects support for this packet or feature,
1491 either through qSupported, or by trying the packet and looking
1492 at the response. If true, GDB assumes the target supports this
1493 packet. If false, the packet is disabled. Configs that don't
1494 have an associated command always have this set to auto. */
1495 enum auto_boolean detect;
1497 /* Does the target support this packet? */
1498 enum packet_support support;
1501 /* Analyze a packet's return value and update the packet config
1511 static enum packet_support packet_config_support (struct packet_config *config);
1512 static enum packet_support packet_support (int packet);
1515 show_packet_config_cmd (struct packet_config *config)
1517 const char *support = "internal-error";
1519 switch (packet_config_support (config))
1522 support = "enabled";
1524 case PACKET_DISABLE:
1525 support = "disabled";
1527 case PACKET_SUPPORT_UNKNOWN:
1528 support = "unknown";
1531 switch (config->detect)
1533 case AUTO_BOOLEAN_AUTO:
1534 printf_filtered (_("Support for the `%s' packet "
1535 "is auto-detected, currently %s.\n"),
1536 config->name, support);
1538 case AUTO_BOOLEAN_TRUE:
1539 case AUTO_BOOLEAN_FALSE:
1540 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1541 config->name, support);
1547 add_packet_config_cmd (struct packet_config *config, const char *name,
1548 const char *title, int legacy)
1554 config->name = name;
1555 config->title = title;
1556 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1558 show_doc = xstrprintf ("Show current use of remote "
1559 "protocol `%s' (%s) packet",
1561 /* set/show TITLE-packet {auto,on,off} */
1562 cmd_name = xstrprintf ("%s-packet", title);
1563 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
1564 &config->detect, set_doc,
1565 show_doc, NULL, /* help_doc */
1567 show_remote_protocol_packet_cmd,
1568 &remote_set_cmdlist, &remote_show_cmdlist);
1569 /* The command code copies the documentation strings. */
1572 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
1577 legacy_name = xstrprintf ("%s-packet", name);
1578 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1579 &remote_set_cmdlist);
1580 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1581 &remote_show_cmdlist);
1585 static enum packet_result
1586 packet_check_result (const char *buf)
1590 /* The stub recognized the packet request. Check that the
1591 operation succeeded. */
1593 && isxdigit (buf[1]) && isxdigit (buf[2])
1595 /* "Enn" - definitly an error. */
1596 return PACKET_ERROR;
1598 /* Always treat "E." as an error. This will be used for
1599 more verbose error messages, such as E.memtypes. */
1600 if (buf[0] == 'E' && buf[1] == '.')
1601 return PACKET_ERROR;
1603 /* The packet may or may not be OK. Just assume it is. */
1607 /* The stub does not support the packet. */
1608 return PACKET_UNKNOWN;
1611 static enum packet_result
1612 packet_ok (const char *buf, struct packet_config *config)
1614 enum packet_result result;
1616 if (config->detect != AUTO_BOOLEAN_TRUE
1617 && config->support == PACKET_DISABLE)
1618 internal_error (__FILE__, __LINE__,
1619 _("packet_ok: attempt to use a disabled packet"));
1621 result = packet_check_result (buf);
1626 /* The stub recognized the packet request. */
1627 if (config->support == PACKET_SUPPORT_UNKNOWN)
1630 fprintf_unfiltered (gdb_stdlog,
1631 "Packet %s (%s) is supported\n",
1632 config->name, config->title);
1633 config->support = PACKET_ENABLE;
1636 case PACKET_UNKNOWN:
1637 /* The stub does not support the packet. */
1638 if (config->detect == AUTO_BOOLEAN_AUTO
1639 && config->support == PACKET_ENABLE)
1641 /* If the stub previously indicated that the packet was
1642 supported then there is a protocol error. */
1643 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1644 config->name, config->title);
1646 else if (config->detect == AUTO_BOOLEAN_TRUE)
1648 /* The user set it wrong. */
1649 error (_("Enabled packet %s (%s) not recognized by stub"),
1650 config->name, config->title);
1654 fprintf_unfiltered (gdb_stdlog,
1655 "Packet %s (%s) is NOT supported\n",
1656 config->name, config->title);
1657 config->support = PACKET_DISABLE;
1678 PACKET_vFile_pwrite,
1680 PACKET_vFile_unlink,
1681 PACKET_vFile_readlink,
1684 PACKET_qXfer_features,
1685 PACKET_qXfer_exec_file,
1686 PACKET_qXfer_libraries,
1687 PACKET_qXfer_libraries_svr4,
1688 PACKET_qXfer_memory_map,
1689 PACKET_qXfer_spu_read,
1690 PACKET_qXfer_spu_write,
1691 PACKET_qXfer_osdata,
1692 PACKET_qXfer_threads,
1693 PACKET_qXfer_statictrace_read,
1694 PACKET_qXfer_traceframe_info,
1700 PACKET_QPassSignals,
1701 PACKET_QCatchSyscalls,
1702 PACKET_QProgramSignals,
1703 PACKET_QSetWorkingDir,
1704 PACKET_QStartupWithShell,
1705 PACKET_QEnvironmentHexEncoded,
1706 PACKET_QEnvironmentReset,
1707 PACKET_QEnvironmentUnset,
1709 PACKET_qSearch_memory,
1712 PACKET_QStartNoAckMode,
1714 PACKET_qXfer_siginfo_read,
1715 PACKET_qXfer_siginfo_write,
1718 /* Support for conditional tracepoints. */
1719 PACKET_ConditionalTracepoints,
1721 /* Support for target-side breakpoint conditions. */
1722 PACKET_ConditionalBreakpoints,
1724 /* Support for target-side breakpoint commands. */
1725 PACKET_BreakpointCommands,
1727 /* Support for fast tracepoints. */
1728 PACKET_FastTracepoints,
1730 /* Support for static tracepoints. */
1731 PACKET_StaticTracepoints,
1733 /* Support for installing tracepoints while a trace experiment is
1735 PACKET_InstallInTrace,
1739 PACKET_TracepointSource,
1742 PACKET_QDisableRandomization,
1744 PACKET_QTBuffer_size,
1748 PACKET_qXfer_btrace,
1750 /* Support for the QNonStop packet. */
1753 /* Support for the QThreadEvents packet. */
1754 PACKET_QThreadEvents,
1756 /* Support for multi-process extensions. */
1757 PACKET_multiprocess_feature,
1759 /* Support for enabling and disabling tracepoints while a trace
1760 experiment is running. */
1761 PACKET_EnableDisableTracepoints_feature,
1763 /* Support for collecting strings using the tracenz bytecode. */
1764 PACKET_tracenz_feature,
1766 /* Support for continuing to run a trace experiment while GDB is
1768 PACKET_DisconnectedTracing_feature,
1770 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
1771 PACKET_augmented_libraries_svr4_read_feature,
1773 /* Support for the qXfer:btrace-conf:read packet. */
1774 PACKET_qXfer_btrace_conf,
1776 /* Support for the Qbtrace-conf:bts:size packet. */
1777 PACKET_Qbtrace_conf_bts_size,
1779 /* Support for swbreak+ feature. */
1780 PACKET_swbreak_feature,
1782 /* Support for hwbreak+ feature. */
1783 PACKET_hwbreak_feature,
1785 /* Support for fork events. */
1786 PACKET_fork_event_feature,
1788 /* Support for vfork events. */
1789 PACKET_vfork_event_feature,
1791 /* Support for the Qbtrace-conf:pt:size packet. */
1792 PACKET_Qbtrace_conf_pt_size,
1794 /* Support for exec events. */
1795 PACKET_exec_event_feature,
1797 /* Support for query supported vCont actions. */
1798 PACKET_vContSupported,
1800 /* Support remote CTRL-C. */
1803 /* Support TARGET_WAITKIND_NO_RESUMED. */
1809 static struct packet_config remote_protocol_packets[PACKET_MAX];
1811 /* Returns the packet's corresponding "set remote foo-packet" command
1812 state. See struct packet_config for more details. */
1814 static enum auto_boolean
1815 packet_set_cmd_state (int packet)
1817 return remote_protocol_packets[packet].detect;
1820 /* Returns whether a given packet or feature is supported. This takes
1821 into account the state of the corresponding "set remote foo-packet"
1822 command, which may be used to bypass auto-detection. */
1824 static enum packet_support
1825 packet_config_support (struct packet_config *config)
1827 switch (config->detect)
1829 case AUTO_BOOLEAN_TRUE:
1830 return PACKET_ENABLE;
1831 case AUTO_BOOLEAN_FALSE:
1832 return PACKET_DISABLE;
1833 case AUTO_BOOLEAN_AUTO:
1834 return config->support;
1836 gdb_assert_not_reached (_("bad switch"));
1840 /* Same as packet_config_support, but takes the packet's enum value as
1843 static enum packet_support
1844 packet_support (int packet)
1846 struct packet_config *config = &remote_protocol_packets[packet];
1848 return packet_config_support (config);
1852 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1853 struct cmd_list_element *c,
1856 struct packet_config *packet;
1858 for (packet = remote_protocol_packets;
1859 packet < &remote_protocol_packets[PACKET_MAX];
1862 if (&packet->detect == c->var)
1864 show_packet_config_cmd (packet);
1868 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
1872 /* Should we try one of the 'Z' requests? */
1876 Z_PACKET_SOFTWARE_BP,
1877 Z_PACKET_HARDWARE_BP,
1884 /* For compatibility with older distributions. Provide a ``set remote
1885 Z-packet ...'' command that updates all the Z packet types. */
1887 static enum auto_boolean remote_Z_packet_detect;
1890 set_remote_protocol_Z_packet_cmd (const char *args, int from_tty,
1891 struct cmd_list_element *c)
1895 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1896 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
1900 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1901 struct cmd_list_element *c,
1906 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1908 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
1912 /* Returns true if the multi-process extensions are in effect. */
1915 remote_multi_process_p (struct remote_state *rs)
1917 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
1920 /* Returns true if fork events are supported. */
1923 remote_fork_event_p (struct remote_state *rs)
1925 return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
1928 /* Returns true if vfork events are supported. */
1931 remote_vfork_event_p (struct remote_state *rs)
1933 return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
1936 /* Returns true if exec events are supported. */
1939 remote_exec_event_p (struct remote_state *rs)
1941 return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
1944 /* Insert fork catchpoint target routine. If fork events are enabled
1945 then return success, nothing more to do. */
1948 remote_target::insert_fork_catchpoint (int pid)
1950 struct remote_state *rs = get_remote_state ();
1952 return !remote_fork_event_p (rs);
1955 /* Remove fork catchpoint target routine. Nothing to do, just
1959 remote_target::remove_fork_catchpoint (int pid)
1964 /* Insert vfork catchpoint target routine. If vfork events are enabled
1965 then return success, nothing more to do. */
1968 remote_target::insert_vfork_catchpoint (int pid)
1970 struct remote_state *rs = get_remote_state ();
1972 return !remote_vfork_event_p (rs);
1975 /* Remove vfork catchpoint target routine. Nothing to do, just
1979 remote_target::remove_vfork_catchpoint (int pid)
1984 /* Insert exec catchpoint target routine. If exec events are
1985 enabled, just return success. */
1988 remote_target::insert_exec_catchpoint (int pid)
1990 struct remote_state *rs = get_remote_state ();
1992 return !remote_exec_event_p (rs);
1995 /* Remove exec catchpoint target routine. Nothing to do, just
1999 remote_target::remove_exec_catchpoint (int pid)
2005 /* Asynchronous signal handle registered as event loop source for
2006 when we have pending events ready to be passed to the core. */
2008 static struct async_event_handler *remote_async_inferior_event_token;
2012 static ptid_t magic_null_ptid;
2013 static ptid_t not_sent_ptid;
2014 static ptid_t any_thread_ptid;
2016 /* Find out if the stub attached to PID (and hence GDB should offer to
2017 detach instead of killing it when bailing out). */
2020 remote_query_attached (int pid)
2022 struct remote_state *rs = get_remote_state ();
2023 size_t size = get_remote_packet_size ();
2025 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
2028 if (remote_multi_process_p (rs))
2029 xsnprintf (rs->buf, size, "qAttached:%x", pid);
2031 xsnprintf (rs->buf, size, "qAttached");
2034 getpkt (&rs->buf, &rs->buf_size, 0);
2036 switch (packet_ok (rs->buf,
2037 &remote_protocol_packets[PACKET_qAttached]))
2040 if (strcmp (rs->buf, "1") == 0)
2044 warning (_("Remote failure reply: %s"), rs->buf);
2046 case PACKET_UNKNOWN:
2053 /* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
2054 has been invented by GDB, instead of reported by the target. Since
2055 we can be connected to a remote system before before knowing about
2056 any inferior, mark the target with execution when we find the first
2057 inferior. If ATTACHED is 1, then we had just attached to this
2058 inferior. If it is 0, then we just created this inferior. If it
2059 is -1, then try querying the remote stub to find out if it had
2060 attached to the inferior or not. If TRY_OPEN_EXEC is true then
2061 attempt to open this inferior's executable as the main executable
2062 if no main executable is open already. */
2064 static struct inferior *
2065 remote_add_inferior (int fake_pid_p, int pid, int attached,
2068 struct inferior *inf;
2070 /* Check whether this process we're learning about is to be
2071 considered attached, or if is to be considered to have been
2072 spawned by the stub. */
2074 attached = remote_query_attached (pid);
2076 if (gdbarch_has_global_solist (target_gdbarch ()))
2078 /* If the target shares code across all inferiors, then every
2079 attach adds a new inferior. */
2080 inf = add_inferior (pid);
2082 /* ... and every inferior is bound to the same program space.
2083 However, each inferior may still have its own address
2085 inf->aspace = maybe_new_address_space ();
2086 inf->pspace = current_program_space;
2090 /* In the traditional debugging scenario, there's a 1-1 match
2091 between program/address spaces. We simply bind the inferior
2092 to the program space's address space. */
2093 inf = current_inferior ();
2094 inferior_appeared (inf, pid);
2097 inf->attach_flag = attached;
2098 inf->fake_pid_p = fake_pid_p;
2100 /* If no main executable is currently open then attempt to
2101 open the file that was executed to create this inferior. */
2102 if (try_open_exec && get_exec_file (0) == NULL)
2103 exec_file_locate_attach (pid, 0, 1);
2108 static remote_thread_info *get_remote_thread_info (thread_info *thread);
2110 /* Add thread PTID to GDB's thread list. Tag it as executing/running
2111 according to RUNNING. */
2114 remote_add_thread (ptid_t ptid, int running, int executing)
2116 struct remote_state *rs = get_remote_state ();
2117 struct thread_info *thread;
2119 /* GDB historically didn't pull threads in the initial connection
2120 setup. If the remote target doesn't even have a concept of
2121 threads (e.g., a bare-metal target), even if internally we
2122 consider that a single-threaded target, mentioning a new thread
2123 might be confusing to the user. Be silent then, preserving the
2124 age old behavior. */
2125 if (rs->starting_up)
2126 thread = add_thread_silent (ptid);
2128 thread = add_thread (ptid);
2130 get_remote_thread_info (thread)->vcont_resumed = executing;
2131 set_executing (ptid, executing);
2132 set_running (ptid, running);
2135 /* Come here when we learn about a thread id from the remote target.
2136 It may be the first time we hear about such thread, so take the
2137 opportunity to add it to GDB's thread list. In case this is the
2138 first time we're noticing its corresponding inferior, add it to
2139 GDB's inferior list as well. EXECUTING indicates whether the
2140 thread is (internally) executing or stopped. */
2143 remote_notice_new_inferior (ptid_t currthread, int executing)
2145 /* In non-stop mode, we assume new found threads are (externally)
2146 running until proven otherwise with a stop reply. In all-stop,
2147 we can only get here if all threads are stopped. */
2148 int running = target_is_non_stop_p () ? 1 : 0;
2150 /* If this is a new thread, add it to GDB's thread list.
2151 If we leave it up to WFI to do this, bad things will happen. */
2153 if (in_thread_list (currthread) && is_exited (currthread))
2155 /* We're seeing an event on a thread id we knew had exited.
2156 This has to be a new thread reusing the old id. Add it. */
2157 remote_add_thread (currthread, running, executing);
2161 if (!in_thread_list (currthread))
2163 struct inferior *inf = NULL;
2164 int pid = ptid_get_pid (currthread);
2166 if (ptid_is_pid (inferior_ptid)
2167 && pid == ptid_get_pid (inferior_ptid))
2169 /* inferior_ptid has no thread member yet. This can happen
2170 with the vAttach -> remote_wait,"TAAthread:" path if the
2171 stub doesn't support qC. This is the first stop reported
2172 after an attach, so this is the main thread. Update the
2173 ptid in the thread list. */
2174 if (in_thread_list (pid_to_ptid (pid)))
2175 thread_change_ptid (inferior_ptid, currthread);
2178 remote_add_thread (currthread, running, executing);
2179 inferior_ptid = currthread;
2184 if (ptid_equal (magic_null_ptid, inferior_ptid))
2186 /* inferior_ptid is not set yet. This can happen with the
2187 vRun -> remote_wait,"TAAthread:" path if the stub
2188 doesn't support qC. This is the first stop reported
2189 after an attach, so this is the main thread. Update the
2190 ptid in the thread list. */
2191 thread_change_ptid (inferior_ptid, currthread);
2195 /* When connecting to a target remote, or to a target
2196 extended-remote which already was debugging an inferior, we
2197 may not know about it yet. Add it before adding its child
2198 thread, so notifications are emitted in a sensible order. */
2199 if (!in_inferior_list (ptid_get_pid (currthread)))
2201 struct remote_state *rs = get_remote_state ();
2202 int fake_pid_p = !remote_multi_process_p (rs);
2204 inf = remote_add_inferior (fake_pid_p,
2205 ptid_get_pid (currthread), -1, 1);
2208 /* This is really a new thread. Add it. */
2209 remote_add_thread (currthread, running, executing);
2211 /* If we found a new inferior, let the common code do whatever
2212 it needs to with it (e.g., read shared libraries, insert
2213 breakpoints), unless we're just setting up an all-stop
2217 struct remote_state *rs = get_remote_state ();
2219 if (!rs->starting_up)
2220 notice_new_inferior (currthread, executing, 0);
2225 /* Return THREAD's private thread data, creating it if necessary. */
2227 static remote_thread_info *
2228 get_remote_thread_info (thread_info *thread)
2230 gdb_assert (thread != NULL);
2232 if (thread->priv == NULL)
2233 thread->priv.reset (new remote_thread_info);
2235 return static_cast<remote_thread_info *> (thread->priv.get ());
2238 /* Return PTID's private thread data, creating it if necessary. */
2240 static remote_thread_info *
2241 get_remote_thread_info (ptid_t ptid)
2243 struct thread_info *info = find_thread_ptid (ptid);
2245 return get_remote_thread_info (info);
2248 /* Call this function as a result of
2249 1) A halt indication (T packet) containing a thread id
2250 2) A direct query of currthread
2251 3) Successful execution of set thread */
2254 record_currthread (struct remote_state *rs, ptid_t currthread)
2256 rs->general_thread = currthread;
2259 /* If 'QPassSignals' is supported, tell the remote stub what signals
2260 it can simply pass through to the inferior without reporting. */
2263 remote_target::pass_signals (int numsigs, unsigned char *pass_signals)
2265 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
2267 char *pass_packet, *p;
2269 struct remote_state *rs = get_remote_state ();
2271 gdb_assert (numsigs < 256);
2272 for (i = 0; i < numsigs; i++)
2274 if (pass_signals[i])
2277 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
2278 strcpy (pass_packet, "QPassSignals:");
2279 p = pass_packet + strlen (pass_packet);
2280 for (i = 0; i < numsigs; i++)
2282 if (pass_signals[i])
2285 *p++ = tohex (i >> 4);
2286 *p++ = tohex (i & 15);
2295 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
2297 putpkt (pass_packet);
2298 getpkt (&rs->buf, &rs->buf_size, 0);
2299 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
2300 if (rs->last_pass_packet)
2301 xfree (rs->last_pass_packet);
2302 rs->last_pass_packet = pass_packet;
2305 xfree (pass_packet);
2309 /* If 'QCatchSyscalls' is supported, tell the remote stub
2310 to report syscalls to GDB. */
2313 remote_target::set_syscall_catchpoint (int pid, bool needed, int any_count,
2314 gdb::array_view<const int> syscall_counts)
2316 const char *catch_packet;
2317 enum packet_result result;
2320 if (packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2322 /* Not supported. */
2326 if (needed && any_count == 0)
2328 /* Count how many syscalls are to be caught. */
2329 for (size_t i = 0; i < syscall_counts.size (); i++)
2331 if (syscall_counts[i] != 0)
2338 fprintf_unfiltered (gdb_stdlog,
2339 "remote_set_syscall_catchpoint "
2340 "pid %d needed %d any_count %d n_sysno %d\n",
2341 pid, needed, any_count, n_sysno);
2344 std::string built_packet;
2347 /* Prepare a packet with the sysno list, assuming max 8+1
2348 characters for a sysno. If the resulting packet size is too
2349 big, fallback on the non-selective packet. */
2350 const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
2351 built_packet.reserve (maxpktsz);
2352 built_packet = "QCatchSyscalls:1";
2355 /* Add in each syscall to be caught. */
2356 for (size_t i = 0; i < syscall_counts.size (); i++)
2358 if (syscall_counts[i] != 0)
2359 string_appendf (built_packet, ";%zx", i);
2362 if (built_packet.size () > get_remote_packet_size ())
2364 /* catch_packet too big. Fallback to less efficient
2365 non selective mode, with GDB doing the filtering. */
2366 catch_packet = "QCatchSyscalls:1";
2369 catch_packet = built_packet.c_str ();
2372 catch_packet = "QCatchSyscalls:0";
2374 struct remote_state *rs = get_remote_state ();
2376 putpkt (catch_packet);
2377 getpkt (&rs->buf, &rs->buf_size, 0);
2378 result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_QCatchSyscalls]);
2379 if (result == PACKET_OK)
2385 /* If 'QProgramSignals' is supported, tell the remote stub what
2386 signals it should pass through to the inferior when detaching. */
2389 remote_target::program_signals (int numsigs, unsigned char *signals)
2391 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
2395 struct remote_state *rs = get_remote_state ();
2397 gdb_assert (numsigs < 256);
2398 for (i = 0; i < numsigs; i++)
2403 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
2404 strcpy (packet, "QProgramSignals:");
2405 p = packet + strlen (packet);
2406 for (i = 0; i < numsigs; i++)
2408 if (signal_pass_state (i))
2411 *p++ = tohex (i >> 4);
2412 *p++ = tohex (i & 15);
2421 if (!rs->last_program_signals_packet
2422 || strcmp (rs->last_program_signals_packet, packet) != 0)
2425 getpkt (&rs->buf, &rs->buf_size, 0);
2426 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
2427 xfree (rs->last_program_signals_packet);
2428 rs->last_program_signals_packet = packet;
2435 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
2436 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2437 thread. If GEN is set, set the general thread, if not, then set
2438 the step/continue thread. */
2440 set_thread (ptid_t ptid, int gen)
2442 struct remote_state *rs = get_remote_state ();
2443 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
2444 char *buf = rs->buf;
2445 char *endbuf = rs->buf + get_remote_packet_size ();
2447 if (ptid_equal (state, ptid))
2451 *buf++ = gen ? 'g' : 'c';
2452 if (ptid_equal (ptid, magic_null_ptid))
2453 xsnprintf (buf, endbuf - buf, "0");
2454 else if (ptid_equal (ptid, any_thread_ptid))
2455 xsnprintf (buf, endbuf - buf, "0");
2456 else if (ptid_equal (ptid, minus_one_ptid))
2457 xsnprintf (buf, endbuf - buf, "-1");
2459 write_ptid (buf, endbuf, ptid);
2461 getpkt (&rs->buf, &rs->buf_size, 0);
2463 rs->general_thread = ptid;
2465 rs->continue_thread = ptid;
2469 set_general_thread (ptid_t ptid)
2471 set_thread (ptid, 1);
2475 set_continue_thread (ptid_t ptid)
2477 set_thread (ptid, 0);
2480 /* Change the remote current process. Which thread within the process
2481 ends up selected isn't important, as long as it is the same process
2482 as what INFERIOR_PTID points to.
2484 This comes from that fact that there is no explicit notion of
2485 "selected process" in the protocol. The selected process for
2486 general operations is the process the selected general thread
2490 set_general_process (void)
2492 struct remote_state *rs = get_remote_state ();
2494 /* If the remote can't handle multiple processes, don't bother. */
2495 if (!remote_multi_process_p (rs))
2498 /* We only need to change the remote current thread if it's pointing
2499 at some other process. */
2500 if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
2501 set_general_thread (inferior_ptid);
2505 /* Return nonzero if this is the main thread that we made up ourselves
2506 to model non-threaded targets as single-threaded. */
2509 remote_thread_always_alive (ptid_t ptid)
2511 if (ptid_equal (ptid, magic_null_ptid))
2512 /* The main thread is always alive. */
2515 if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
2516 /* The main thread is always alive. This can happen after a
2517 vAttach, if the remote side doesn't support
2524 /* Return nonzero if the thread PTID is still alive on the remote
2528 remote_target::thread_alive (ptid_t ptid)
2530 struct remote_state *rs = get_remote_state ();
2533 /* Check if this is a thread that we made up ourselves to model
2534 non-threaded targets as single-threaded. */
2535 if (remote_thread_always_alive (ptid))
2539 endp = rs->buf + get_remote_packet_size ();
2542 write_ptid (p, endp, ptid);
2545 getpkt (&rs->buf, &rs->buf_size, 0);
2546 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
2549 /* Return a pointer to a thread name if we know it and NULL otherwise.
2550 The thread_info object owns the memory for the name. */
2553 remote_target::thread_name (struct thread_info *info)
2555 if (info->priv != NULL)
2557 const std::string &name = get_remote_thread_info (info)->name;
2558 return !name.empty () ? name.c_str () : NULL;
2564 /* About these extended threadlist and threadinfo packets. They are
2565 variable length packets but, the fields within them are often fixed
2566 length. They are redundent enough to send over UDP as is the
2567 remote protocol in general. There is a matching unit test module
2570 /* WARNING: This threadref data structure comes from the remote O.S.,
2571 libstub protocol encoding, and remote.c. It is not particularly
2574 /* Right now, the internal structure is int. We want it to be bigger.
2575 Plan to fix this. */
2577 typedef int gdb_threadref; /* Internal GDB thread reference. */
2579 /* gdb_ext_thread_info is an internal GDB data structure which is
2580 equivalent to the reply of the remote threadinfo packet. */
2582 struct gdb_ext_thread_info
2584 threadref threadid; /* External form of thread reference. */
2585 int active; /* Has state interesting to GDB?
2587 char display[256]; /* Brief state display, name,
2588 blocked/suspended. */
2589 char shortname[32]; /* To be used to name threads. */
2590 char more_display[256]; /* Long info, statistics, queue depth,
2594 /* The volume of remote transfers can be limited by submitting
2595 a mask containing bits specifying the desired information.
2596 Use a union of these values as the 'selection' parameter to
2597 get_thread_info. FIXME: Make these TAG names more thread specific. */
2599 #define TAG_THREADID 1
2600 #define TAG_EXISTS 2
2601 #define TAG_DISPLAY 4
2602 #define TAG_THREADNAME 8
2603 #define TAG_MOREDISPLAY 16
2605 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
2607 static char *unpack_nibble (char *buf, int *val);
2609 static char *unpack_byte (char *buf, int *value);
2611 static char *pack_int (char *buf, int value);
2613 static char *unpack_int (char *buf, int *value);
2615 static char *unpack_string (char *src, char *dest, int length);
2617 static char *pack_threadid (char *pkt, threadref *id);
2619 static char *unpack_threadid (char *inbuf, threadref *id);
2621 void int_to_threadref (threadref *id, int value);
2623 static int threadref_to_int (threadref *ref);
2625 static void copy_threadref (threadref *dest, threadref *src);
2627 static int threadmatch (threadref *dest, threadref *src);
2629 static char *pack_threadinfo_request (char *pkt, int mode,
2632 static int remote_unpack_thread_info_response (char *pkt,
2633 threadref *expectedref,
2634 struct gdb_ext_thread_info
2638 static int remote_get_threadinfo (threadref *threadid,
2639 int fieldset, /*TAG mask */
2640 struct gdb_ext_thread_info *info);
2642 static char *pack_threadlist_request (char *pkt, int startflag,
2644 threadref *nextthread);
2646 static int parse_threadlist_response (char *pkt,
2648 threadref *original_echo,
2649 threadref *resultlist,
2652 static int remote_get_threadlist (int startflag,
2653 threadref *nextthread,
2657 threadref *threadlist);
2659 typedef int (*rmt_thread_action) (threadref *ref, void *context);
2661 static int remote_threadlist_iterator (rmt_thread_action stepfunction,
2662 void *context, int looplimit);
2664 static int remote_newthread_step (threadref *ref, void *context);
2667 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
2668 buffer we're allowed to write to. Returns
2669 BUF+CHARACTERS_WRITTEN. */
2672 write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2675 struct remote_state *rs = get_remote_state ();
2677 if (remote_multi_process_p (rs))
2679 pid = ptid_get_pid (ptid);
2681 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2683 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2685 tid = ptid_get_lwp (ptid);
2687 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2689 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2694 /* Extract a PTID from BUF. If non-null, OBUF is set to one past the
2695 last parsed char. Returns null_ptid if no thread id is found, and
2696 throws an error if the thread id has an invalid format. */
2699 read_ptid (const char *buf, const char **obuf)
2701 const char *p = buf;
2703 ULONGEST pid = 0, tid = 0;
2707 /* Multi-process ptid. */
2708 pp = unpack_varlen_hex (p + 1, &pid);
2710 error (_("invalid remote ptid: %s"), p);
2713 pp = unpack_varlen_hex (p + 1, &tid);
2716 return ptid_build (pid, tid, 0);
2719 /* No multi-process. Just a tid. */
2720 pp = unpack_varlen_hex (p, &tid);
2722 /* Return null_ptid when no thread id is found. */
2730 /* Since the stub is not sending a process id, then default to
2731 what's in inferior_ptid, unless it's null at this point. If so,
2732 then since there's no way to know the pid of the reported
2733 threads, use the magic number. */
2734 if (ptid_equal (inferior_ptid, null_ptid))
2735 pid = ptid_get_pid (magic_null_ptid);
2737 pid = ptid_get_pid (inferior_ptid);
2741 return ptid_build (pid, tid, 0);
2747 if (ch >= 'a' && ch <= 'f')
2748 return ch - 'a' + 10;
2749 if (ch >= '0' && ch <= '9')
2751 if (ch >= 'A' && ch <= 'F')
2752 return ch - 'A' + 10;
2757 stub_unpack_int (char *buff, int fieldlength)
2764 nibble = stubhex (*buff++);
2768 retval = retval << 4;
2774 unpack_nibble (char *buf, int *val)
2776 *val = fromhex (*buf++);
2781 unpack_byte (char *buf, int *value)
2783 *value = stub_unpack_int (buf, 2);
2788 pack_int (char *buf, int value)
2790 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2791 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2792 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2793 buf = pack_hex_byte (buf, (value & 0xff));
2798 unpack_int (char *buf, int *value)
2800 *value = stub_unpack_int (buf, 8);
2804 #if 0 /* Currently unused, uncomment when needed. */
2805 static char *pack_string (char *pkt, char *string);
2808 pack_string (char *pkt, char *string)
2813 len = strlen (string);
2815 len = 200; /* Bigger than most GDB packets, junk??? */
2816 pkt = pack_hex_byte (pkt, len);
2820 if ((ch == '\0') || (ch == '#'))
2821 ch = '*'; /* Protect encapsulation. */
2826 #endif /* 0 (unused) */
2829 unpack_string (char *src, char *dest, int length)
2838 pack_threadid (char *pkt, threadref *id)
2841 unsigned char *altid;
2843 altid = (unsigned char *) id;
2844 limit = pkt + BUF_THREAD_ID_SIZE;
2846 pkt = pack_hex_byte (pkt, *altid++);
2852 unpack_threadid (char *inbuf, threadref *id)
2855 char *limit = inbuf + BUF_THREAD_ID_SIZE;
2858 altref = (char *) id;
2860 while (inbuf < limit)
2862 x = stubhex (*inbuf++);
2863 y = stubhex (*inbuf++);
2864 *altref++ = (x << 4) | y;
2869 /* Externally, threadrefs are 64 bits but internally, they are still
2870 ints. This is due to a mismatch of specifications. We would like
2871 to use 64bit thread references internally. This is an adapter
2875 int_to_threadref (threadref *id, int value)
2877 unsigned char *scan;
2879 scan = (unsigned char *) id;
2885 *scan++ = (value >> 24) & 0xff;
2886 *scan++ = (value >> 16) & 0xff;
2887 *scan++ = (value >> 8) & 0xff;
2888 *scan++ = (value & 0xff);
2892 threadref_to_int (threadref *ref)
2895 unsigned char *scan;
2901 value = (value << 8) | ((*scan++) & 0xff);
2906 copy_threadref (threadref *dest, threadref *src)
2909 unsigned char *csrc, *cdest;
2911 csrc = (unsigned char *) src;
2912 cdest = (unsigned char *) dest;
2919 threadmatch (threadref *dest, threadref *src)
2921 /* Things are broken right now, so just assume we got a match. */
2923 unsigned char *srcp, *destp;
2925 srcp = (char *) src;
2926 destp = (char *) dest;
2930 result &= (*srcp++ == *destp++) ? 1 : 0;
2937 threadid:1, # always request threadid
2944 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
2947 pack_threadinfo_request (char *pkt, int mode, threadref *id)
2949 *pkt++ = 'q'; /* Info Query */
2950 *pkt++ = 'P'; /* process or thread info */
2951 pkt = pack_int (pkt, mode); /* mode */
2952 pkt = pack_threadid (pkt, id); /* threadid */
2953 *pkt = '\0'; /* terminate */
2957 /* These values tag the fields in a thread info response packet. */
2958 /* Tagging the fields allows us to request specific fields and to
2959 add more fields as time goes by. */
2961 #define TAG_THREADID 1 /* Echo the thread identifier. */
2962 #define TAG_EXISTS 2 /* Is this process defined enough to
2963 fetch registers and its stack? */
2964 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
2965 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
2966 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
2970 remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2971 struct gdb_ext_thread_info *info)
2973 struct remote_state *rs = get_remote_state ();
2977 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
2980 /* info->threadid = 0; FIXME: implement zero_threadref. */
2982 info->display[0] = '\0';
2983 info->shortname[0] = '\0';
2984 info->more_display[0] = '\0';
2986 /* Assume the characters indicating the packet type have been
2988 pkt = unpack_int (pkt, &mask); /* arg mask */
2989 pkt = unpack_threadid (pkt, &ref);
2992 warning (_("Incomplete response to threadinfo request."));
2993 if (!threadmatch (&ref, expectedref))
2994 { /* This is an answer to a different request. */
2995 warning (_("ERROR RMT Thread info mismatch."));
2998 copy_threadref (&info->threadid, &ref);
3000 /* Loop on tagged fields , try to bail if somthing goes wrong. */
3002 /* Packets are terminated with nulls. */
3003 while ((pkt < limit) && mask && *pkt)
3005 pkt = unpack_int (pkt, &tag); /* tag */
3006 pkt = unpack_byte (pkt, &length); /* length */
3007 if (!(tag & mask)) /* Tags out of synch with mask. */
3009 warning (_("ERROR RMT: threadinfo tag mismatch."));
3013 if (tag == TAG_THREADID)
3017 warning (_("ERROR RMT: length of threadid is not 16."));
3021 pkt = unpack_threadid (pkt, &ref);
3022 mask = mask & ~TAG_THREADID;
3025 if (tag == TAG_EXISTS)
3027 info->active = stub_unpack_int (pkt, length);
3029 mask = mask & ~(TAG_EXISTS);
3032 warning (_("ERROR RMT: 'exists' length too long."));
3038 if (tag == TAG_THREADNAME)
3040 pkt = unpack_string (pkt, &info->shortname[0], length);
3041 mask = mask & ~TAG_THREADNAME;
3044 if (tag == TAG_DISPLAY)
3046 pkt = unpack_string (pkt, &info->display[0], length);
3047 mask = mask & ~TAG_DISPLAY;
3050 if (tag == TAG_MOREDISPLAY)
3052 pkt = unpack_string (pkt, &info->more_display[0], length);
3053 mask = mask & ~TAG_MOREDISPLAY;
3056 warning (_("ERROR RMT: unknown thread info tag."));
3057 break; /* Not a tag we know about. */
3063 remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
3064 struct gdb_ext_thread_info *info)
3066 struct remote_state *rs = get_remote_state ();
3069 pack_threadinfo_request (rs->buf, fieldset, threadid);
3071 getpkt (&rs->buf, &rs->buf_size, 0);
3073 if (rs->buf[0] == '\0')
3076 result = remote_unpack_thread_info_response (rs->buf + 2,
3081 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
3084 pack_threadlist_request (char *pkt, int startflag, int threadcount,
3085 threadref *nextthread)
3087 *pkt++ = 'q'; /* info query packet */
3088 *pkt++ = 'L'; /* Process LIST or threadLIST request */
3089 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
3090 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
3091 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
3096 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
3099 parse_threadlist_response (char *pkt, int result_limit,
3100 threadref *original_echo, threadref *resultlist,
3103 struct remote_state *rs = get_remote_state ();
3105 int count, resultcount, done;
3108 /* Assume the 'q' and 'M chars have been stripped. */
3109 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
3110 /* done parse past here */
3111 pkt = unpack_byte (pkt, &count); /* count field */
3112 pkt = unpack_nibble (pkt, &done);
3113 /* The first threadid is the argument threadid. */
3114 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
3115 while ((count-- > 0) && (pkt < limit))
3117 pkt = unpack_threadid (pkt, resultlist++);
3118 if (resultcount++ >= result_limit)
3126 /* Fetch the next batch of threads from the remote. Returns -1 if the
3127 qL packet is not supported, 0 on error and 1 on success. */
3130 remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
3131 int *done, int *result_count, threadref *threadlist)
3133 struct remote_state *rs = get_remote_state ();
3136 /* Trancate result limit to be smaller than the packet size. */
3137 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
3138 >= get_remote_packet_size ())
3139 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
3141 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
3143 getpkt (&rs->buf, &rs->buf_size, 0);
3144 if (*rs->buf == '\0')
3146 /* Packet not supported. */
3151 parse_threadlist_response (rs->buf + 2, result_limit,
3152 &rs->echo_nextthread, threadlist, done);
3154 if (!threadmatch (&rs->echo_nextthread, nextthread))
3156 /* FIXME: This is a good reason to drop the packet. */
3157 /* Possably, there is a duplicate response. */
3159 retransmit immediatly - race conditions
3160 retransmit after timeout - yes
3162 wait for packet, then exit
3164 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
3165 return 0; /* I choose simply exiting. */
3167 if (*result_count <= 0)
3171 warning (_("RMT ERROR : failed to get remote thread list."));
3174 return result; /* break; */
3176 if (*result_count > result_limit)
3179 warning (_("RMT ERROR: threadlist response longer than requested."));
3185 /* Fetch the list of remote threads, with the qL packet, and call
3186 STEPFUNCTION for each thread found. Stops iterating and returns 1
3187 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
3188 STEPFUNCTION returns false. If the packet is not supported,
3192 remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
3195 struct remote_state *rs = get_remote_state ();
3196 int done, i, result_count;
3204 if (loopcount++ > looplimit)
3207 warning (_("Remote fetch threadlist -infinite loop-."));
3210 result = remote_get_threadlist (startflag, &rs->nextthread,
3211 MAXTHREADLISTRESULTS,
3212 &done, &result_count,
3213 rs->resultthreadlist);
3216 /* Clear for later iterations. */
3218 /* Setup to resume next batch of thread references, set nextthread. */
3219 if (result_count >= 1)
3220 copy_threadref (&rs->nextthread,
3221 &rs->resultthreadlist[result_count - 1]);
3223 while (result_count--)
3225 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
3235 /* A thread found on the remote target. */
3239 explicit thread_item (ptid_t ptid_)
3243 thread_item (thread_item &&other) = default;
3244 thread_item &operator= (thread_item &&other) = default;
3246 DISABLE_COPY_AND_ASSIGN (thread_item);
3248 /* The thread's PTID. */
3251 /* The thread's extra info. */
3254 /* The thread's name. */
3257 /* The core the thread was running on. -1 if not known. */
3260 /* The thread handle associated with the thread. */
3261 gdb::byte_vector thread_handle;
3264 /* Context passed around to the various methods listing remote
3265 threads. As new threads are found, they're added to the ITEMS
3268 struct threads_listing_context
3270 /* Return true if this object contains an entry for a thread with ptid
3273 bool contains_thread (ptid_t ptid) const
3275 auto match_ptid = [&] (const thread_item &item)
3277 return item.ptid == ptid;
3280 auto it = std::find_if (this->items.begin (),
3284 return it != this->items.end ();
3287 /* Remove the thread with ptid PTID. */
3289 void remove_thread (ptid_t ptid)
3291 auto match_ptid = [&] (const thread_item &item)
3293 return item.ptid == ptid;
3296 auto it = std::remove_if (this->items.begin (),
3300 if (it != this->items.end ())
3301 this->items.erase (it);
3304 /* The threads found on the remote target. */
3305 std::vector<thread_item> items;
3309 remote_newthread_step (threadref *ref, void *data)
3311 struct threads_listing_context *context
3312 = (struct threads_listing_context *) data;
3313 int pid = inferior_ptid.pid ();
3314 int lwp = threadref_to_int (ref);
3315 ptid_t ptid (pid, lwp);
3317 context->items.emplace_back (ptid);
3319 return 1; /* continue iterator */
3322 #define CRAZY_MAX_THREADS 1000
3325 remote_current_thread (ptid_t oldpid)
3327 struct remote_state *rs = get_remote_state ();
3330 getpkt (&rs->buf, &rs->buf_size, 0);
3331 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
3336 result = read_ptid (&rs->buf[2], &obuf);
3337 if (*obuf != '\0' && remote_debug)
3338 fprintf_unfiltered (gdb_stdlog,
3339 "warning: garbage in qC reply\n");
3347 /* List remote threads using the deprecated qL packet. */
3350 remote_get_threads_with_ql (struct target_ops *ops,
3351 struct threads_listing_context *context)
3353 if (remote_threadlist_iterator (remote_newthread_step, context,
3354 CRAZY_MAX_THREADS) >= 0)
3360 #if defined(HAVE_LIBEXPAT)
3363 start_thread (struct gdb_xml_parser *parser,
3364 const struct gdb_xml_element *element,
3366 std::vector<gdb_xml_value> &attributes)
3368 struct threads_listing_context *data
3369 = (struct threads_listing_context *) user_data;
3370 struct gdb_xml_value *attr;
3372 char *id = (char *) xml_find_attribute (attributes, "id")->value.get ();
3373 ptid_t ptid = read_ptid (id, NULL);
3375 data->items.emplace_back (ptid);
3376 thread_item &item = data->items.back ();
3378 attr = xml_find_attribute (attributes, "core");
3380 item.core = *(ULONGEST *) attr->value.get ();
3382 attr = xml_find_attribute (attributes, "name");
3384 item.name = (const char *) attr->value.get ();
3386 attr = xml_find_attribute (attributes, "handle");
3388 item.thread_handle = hex2bin ((const char *) attr->value.get ());
3392 end_thread (struct gdb_xml_parser *parser,
3393 const struct gdb_xml_element *element,
3394 void *user_data, const char *body_text)
3396 struct threads_listing_context *data
3397 = (struct threads_listing_context *) user_data;
3399 if (body_text != NULL && *body_text != '\0')
3400 data->items.back ().extra = body_text;
3403 const struct gdb_xml_attribute thread_attributes[] = {
3404 { "id", GDB_XML_AF_NONE, NULL, NULL },
3405 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
3406 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
3407 { "handle", GDB_XML_AF_OPTIONAL, NULL, NULL },
3408 { NULL, GDB_XML_AF_NONE, NULL, NULL }
3411 const struct gdb_xml_element thread_children[] = {
3412 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3415 const struct gdb_xml_element threads_children[] = {
3416 { "thread", thread_attributes, thread_children,
3417 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3418 start_thread, end_thread },
3419 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3422 const struct gdb_xml_element threads_elements[] = {
3423 { "threads", NULL, threads_children,
3424 GDB_XML_EF_NONE, NULL, NULL },
3425 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3430 /* List remote threads using qXfer:threads:read. */
3433 remote_get_threads_with_qxfer (struct target_ops *ops,
3434 struct threads_listing_context *context)
3436 #if defined(HAVE_LIBEXPAT)
3437 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3439 gdb::optional<gdb::char_vector> xml
3440 = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
3442 if (xml && (*xml)[0] != '\0')
3444 gdb_xml_parse_quick (_("threads"), "threads.dtd",
3445 threads_elements, xml->data (), context);
3455 /* List remote threads using qfThreadInfo/qsThreadInfo. */
3458 remote_get_threads_with_qthreadinfo (struct target_ops *ops,
3459 struct threads_listing_context *context)
3461 struct remote_state *rs = get_remote_state ();
3463 if (rs->use_threadinfo_query)
3467 putpkt ("qfThreadInfo");
3468 getpkt (&rs->buf, &rs->buf_size, 0);
3470 if (bufp[0] != '\0') /* q packet recognized */
3472 while (*bufp++ == 'm') /* reply contains one or more TID */
3476 ptid_t ptid = read_ptid (bufp, &bufp);
3477 context->items.emplace_back (ptid);
3479 while (*bufp++ == ','); /* comma-separated list */
3480 putpkt ("qsThreadInfo");
3481 getpkt (&rs->buf, &rs->buf_size, 0);
3488 /* Packet not recognized. */
3489 rs->use_threadinfo_query = 0;
3496 /* Implement the to_update_thread_list function for the remote
3500 remote_target::update_thread_list ()
3502 struct threads_listing_context context;
3505 /* We have a few different mechanisms to fetch the thread list. Try
3506 them all, starting with the most preferred one first, falling
3507 back to older methods. */
3508 if (remote_get_threads_with_qxfer (this, &context)
3509 || remote_get_threads_with_qthreadinfo (this, &context)
3510 || remote_get_threads_with_ql (this, &context))
3512 struct thread_info *tp, *tmp;
3516 if (context.items.empty ()
3517 && remote_thread_always_alive (inferior_ptid))
3519 /* Some targets don't really support threads, but still
3520 reply an (empty) thread list in response to the thread
3521 listing packets, instead of replying "packet not
3522 supported". Exit early so we don't delete the main
3527 /* CONTEXT now holds the current thread list on the remote
3528 target end. Delete GDB-side threads no longer found on the
3530 ALL_THREADS_SAFE (tp, tmp)
3532 if (!context.contains_thread (tp->ptid))
3535 delete_thread (tp->ptid);
3539 /* Remove any unreported fork child threads from CONTEXT so
3540 that we don't interfere with follow fork, which is where
3541 creation of such threads is handled. */
3542 remove_new_fork_children (&context);
3544 /* And now add threads we don't know about yet to our list. */
3545 for (thread_item &item : context.items)
3547 if (item.ptid != null_ptid)
3549 /* In non-stop mode, we assume new found threads are
3550 executing until proven otherwise with a stop reply.
3551 In all-stop, we can only get here if all threads are
3553 int executing = target_is_non_stop_p () ? 1 : 0;
3555 remote_notice_new_inferior (item.ptid, executing);
3557 remote_thread_info *info = get_remote_thread_info (item.ptid);
3558 info->core = item.core;
3559 info->extra = std::move (item.extra);
3560 info->name = std::move (item.name);
3561 info->thread_handle = std::move (item.thread_handle);
3568 /* If no thread listing method is supported, then query whether
3569 each known thread is alive, one by one, with the T packet.
3570 If the target doesn't support threads at all, then this is a
3571 no-op. See remote_thread_alive. */
3577 * Collect a descriptive string about the given thread.
3578 * The target may say anything it wants to about the thread
3579 * (typically info about its blocked / runnable state, name, etc.).
3580 * This string will appear in the info threads display.
3582 * Optional: targets are not required to implement this function.
3586 remote_target::extra_thread_info (thread_info *tp)
3588 struct remote_state *rs = get_remote_state ();
3592 struct gdb_ext_thread_info threadinfo;
3593 static char display_buf[100]; /* arbitrary... */
3594 int n = 0; /* position in display_buf */
3596 if (rs->remote_desc == 0) /* paranoia */
3597 internal_error (__FILE__, __LINE__,
3598 _("remote_threads_extra_info"));
3600 if (ptid_equal (tp->ptid, magic_null_ptid)
3601 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
3602 /* This is the main thread which was added by GDB. The remote
3603 server doesn't know about it. */
3606 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3608 struct thread_info *info = find_thread_ptid (tp->ptid);
3610 if (info != NULL && info->priv != NULL)
3612 const std::string &extra = get_remote_thread_info (info)->extra;
3613 return !extra.empty () ? extra.c_str () : NULL;
3619 if (rs->use_threadextra_query)
3622 char *endb = rs->buf + get_remote_packet_size ();
3624 xsnprintf (b, endb - b, "qThreadExtraInfo,");
3626 write_ptid (b, endb, tp->ptid);
3629 getpkt (&rs->buf, &rs->buf_size, 0);
3630 if (rs->buf[0] != 0)
3632 n = std::min (strlen (rs->buf) / 2, sizeof (display_buf));
3633 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
3634 display_buf [result] = '\0';
3639 /* If the above query fails, fall back to the old method. */
3640 rs->use_threadextra_query = 0;
3641 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3642 | TAG_MOREDISPLAY | TAG_DISPLAY;
3643 int_to_threadref (&id, ptid_get_lwp (tp->ptid));
3644 if (remote_get_threadinfo (&id, set, &threadinfo))
3645 if (threadinfo.active)
3647 if (*threadinfo.shortname)
3648 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
3649 " Name: %s,", threadinfo.shortname);
3650 if (*threadinfo.display)
3651 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3652 " State: %s,", threadinfo.display);
3653 if (*threadinfo.more_display)
3654 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3655 " Priority: %s", threadinfo.more_display);
3659 /* For purely cosmetic reasons, clear up trailing commas. */
3660 if (',' == display_buf[n-1])
3661 display_buf[n-1] = ' ';
3670 remote_target::static_tracepoint_marker_at (CORE_ADDR addr,
3671 struct static_tracepoint_marker *marker)
3673 struct remote_state *rs = get_remote_state ();
3676 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
3678 p += hexnumstr (p, addr);
3680 getpkt (&rs->buf, &rs->buf_size, 0);
3684 error (_("Remote failure reply: %s"), p);
3688 parse_static_tracepoint_marker_definition (p, NULL, marker);
3695 std::vector<static_tracepoint_marker>
3696 remote_target::static_tracepoint_markers_by_strid (const char *strid)
3698 struct remote_state *rs = get_remote_state ();
3699 std::vector<static_tracepoint_marker> markers;
3701 static_tracepoint_marker marker;
3703 /* Ask for a first packet of static tracepoint marker
3706 getpkt (&rs->buf, &rs->buf_size, 0);
3709 error (_("Remote failure reply: %s"), p);
3715 parse_static_tracepoint_marker_definition (p, &p, &marker);
3717 if (strid == NULL || marker.str_id == strid)
3718 markers.push_back (std::move (marker));
3720 while (*p++ == ','); /* comma-separated list */
3721 /* Ask for another packet of static tracepoint definition. */
3723 getpkt (&rs->buf, &rs->buf_size, 0);
3731 /* Implement the to_get_ada_task_ptid function for the remote targets. */
3734 remote_target::get_ada_task_ptid (long lwp, long thread)
3736 return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
3740 /* Restart the remote side; this is an extended protocol operation. */
3743 extended_remote_restart (void)
3745 struct remote_state *rs = get_remote_state ();
3747 /* Send the restart command; for reasons I don't understand the
3748 remote side really expects a number after the "R". */
3749 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
3752 remote_fileio_reset ();
3755 /* Clean up connection to a remote debugger. */
3758 remote_target::close ()
3760 struct remote_state *rs = get_remote_state ();
3762 if (rs->remote_desc == NULL)
3763 return; /* already closed */
3765 /* Make sure we leave stdin registered in the event loop. */
3768 serial_close (rs->remote_desc);
3769 rs->remote_desc = NULL;
3771 /* We don't have a connection to the remote stub anymore. Get rid
3772 of all the inferiors and their threads we were controlling.
3773 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3774 will be unable to find the thread corresponding to (pid, 0, 0). */
3775 inferior_ptid = null_ptid;
3776 discard_all_inferiors ();
3778 /* We are closing the remote target, so we should discard
3779 everything of this target. */
3780 discard_pending_stop_replies_in_queue (rs);
3782 if (remote_async_inferior_event_token)
3783 delete_async_event_handler (&remote_async_inferior_event_token);
3785 remote_notif_state_xfree (rs->notif_state);
3787 trace_reset_local_state ();
3790 /* Query the remote side for the text, data and bss offsets. */
3795 struct remote_state *rs = get_remote_state ();
3798 int lose, num_segments = 0, do_sections, do_segments;
3799 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
3800 struct section_offsets *offs;
3801 struct symfile_segment_data *data;
3803 if (symfile_objfile == NULL)
3806 putpkt ("qOffsets");
3807 getpkt (&rs->buf, &rs->buf_size, 0);
3810 if (buf[0] == '\000')
3811 return; /* Return silently. Stub doesn't support
3815 warning (_("Remote failure reply: %s"), buf);
3819 /* Pick up each field in turn. This used to be done with scanf, but
3820 scanf will make trouble if CORE_ADDR size doesn't match
3821 conversion directives correctly. The following code will work
3822 with any size of CORE_ADDR. */
3823 text_addr = data_addr = bss_addr = 0;
3827 if (startswith (ptr, "Text="))
3830 /* Don't use strtol, could lose on big values. */
3831 while (*ptr && *ptr != ';')
3832 text_addr = (text_addr << 4) + fromhex (*ptr++);
3834 if (startswith (ptr, ";Data="))
3837 while (*ptr && *ptr != ';')
3838 data_addr = (data_addr << 4) + fromhex (*ptr++);
3843 if (!lose && startswith (ptr, ";Bss="))
3846 while (*ptr && *ptr != ';')
3847 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
3849 if (bss_addr != data_addr)
3850 warning (_("Target reported unsupported offsets: %s"), buf);
3855 else if (startswith (ptr, "TextSeg="))
3858 /* Don't use strtol, could lose on big values. */
3859 while (*ptr && *ptr != ';')
3860 text_addr = (text_addr << 4) + fromhex (*ptr++);
3863 if (startswith (ptr, ";DataSeg="))
3866 while (*ptr && *ptr != ';')
3867 data_addr = (data_addr << 4) + fromhex (*ptr++);
3875 error (_("Malformed response to offset query, %s"), buf);
3876 else if (*ptr != '\0')
3877 warning (_("Target reported unsupported offsets: %s"), buf);
3879 offs = ((struct section_offsets *)
3880 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
3881 memcpy (offs, symfile_objfile->section_offsets,
3882 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
3884 data = get_symfile_segment_data (symfile_objfile->obfd);
3885 do_segments = (data != NULL);
3886 do_sections = num_segments == 0;
3888 if (num_segments > 0)
3890 segments[0] = text_addr;
3891 segments[1] = data_addr;
3893 /* If we have two segments, we can still try to relocate everything
3894 by assuming that the .text and .data offsets apply to the whole
3895 text and data segments. Convert the offsets given in the packet
3896 to base addresses for symfile_map_offsets_to_segments. */
3897 else if (data && data->num_segments == 2)
3899 segments[0] = data->segment_bases[0] + text_addr;
3900 segments[1] = data->segment_bases[1] + data_addr;
3903 /* If the object file has only one segment, assume that it is text
3904 rather than data; main programs with no writable data are rare,
3905 but programs with no code are useless. Of course the code might
3906 have ended up in the data segment... to detect that we would need
3907 the permissions here. */
3908 else if (data && data->num_segments == 1)
3910 segments[0] = data->segment_bases[0] + text_addr;
3913 /* There's no way to relocate by segment. */
3919 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3920 offs, num_segments, segments);
3922 if (ret == 0 && !do_sections)
3923 error (_("Can not handle qOffsets TextSeg "
3924 "response with this symbol file"));
3931 free_symfile_segment_data (data);
3935 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3937 /* This is a temporary kludge to force data and bss to use the
3938 same offsets because that's what nlmconv does now. The real
3939 solution requires changes to the stub and remote.c that I
3940 don't have time to do right now. */
3942 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3943 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3946 objfile_relocate (symfile_objfile, offs);
3949 /* Send interrupt_sequence to remote target. */
3951 send_interrupt_sequence (void)
3953 struct remote_state *rs = get_remote_state ();
3955 if (interrupt_sequence_mode == interrupt_sequence_control_c)
3956 remote_serial_write ("\x03", 1);
3957 else if (interrupt_sequence_mode == interrupt_sequence_break)
3958 serial_send_break (rs->remote_desc);
3959 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3961 serial_send_break (rs->remote_desc);
3962 remote_serial_write ("g", 1);
3965 internal_error (__FILE__, __LINE__,
3966 _("Invalid value for interrupt_sequence_mode: %s."),
3967 interrupt_sequence_mode);
3971 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
3972 and extract the PTID. Returns NULL_PTID if not found. */
3975 stop_reply_extract_thread (char *stop_reply)
3977 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3981 /* Txx r:val ; r:val (...) */
3984 /* Look for "register" named "thread". */
3989 p1 = strchr (p, ':');
3993 if (strncmp (p, "thread", p1 - p) == 0)
3994 return read_ptid (++p1, &p);
3996 p1 = strchr (p, ';');
4008 /* Determine the remote side's current thread. If we have a stop
4009 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
4010 "thread" register we can extract the current thread from. If not,
4011 ask the remote which is the current thread with qC. The former
4012 method avoids a roundtrip. */
4015 get_current_thread (char *wait_status)
4017 ptid_t ptid = null_ptid;
4019 /* Note we don't use remote_parse_stop_reply as that makes use of
4020 the target architecture, which we haven't yet fully determined at
4022 if (wait_status != NULL)
4023 ptid = stop_reply_extract_thread (wait_status);
4024 if (ptid_equal (ptid, null_ptid))
4025 ptid = remote_current_thread (inferior_ptid);
4030 /* Query the remote target for which is the current thread/process,
4031 add it to our tables, and update INFERIOR_PTID. The caller is
4032 responsible for setting the state such that the remote end is ready
4033 to return the current thread.
4035 This function is called after handling the '?' or 'vRun' packets,
4036 whose response is a stop reply from which we can also try
4037 extracting the thread. If the target doesn't support the explicit
4038 qC query, we infer the current thread from that stop reply, passed
4039 in in WAIT_STATUS, which may be NULL. */
4042 add_current_inferior_and_thread (char *wait_status)
4044 struct remote_state *rs = get_remote_state ();
4047 inferior_ptid = null_ptid;
4049 /* Now, if we have thread information, update inferior_ptid. */
4050 ptid_t curr_ptid = get_current_thread (wait_status);
4052 if (curr_ptid != null_ptid)
4054 if (!remote_multi_process_p (rs))
4059 /* Without this, some commands which require an active target
4060 (such as kill) won't work. This variable serves (at least)
4061 double duty as both the pid of the target process (if it has
4062 such), and as a flag indicating that a target is active. */
4063 curr_ptid = magic_null_ptid;
4067 remote_add_inferior (fake_pid_p, ptid_get_pid (curr_ptid), -1, 1);
4069 /* Add the main thread and switch to it. Don't try reading
4070 registers yet, since we haven't fetched the target description
4072 thread_info *tp = add_thread_silent (curr_ptid);
4073 switch_to_thread_no_regs (tp);
4076 /* Print info about a thread that was found already stopped on
4080 print_one_stopped_thread (struct thread_info *thread)
4082 struct target_waitstatus *ws = &thread->suspend.waitstatus;
4084 switch_to_thread (thread->ptid);
4085 stop_pc = get_frame_pc (get_current_frame ());
4086 set_current_sal_from_frame (get_current_frame ());
4088 thread->suspend.waitstatus_pending_p = 0;
4090 if (ws->kind == TARGET_WAITKIND_STOPPED)
4092 enum gdb_signal sig = ws->value.sig;
4094 if (signal_print_state (sig))
4095 gdb::observers::signal_received.notify (sig);
4097 gdb::observers::normal_stop.notify (NULL, 1);
4100 /* Process all initial stop replies the remote side sent in response
4101 to the ? packet. These indicate threads that were already stopped
4102 on initial connection. We mark these threads as stopped and print
4103 their current frame before giving the user the prompt. */
4106 process_initial_stop_replies (int from_tty)
4108 int pending_stop_replies = stop_reply_queue_length ();
4109 struct inferior *inf;
4110 struct thread_info *thread;
4111 struct thread_info *selected = NULL;
4112 struct thread_info *lowest_stopped = NULL;
4113 struct thread_info *first = NULL;
4115 /* Consume the initial pending events. */
4116 while (pending_stop_replies-- > 0)
4118 ptid_t waiton_ptid = minus_one_ptid;
4120 struct target_waitstatus ws;
4121 int ignore_event = 0;
4122 struct thread_info *thread;
4124 memset (&ws, 0, sizeof (ws));
4125 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
4127 print_target_wait_results (waiton_ptid, event_ptid, &ws);
4131 case TARGET_WAITKIND_IGNORE:
4132 case TARGET_WAITKIND_NO_RESUMED:
4133 case TARGET_WAITKIND_SIGNALLED:
4134 case TARGET_WAITKIND_EXITED:
4135 /* We shouldn't see these, but if we do, just ignore. */
4137 fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
4141 case TARGET_WAITKIND_EXECD:
4142 xfree (ws.value.execd_pathname);
4151 thread = find_thread_ptid (event_ptid);
4153 if (ws.kind == TARGET_WAITKIND_STOPPED)
4155 enum gdb_signal sig = ws.value.sig;
4157 /* Stubs traditionally report SIGTRAP as initial signal,
4158 instead of signal 0. Suppress it. */
4159 if (sig == GDB_SIGNAL_TRAP)
4161 thread->suspend.stop_signal = sig;
4165 thread->suspend.waitstatus = ws;
4167 if (ws.kind != TARGET_WAITKIND_STOPPED
4168 || ws.value.sig != GDB_SIGNAL_0)
4169 thread->suspend.waitstatus_pending_p = 1;
4171 set_executing (event_ptid, 0);
4172 set_running (event_ptid, 0);
4173 get_remote_thread_info (thread)->vcont_resumed = 0;
4176 /* "Notice" the new inferiors before anything related to
4177 registers/memory. */
4183 inf->needs_setup = 1;
4187 thread = any_live_thread_of_process (inf->pid);
4188 notice_new_inferior (thread->ptid,
4189 thread->state == THREAD_RUNNING,
4194 /* If all-stop on top of non-stop, pause all threads. Note this
4195 records the threads' stop pc, so must be done after "noticing"
4199 stop_all_threads ();
4201 /* If all threads of an inferior were already stopped, we
4202 haven't setup the inferior yet. */
4208 if (inf->needs_setup)
4210 thread = any_live_thread_of_process (inf->pid);
4211 switch_to_thread_no_regs (thread);
4217 /* Now go over all threads that are stopped, and print their current
4218 frame. If all-stop, then if there's a signalled thread, pick
4220 ALL_NON_EXITED_THREADS (thread)
4226 set_running (thread->ptid, 0);
4227 else if (thread->state != THREAD_STOPPED)
4230 if (selected == NULL
4231 && thread->suspend.waitstatus_pending_p)
4234 if (lowest_stopped == NULL
4235 || thread->inf->num < lowest_stopped->inf->num
4236 || thread->per_inf_num < lowest_stopped->per_inf_num)
4237 lowest_stopped = thread;
4240 print_one_stopped_thread (thread);
4243 /* In all-stop, we only print the status of one thread, and leave
4244 others with their status pending. */
4249 thread = lowest_stopped;
4253 print_one_stopped_thread (thread);
4256 /* For "info program". */
4257 thread = inferior_thread ();
4258 if (thread->state == THREAD_STOPPED)
4259 set_last_target_status (inferior_ptid, thread->suspend.waitstatus);
4262 /* Start the remote connection and sync state. */
4265 remote_target::start_remote (int from_tty, int extended_p)
4267 struct remote_state *rs = get_remote_state ();
4268 struct packet_config *noack_config;
4269 char *wait_status = NULL;
4271 /* Signal other parts that we're going through the initial setup,
4272 and so things may not be stable yet. E.g., we don't try to
4273 install tracepoints until we've relocated symbols. Also, a
4274 Ctrl-C before we're connected and synced up can't interrupt the
4275 target. Instead, it offers to drop the (potentially wedged)
4277 rs->starting_up = 1;
4281 if (interrupt_on_connect)
4282 send_interrupt_sequence ();
4284 /* Ack any packet which the remote side has already sent. */
4285 remote_serial_write ("+", 1);
4287 /* The first packet we send to the target is the optional "supported
4288 packets" request. If the target can answer this, it will tell us
4289 which later probes to skip. */
4290 remote_query_supported ();
4292 /* If the stub wants to get a QAllow, compose one and send it. */
4293 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
4296 /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
4297 unknown 'v' packet with string "OK". "OK" gets interpreted by GDB
4298 as a reply to known packet. For packet "vFile:setfs:" it is an
4299 invalid reply and GDB would return error in
4300 remote_hostio_set_filesystem, making remote files access impossible.
4301 Disable "vFile:setfs:" in such case. Do not disable other 'v' packets as
4302 other "vFile" packets get correctly detected even on gdbserver < 7.7. */
4304 const char v_mustreplyempty[] = "vMustReplyEmpty";
4306 putpkt (v_mustreplyempty);
4307 getpkt (&rs->buf, &rs->buf_size, 0);
4308 if (strcmp (rs->buf, "OK") == 0)
4309 remote_protocol_packets[PACKET_vFile_setfs].support = PACKET_DISABLE;
4310 else if (strcmp (rs->buf, "") != 0)
4311 error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
4315 /* Next, we possibly activate noack mode.
4317 If the QStartNoAckMode packet configuration is set to AUTO,
4318 enable noack mode if the stub reported a wish for it with
4321 If set to TRUE, then enable noack mode even if the stub didn't
4322 report it in qSupported. If the stub doesn't reply OK, the
4323 session ends with an error.
4325 If FALSE, then don't activate noack mode, regardless of what the
4326 stub claimed should be the default with qSupported. */
4328 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4329 if (packet_config_support (noack_config) != PACKET_DISABLE)
4331 putpkt ("QStartNoAckMode");
4332 getpkt (&rs->buf, &rs->buf_size, 0);
4333 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
4339 /* Tell the remote that we are using the extended protocol. */
4341 getpkt (&rs->buf, &rs->buf_size, 0);
4344 /* Let the target know which signals it is allowed to pass down to
4346 update_signals_program_target ();
4348 /* Next, if the target can specify a description, read it. We do
4349 this before anything involving memory or registers. */
4350 target_find_description ();
4352 /* Next, now that we know something about the target, update the
4353 address spaces in the program spaces. */
4354 update_address_spaces ();
4356 /* On OSs where the list of libraries is global to all
4357 processes, we fetch them early. */
4358 if (gdbarch_has_global_solist (target_gdbarch ()))
4359 solib_add (NULL, from_tty, auto_solib_add);
4361 if (target_is_non_stop_p ())
4363 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
4364 error (_("Non-stop mode requested, but remote "
4365 "does not support non-stop"));
4367 putpkt ("QNonStop:1");
4368 getpkt (&rs->buf, &rs->buf_size, 0);
4370 if (strcmp (rs->buf, "OK") != 0)
4371 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
4373 /* Find about threads and processes the stub is already
4374 controlling. We default to adding them in the running state.
4375 The '?' query below will then tell us about which threads are
4377 this->update_thread_list ();
4379 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
4381 /* Don't assume that the stub can operate in all-stop mode.
4382 Request it explicitly. */
4383 putpkt ("QNonStop:0");
4384 getpkt (&rs->buf, &rs->buf_size, 0);
4386 if (strcmp (rs->buf, "OK") != 0)
4387 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
4390 /* Upload TSVs regardless of whether the target is running or not. The
4391 remote stub, such as GDBserver, may have some predefined or builtin
4392 TSVs, even if the target is not running. */
4393 if (get_trace_status (current_trace_status ()) != -1)
4395 struct uploaded_tsv *uploaded_tsvs = NULL;
4397 upload_trace_state_variables (&uploaded_tsvs);
4398 merge_uploaded_trace_state_variables (&uploaded_tsvs);
4401 /* Check whether the target is running now. */
4403 getpkt (&rs->buf, &rs->buf_size, 0);
4405 if (!target_is_non_stop_p ())
4407 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
4410 error (_("The target is not running (try extended-remote?)"));
4412 /* We're connected, but not running. Drop out before we
4413 call start_remote. */
4414 rs->starting_up = 0;
4419 /* Save the reply for later. */
4420 wait_status = (char *) alloca (strlen (rs->buf) + 1);
4421 strcpy (wait_status, rs->buf);
4424 /* Fetch thread list. */
4425 target_update_thread_list ();
4427 /* Let the stub know that we want it to return the thread. */
4428 set_continue_thread (minus_one_ptid);
4430 if (thread_count () == 0)
4432 /* Target has no concept of threads at all. GDB treats
4433 non-threaded target as single-threaded; add a main
4435 add_current_inferior_and_thread (wait_status);
4439 /* We have thread information; select the thread the target
4440 says should be current. If we're reconnecting to a
4441 multi-threaded program, this will ideally be the thread
4442 that last reported an event before GDB disconnected. */
4443 inferior_ptid = get_current_thread (wait_status);
4444 if (ptid_equal (inferior_ptid, null_ptid))
4446 /* Odd... The target was able to list threads, but not
4447 tell us which thread was current (no "thread"
4448 register in T stop reply?). Just pick the first
4449 thread in the thread list then. */
4452 fprintf_unfiltered (gdb_stdlog,
4453 "warning: couldn't determine remote "
4454 "current thread; picking first in list.\n");
4456 inferior_ptid = thread_list->ptid;
4460 /* init_wait_for_inferior should be called before get_offsets in order
4461 to manage `inserted' flag in bp loc in a correct state.
4462 breakpoint_init_inferior, called from init_wait_for_inferior, set
4463 `inserted' flag to 0, while before breakpoint_re_set, called from
4464 start_remote, set `inserted' flag to 1. In the initialization of
4465 inferior, breakpoint_init_inferior should be called first, and then
4466 breakpoint_re_set can be called. If this order is broken, state of
4467 `inserted' flag is wrong, and cause some problems on breakpoint
4469 init_wait_for_inferior ();
4471 get_offsets (); /* Get text, data & bss offsets. */
4473 /* If we could not find a description using qXfer, and we know
4474 how to do it some other way, try again. This is not
4475 supported for non-stop; it could be, but it is tricky if
4476 there are no stopped threads when we connect. */
4477 if (remote_read_description_p (this)
4478 && gdbarch_target_desc (target_gdbarch ()) == NULL)
4480 target_clear_description ();
4481 target_find_description ();
4484 /* Use the previously fetched status. */
4485 gdb_assert (wait_status != NULL);
4486 strcpy (rs->buf, wait_status);
4487 rs->cached_wait_status = 1;
4489 ::start_remote (from_tty); /* Initialize gdb process mechanisms. */
4493 /* Clear WFI global state. Do this before finding about new
4494 threads and inferiors, and setting the current inferior.
4495 Otherwise we would clear the proceed status of the current
4496 inferior when we want its stop_soon state to be preserved
4497 (see notice_new_inferior). */
4498 init_wait_for_inferior ();
4500 /* In non-stop, we will either get an "OK", meaning that there
4501 are no stopped threads at this time; or, a regular stop
4502 reply. In the latter case, there may be more than one thread
4503 stopped --- we pull them all out using the vStopped
4505 if (strcmp (rs->buf, "OK") != 0)
4507 struct notif_client *notif = ¬if_client_stop;
4509 /* remote_notif_get_pending_replies acks this one, and gets
4511 rs->notif_state->pending_event[notif_client_stop.id]
4512 = remote_notif_parse (notif, rs->buf);
4513 remote_notif_get_pending_events (notif);
4516 if (thread_count () == 0)
4519 error (_("The target is not running (try extended-remote?)"));
4521 /* We're connected, but not running. Drop out before we
4522 call start_remote. */
4523 rs->starting_up = 0;
4527 /* In non-stop mode, any cached wait status will be stored in
4528 the stop reply queue. */
4529 gdb_assert (wait_status == NULL);
4531 /* Report all signals during attach/startup. */
4532 pass_signals (0, NULL);
4534 /* If there are already stopped threads, mark them stopped and
4535 report their stops before giving the prompt to the user. */
4536 process_initial_stop_replies (from_tty);
4538 if (target_can_async_p ())
4542 /* If we connected to a live target, do some additional setup. */
4543 if (target_has_execution)
4545 if (symfile_objfile) /* No use without a symbol-file. */
4546 remote_check_symbols ();
4549 /* Possibly the target has been engaged in a trace run started
4550 previously; find out where things are at. */
4551 if (get_trace_status (current_trace_status ()) != -1)
4553 struct uploaded_tp *uploaded_tps = NULL;
4555 if (current_trace_status ()->running)
4556 printf_filtered (_("Trace is already running on the target.\n"));
4558 upload_tracepoints (&uploaded_tps);
4560 merge_uploaded_tracepoints (&uploaded_tps);
4563 /* Possibly the target has been engaged in a btrace record started
4564 previously; find out where things are at. */
4565 remote_btrace_maybe_reopen ();
4567 /* The thread and inferior lists are now synchronized with the
4568 target, our symbols have been relocated, and we're merged the
4569 target's tracepoints with ours. We're done with basic start
4571 rs->starting_up = 0;
4573 /* Maybe breakpoints are global and need to be inserted now. */
4574 if (breakpoints_should_be_inserted_now ())
4575 insert_breakpoints ();
4578 /* Open a connection to a remote debugger.
4579 NAME is the filename used for communication. */
4582 remote_target::open (const char *name, int from_tty)
4584 open_1 (name, from_tty, 0);
4587 /* Open a connection to a remote debugger using the extended
4588 remote gdb protocol. NAME is the filename used for communication. */
4591 extended_remote_target::open (const char *name, int from_tty)
4593 open_1 (name, from_tty, 1 /*extended_p */);
4596 /* Reset all packets back to "unknown support". Called when opening a
4597 new connection to a remote target. */
4600 reset_all_packet_configs_support (void)
4604 for (i = 0; i < PACKET_MAX; i++)
4605 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4608 /* Initialize all packet configs. */
4611 init_all_packet_configs (void)
4615 for (i = 0; i < PACKET_MAX; i++)
4617 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
4618 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4622 /* Symbol look-up. */
4625 remote_check_symbols (void)
4627 char *msg, *reply, *tmp;
4630 struct cleanup *old_chain;
4632 /* The remote side has no concept of inferiors that aren't running
4633 yet, it only knows about running processes. If we're connected
4634 but our current inferior is not running, we should not invite the
4635 remote target to request symbol lookups related to its
4636 (unrelated) current process. */
4637 if (!target_has_execution)
4640 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
4643 /* Make sure the remote is pointing at the right process. Note
4644 there's no way to select "no process". */
4645 set_general_process ();
4647 /* Allocate a message buffer. We can't reuse the input buffer in RS,
4648 because we need both at the same time. */
4649 msg = (char *) xmalloc (get_remote_packet_size ());
4650 old_chain = make_cleanup (xfree, msg);
4651 reply = (char *) xmalloc (get_remote_packet_size ());
4652 make_cleanup (free_current_contents, &reply);
4653 reply_size = get_remote_packet_size ();
4655 /* Invite target to request symbol lookups. */
4657 putpkt ("qSymbol::");
4658 getpkt (&reply, &reply_size, 0);
4659 packet_ok (reply, &remote_protocol_packets[PACKET_qSymbol]);
4661 while (startswith (reply, "qSymbol:"))
4663 struct bound_minimal_symbol sym;
4666 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
4668 sym = lookup_minimal_symbol (msg, NULL, NULL);
4669 if (sym.minsym == NULL)
4670 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
4673 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4674 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
4676 /* If this is a function address, return the start of code
4677 instead of any data function descriptor. */
4678 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
4682 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
4683 phex_nz (sym_addr, addr_size), &reply[8]);
4687 getpkt (&reply, &reply_size, 0);
4690 do_cleanups (old_chain);
4693 static struct serial *
4694 remote_serial_open (const char *name)
4696 static int udp_warning = 0;
4698 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
4699 of in ser-tcp.c, because it is the remote protocol assuming that the
4700 serial connection is reliable and not the serial connection promising
4702 if (!udp_warning && startswith (name, "udp:"))
4704 warning (_("The remote protocol may be unreliable over UDP.\n"
4705 "Some events may be lost, rendering further debugging "
4710 return serial_open (name);
4713 /* Inform the target of our permission settings. The permission flags
4714 work without this, but if the target knows the settings, it can do
4715 a couple things. First, it can add its own check, to catch cases
4716 that somehow manage to get by the permissions checks in target
4717 methods. Second, if the target is wired to disallow particular
4718 settings (for instance, a system in the field that is not set up to
4719 be able to stop at a breakpoint), it can object to any unavailable
4723 remote_target::set_permissions ()
4725 struct remote_state *rs = get_remote_state ();
4727 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
4728 "WriteReg:%x;WriteMem:%x;"
4729 "InsertBreak:%x;InsertTrace:%x;"
4730 "InsertFastTrace:%x;Stop:%x",
4731 may_write_registers, may_write_memory,
4732 may_insert_breakpoints, may_insert_tracepoints,
4733 may_insert_fast_tracepoints, may_stop);
4735 getpkt (&rs->buf, &rs->buf_size, 0);
4737 /* If the target didn't like the packet, warn the user. Do not try
4738 to undo the user's settings, that would just be maddening. */
4739 if (strcmp (rs->buf, "OK") != 0)
4740 warning (_("Remote refused setting permissions with: %s"), rs->buf);
4743 /* This type describes each known response to the qSupported
4745 struct protocol_feature
4747 /* The name of this protocol feature. */
4750 /* The default for this protocol feature. */
4751 enum packet_support default_support;
4753 /* The function to call when this feature is reported, or after
4754 qSupported processing if the feature is not supported.
4755 The first argument points to this structure. The second
4756 argument indicates whether the packet requested support be
4757 enabled, disabled, or probed (or the default, if this function
4758 is being called at the end of processing and this feature was
4759 not reported). The third argument may be NULL; if not NULL, it
4760 is a NUL-terminated string taken from the packet following
4761 this feature's name and an equals sign. */
4762 void (*func) (const struct protocol_feature *, enum packet_support,
4765 /* The corresponding packet for this feature. Only used if
4766 FUNC is remote_supported_packet. */
4771 remote_supported_packet (const struct protocol_feature *feature,
4772 enum packet_support support,
4773 const char *argument)
4777 warning (_("Remote qSupported response supplied an unexpected value for"
4778 " \"%s\"."), feature->name);
4782 remote_protocol_packets[feature->packet].support = support;
4786 remote_packet_size (const struct protocol_feature *feature,
4787 enum packet_support support, const char *value)
4789 struct remote_state *rs = get_remote_state ();
4794 if (support != PACKET_ENABLE)
4797 if (value == NULL || *value == '\0')
4799 warning (_("Remote target reported \"%s\" without a size."),
4805 packet_size = strtol (value, &value_end, 16);
4806 if (errno != 0 || *value_end != '\0' || packet_size < 0)
4808 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
4809 feature->name, value);
4813 /* Record the new maximum packet size. */
4814 rs->explicit_packet_size = packet_size;
4817 static const struct protocol_feature remote_protocol_features[] = {
4818 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
4819 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
4820 PACKET_qXfer_auxv },
4821 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
4822 PACKET_qXfer_exec_file },
4823 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
4824 PACKET_qXfer_features },
4825 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
4826 PACKET_qXfer_libraries },
4827 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
4828 PACKET_qXfer_libraries_svr4 },
4829 { "augmented-libraries-svr4-read", PACKET_DISABLE,
4830 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
4831 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
4832 PACKET_qXfer_memory_map },
4833 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
4834 PACKET_qXfer_spu_read },
4835 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
4836 PACKET_qXfer_spu_write },
4837 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
4838 PACKET_qXfer_osdata },
4839 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
4840 PACKET_qXfer_threads },
4841 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
4842 PACKET_qXfer_traceframe_info },
4843 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
4844 PACKET_QPassSignals },
4845 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
4846 PACKET_QCatchSyscalls },
4847 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
4848 PACKET_QProgramSignals },
4849 { "QSetWorkingDir", PACKET_DISABLE, remote_supported_packet,
4850 PACKET_QSetWorkingDir },
4851 { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
4852 PACKET_QStartupWithShell },
4853 { "QEnvironmentHexEncoded", PACKET_DISABLE, remote_supported_packet,
4854 PACKET_QEnvironmentHexEncoded },
4855 { "QEnvironmentReset", PACKET_DISABLE, remote_supported_packet,
4856 PACKET_QEnvironmentReset },
4857 { "QEnvironmentUnset", PACKET_DISABLE, remote_supported_packet,
4858 PACKET_QEnvironmentUnset },
4859 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
4860 PACKET_QStartNoAckMode },
4861 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
4862 PACKET_multiprocess_feature },
4863 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4864 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
4865 PACKET_qXfer_siginfo_read },
4866 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4867 PACKET_qXfer_siginfo_write },
4868 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
4869 PACKET_ConditionalTracepoints },
4870 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
4871 PACKET_ConditionalBreakpoints },
4872 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
4873 PACKET_BreakpointCommands },
4874 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
4875 PACKET_FastTracepoints },
4876 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
4877 PACKET_StaticTracepoints },
4878 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
4879 PACKET_InstallInTrace},
4880 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
4881 PACKET_DisconnectedTracing_feature },
4882 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4884 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4886 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4887 PACKET_TracepointSource },
4888 { "QAllow", PACKET_DISABLE, remote_supported_packet,
4890 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
4891 PACKET_EnableDisableTracepoints_feature },
4892 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4893 PACKET_qXfer_fdpic },
4894 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4896 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4897 PACKET_QDisableRandomization },
4898 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
4899 { "QTBuffer:size", PACKET_DISABLE,
4900 remote_supported_packet, PACKET_QTBuffer_size},
4901 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
4902 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4903 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
4904 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
4905 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
4906 PACKET_qXfer_btrace },
4907 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
4908 PACKET_qXfer_btrace_conf },
4909 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
4910 PACKET_Qbtrace_conf_bts_size },
4911 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
4912 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
4913 { "fork-events", PACKET_DISABLE, remote_supported_packet,
4914 PACKET_fork_event_feature },
4915 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
4916 PACKET_vfork_event_feature },
4917 { "exec-events", PACKET_DISABLE, remote_supported_packet,
4918 PACKET_exec_event_feature },
4919 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
4920 PACKET_Qbtrace_conf_pt_size },
4921 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
4922 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
4923 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
4926 static char *remote_support_xml;
4928 /* Register string appended to "xmlRegisters=" in qSupported query. */
4931 register_remote_support_xml (const char *xml)
4933 #if defined(HAVE_LIBEXPAT)
4934 if (remote_support_xml == NULL)
4935 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
4938 char *copy = xstrdup (remote_support_xml + 13);
4939 char *p = strtok (copy, ",");
4943 if (strcmp (p, xml) == 0)
4950 while ((p = strtok (NULL, ",")) != NULL);
4953 remote_support_xml = reconcat (remote_support_xml,
4954 remote_support_xml, ",", xml,
4961 remote_query_supported_append (char *msg, const char *append)
4964 return reconcat (msg, msg, ";", append, (char *) NULL);
4966 return xstrdup (append);
4970 remote_query_supported (void)
4972 struct remote_state *rs = get_remote_state ();
4975 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4977 /* The packet support flags are handled differently for this packet
4978 than for most others. We treat an error, a disabled packet, and
4979 an empty response identically: any features which must be reported
4980 to be used will be automatically disabled. An empty buffer
4981 accomplishes this, since that is also the representation for a list
4982 containing no features. */
4985 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
4988 struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
4990 if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
4991 q = remote_query_supported_append (q, "multiprocess+");
4993 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
4994 q = remote_query_supported_append (q, "swbreak+");
4995 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
4996 q = remote_query_supported_append (q, "hwbreak+");
4998 q = remote_query_supported_append (q, "qRelocInsn+");
5000 if (packet_set_cmd_state (PACKET_fork_event_feature)
5001 != AUTO_BOOLEAN_FALSE)
5002 q = remote_query_supported_append (q, "fork-events+");
5003 if (packet_set_cmd_state (PACKET_vfork_event_feature)
5004 != AUTO_BOOLEAN_FALSE)
5005 q = remote_query_supported_append (q, "vfork-events+");
5006 if (packet_set_cmd_state (PACKET_exec_event_feature)
5007 != AUTO_BOOLEAN_FALSE)
5008 q = remote_query_supported_append (q, "exec-events+");
5010 if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
5011 q = remote_query_supported_append (q, "vContSupported+");
5013 if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
5014 q = remote_query_supported_append (q, "QThreadEvents+");
5016 if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
5017 q = remote_query_supported_append (q, "no-resumed+");
5019 /* Keep this one last to work around a gdbserver <= 7.10 bug in
5020 the qSupported:xmlRegisters=i386 handling. */
5021 if (remote_support_xml != NULL
5022 && packet_support (PACKET_qXfer_features) != PACKET_DISABLE)
5023 q = remote_query_supported_append (q, remote_support_xml);
5025 q = reconcat (q, "qSupported:", q, (char *) NULL);
5028 do_cleanups (old_chain);
5030 getpkt (&rs->buf, &rs->buf_size, 0);
5032 /* If an error occured, warn, but do not return - just reset the
5033 buffer to empty and go on to disable features. */
5034 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
5037 warning (_("Remote failure reply: %s"), rs->buf);
5042 memset (seen, 0, sizeof (seen));
5047 enum packet_support is_supported;
5048 char *p, *end, *name_end, *value;
5050 /* First separate out this item from the rest of the packet. If
5051 there's another item after this, we overwrite the separator
5052 (terminated strings are much easier to work with). */
5054 end = strchr (p, ';');
5057 end = p + strlen (p);
5067 warning (_("empty item in \"qSupported\" response"));
5072 name_end = strchr (p, '=');
5075 /* This is a name=value entry. */
5076 is_supported = PACKET_ENABLE;
5077 value = name_end + 1;
5086 is_supported = PACKET_ENABLE;
5090 is_supported = PACKET_DISABLE;
5094 is_supported = PACKET_SUPPORT_UNKNOWN;
5098 warning (_("unrecognized item \"%s\" "
5099 "in \"qSupported\" response"), p);
5105 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5106 if (strcmp (remote_protocol_features[i].name, p) == 0)
5108 const struct protocol_feature *feature;
5111 feature = &remote_protocol_features[i];
5112 feature->func (feature, is_supported, value);
5117 /* If we increased the packet size, make sure to increase the global
5118 buffer size also. We delay this until after parsing the entire
5119 qSupported packet, because this is the same buffer we were
5121 if (rs->buf_size < rs->explicit_packet_size)
5123 rs->buf_size = rs->explicit_packet_size;
5124 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
5127 /* Handle the defaults for unmentioned features. */
5128 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5131 const struct protocol_feature *feature;
5133 feature = &remote_protocol_features[i];
5134 feature->func (feature, feature->default_support, NULL);
5138 /* Serial QUIT handler for the remote serial descriptor.
5140 Defers handling a Ctrl-C until we're done with the current
5141 command/response packet sequence, unless:
5143 - We're setting up the connection. Don't send a remote interrupt
5144 request, as we're not fully synced yet. Quit immediately
5147 - The target has been resumed in the foreground
5148 (target_terminal::is_ours is false) with a synchronous resume
5149 packet, and we're blocked waiting for the stop reply, thus a
5150 Ctrl-C should be immediately sent to the target.
5152 - We get a second Ctrl-C while still within the same serial read or
5153 write. In that case the serial is seemingly wedged --- offer to
5156 - We see a second Ctrl-C without target response, after having
5157 previously interrupted the target. In that case the target/stub
5158 is probably wedged --- offer to quit/disconnect.
5162 remote_serial_quit_handler (void)
5164 struct remote_state *rs = get_remote_state ();
5166 if (check_quit_flag ())
5168 /* If we're starting up, we're not fully synced yet. Quit
5170 if (rs->starting_up)
5172 else if (rs->got_ctrlc_during_io)
5174 if (query (_("The target is not responding to GDB commands.\n"
5175 "Stop debugging it? ")))
5176 remote_unpush_and_throw ();
5178 /* If ^C has already been sent once, offer to disconnect. */
5179 else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
5181 /* All-stop protocol, and blocked waiting for stop reply. Send
5182 an interrupt request. */
5183 else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
5184 target_interrupt ();
5186 rs->got_ctrlc_during_io = 1;
5190 /* Remove any of the remote.c targets from target stack. Upper targets depend
5191 on it so remove them first. */
5194 remote_unpush_target (void)
5196 pop_all_targets_at_and_above (process_stratum);
5200 remote_unpush_and_throw (void)
5202 remote_unpush_target ();
5203 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5207 remote_target::open_1 (const char *name, int from_tty, int extended_p)
5209 struct remote_state *rs = get_remote_state ();
5212 error (_("To open a remote debug connection, you need to specify what\n"
5213 "serial device is attached to the remote system\n"
5214 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
5216 /* See FIXME above. */
5217 if (!target_async_permitted)
5218 wait_forever_enabled_p = 1;
5220 /* If we're connected to a running target, target_preopen will kill it.
5221 Ask this question first, before target_preopen has a chance to kill
5223 if (rs->remote_desc != NULL && !have_inferiors ())
5226 && !query (_("Already connected to a remote target. Disconnect? ")))
5227 error (_("Still connected."));
5230 /* Here the possibly existing remote target gets unpushed. */
5231 target_preopen (from_tty);
5233 /* Make sure we send the passed signals list the next time we resume. */
5234 xfree (rs->last_pass_packet);
5235 rs->last_pass_packet = NULL;
5237 /* Make sure we send the program signals list the next time we
5239 xfree (rs->last_program_signals_packet);
5240 rs->last_program_signals_packet = NULL;
5242 remote_fileio_reset ();
5243 reopen_exec_file ();
5246 rs->remote_desc = remote_serial_open (name);
5247 if (!rs->remote_desc)
5248 perror_with_name (name);
5250 if (baud_rate != -1)
5252 if (serial_setbaudrate (rs->remote_desc, baud_rate))
5254 /* The requested speed could not be set. Error out to
5255 top level after closing remote_desc. Take care to
5256 set remote_desc to NULL to avoid closing remote_desc
5258 serial_close (rs->remote_desc);
5259 rs->remote_desc = NULL;
5260 perror_with_name (name);
5264 serial_setparity (rs->remote_desc, serial_parity);
5265 serial_raw (rs->remote_desc);
5267 /* If there is something sitting in the buffer we might take it as a
5268 response to a command, which would be bad. */
5269 serial_flush_input (rs->remote_desc);
5273 puts_filtered ("Remote debugging using ");
5274 puts_filtered (name);
5275 puts_filtered ("\n");
5278 remote_target *target
5279 = extended_p ? &extended_remote_ops : &remote_ops;
5280 push_target (target); /* Switch to using remote target now. */
5282 /* Register extra event sources in the event loop. */
5283 remote_async_inferior_event_token
5284 = create_async_event_handler (remote_async_inferior_event_handler,
5286 rs->notif_state = remote_notif_state_allocate ();
5288 /* Reset the target state; these things will be queried either by
5289 remote_query_supported or as they are needed. */
5290 reset_all_packet_configs_support ();
5291 rs->cached_wait_status = 0;
5292 rs->explicit_packet_size = 0;
5294 rs->extended = extended_p;
5295 rs->waiting_for_stop_reply = 0;
5296 rs->ctrlc_pending_p = 0;
5297 rs->got_ctrlc_during_io = 0;
5299 rs->general_thread = not_sent_ptid;
5300 rs->continue_thread = not_sent_ptid;
5301 rs->remote_traceframe_number = -1;
5303 rs->last_resume_exec_dir = EXEC_FORWARD;
5305 /* Probe for ability to use "ThreadInfo" query, as required. */
5306 rs->use_threadinfo_query = 1;
5307 rs->use_threadextra_query = 1;
5309 readahead_cache_invalidate ();
5311 if (target_async_permitted)
5313 /* FIXME: cagney/1999-09-23: During the initial connection it is
5314 assumed that the target is already ready and able to respond to
5315 requests. Unfortunately remote_start_remote() eventually calls
5316 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
5317 around this. Eventually a mechanism that allows
5318 wait_for_inferior() to expect/get timeouts will be
5320 wait_forever_enabled_p = 0;
5323 /* First delete any symbols previously loaded from shared libraries. */
5324 no_shared_libraries (NULL, 0);
5327 init_thread_list ();
5329 /* Start the remote connection. If error() or QUIT, discard this
5330 target (we'd otherwise be in an inconsistent state) and then
5331 propogate the error on up the exception chain. This ensures that
5332 the caller doesn't stumble along blindly assuming that the
5333 function succeeded. The CLI doesn't have this problem but other
5334 UI's, such as MI do.
5336 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
5337 this function should return an error indication letting the
5338 caller restore the previous state. Unfortunately the command
5339 ``target remote'' is directly wired to this function making that
5340 impossible. On a positive note, the CLI side of this problem has
5341 been fixed - the function set_cmd_context() makes it possible for
5342 all the ``target ....'' commands to share a common callback
5343 function. See cli-dump.c. */
5348 target->start_remote (from_tty, extended_p);
5350 CATCH (ex, RETURN_MASK_ALL)
5352 /* Pop the partially set up target - unless something else did
5353 already before throwing the exception. */
5354 if (rs->remote_desc != NULL)
5355 remote_unpush_target ();
5356 if (target_async_permitted)
5357 wait_forever_enabled_p = 1;
5358 throw_exception (ex);
5363 remote_btrace_reset ();
5365 if (target_async_permitted)
5366 wait_forever_enabled_p = 1;
5369 /* Detach the specified process. */
5372 remote_detach_pid (int pid)
5374 struct remote_state *rs = get_remote_state ();
5376 if (remote_multi_process_p (rs))
5377 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
5379 strcpy (rs->buf, "D");
5382 getpkt (&rs->buf, &rs->buf_size, 0);
5384 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
5386 else if (rs->buf[0] == '\0')
5387 error (_("Remote doesn't know how to detach"));
5389 error (_("Can't detach process."));
5392 /* This detaches a program to which we previously attached, using
5393 inferior_ptid to identify the process. After this is done, GDB
5394 can be used to debug some other program. We better not have left
5395 any breakpoints in the target program or it'll die when it hits
5399 remote_detach_1 (int from_tty, inferior *inf)
5401 int pid = ptid_get_pid (inferior_ptid);
5402 struct remote_state *rs = get_remote_state ();
5403 struct thread_info *tp = find_thread_ptid (inferior_ptid);
5406 if (!target_has_execution)
5407 error (_("No process to detach from."));
5409 target_announce_detach (from_tty);
5411 /* Tell the remote target to detach. */
5412 remote_detach_pid (pid);
5414 /* Exit only if this is the only active inferior. */
5415 if (from_tty && !rs->extended && number_of_live_inferiors () == 1)
5416 puts_filtered (_("Ending remote debugging.\n"));
5418 /* Check to see if we are detaching a fork parent. Note that if we
5419 are detaching a fork child, tp == NULL. */
5420 is_fork_parent = (tp != NULL
5421 && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
5423 /* If doing detach-on-fork, we don't mourn, because that will delete
5424 breakpoints that should be available for the followed inferior. */
5425 if (!is_fork_parent)
5427 /* Save the pid as a string before mourning, since that will
5428 unpush the remote target, and we need the string after. */
5429 std::string infpid = target_pid_to_str (pid_to_ptid (pid));
5431 target_mourn_inferior (inferior_ptid);
5432 if (print_inferior_events)
5433 printf_unfiltered (_("[Inferior %d (%s) detached]\n"),
5434 inf->num, infpid.c_str ());
5438 inferior_ptid = null_ptid;
5439 detach_inferior (pid);
5444 remote_target::detach (inferior *inf, int from_tty)
5446 remote_detach_1 (from_tty, inf);
5450 extended_remote_target::detach (inferior *inf, int from_tty)
5452 remote_detach_1 (from_tty, inf);
5455 /* Target follow-fork function for remote targets. On entry, and
5456 at return, the current inferior is the fork parent.
5458 Note that although this is currently only used for extended-remote,
5459 it is named remote_follow_fork in anticipation of using it for the
5460 remote target as well. */
5463 remote_target::follow_fork (int follow_child, int detach_fork)
5465 struct remote_state *rs = get_remote_state ();
5466 enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
5468 if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
5469 || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
5471 /* When following the parent and detaching the child, we detach
5472 the child here. For the case of following the child and
5473 detaching the parent, the detach is done in the target-
5474 independent follow fork code in infrun.c. We can't use
5475 target_detach when detaching an unfollowed child because
5476 the client side doesn't know anything about the child. */
5477 if (detach_fork && !follow_child)
5479 /* Detach the fork child. */
5483 child_ptid = inferior_thread ()->pending_follow.value.related_pid;
5484 child_pid = ptid_get_pid (child_ptid);
5486 remote_detach_pid (child_pid);
5492 /* Target follow-exec function for remote targets. Save EXECD_PATHNAME
5493 in the program space of the new inferior. On entry and at return the
5494 current inferior is the exec'ing inferior. INF is the new exec'd
5495 inferior, which may be the same as the exec'ing inferior unless
5496 follow-exec-mode is "new". */
5499 remote_target::follow_exec (struct inferior *inf, char *execd_pathname)
5501 /* We know that this is a target file name, so if it has the "target:"
5502 prefix we strip it off before saving it in the program space. */
5503 if (is_target_filename (execd_pathname))
5504 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
5506 set_pspace_remote_exec_file (inf->pspace, execd_pathname);
5509 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
5512 remote_target::disconnect (const char *args, int from_tty)
5515 error (_("Argument given to \"disconnect\" when remotely debugging."));
5517 /* Make sure we unpush even the extended remote targets. Calling
5518 target_mourn_inferior won't unpush, and remote_mourn won't
5519 unpush if there is more than one inferior left. */
5520 unpush_target (this);
5521 generic_mourn_inferior ();
5524 puts_filtered ("Ending remote debugging.\n");
5527 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
5528 be chatty about it. */
5531 extended_remote_target::attach (const char *args, int from_tty)
5533 struct remote_state *rs = get_remote_state ();
5535 char *wait_status = NULL;
5537 pid = parse_pid_to_attach (args);
5539 /* Remote PID can be freely equal to getpid, do not check it here the same
5540 way as in other targets. */
5542 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
5543 error (_("This target does not support attaching to a process"));
5547 char *exec_file = get_exec_file (0);
5550 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
5551 target_pid_to_str (pid_to_ptid (pid)));
5553 printf_unfiltered (_("Attaching to %s\n"),
5554 target_pid_to_str (pid_to_ptid (pid)));
5556 gdb_flush (gdb_stdout);
5559 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
5561 getpkt (&rs->buf, &rs->buf_size, 0);
5563 switch (packet_ok (rs->buf,
5564 &remote_protocol_packets[PACKET_vAttach]))
5567 if (!target_is_non_stop_p ())
5569 /* Save the reply for later. */
5570 wait_status = (char *) alloca (strlen (rs->buf) + 1);
5571 strcpy (wait_status, rs->buf);
5573 else if (strcmp (rs->buf, "OK") != 0)
5574 error (_("Attaching to %s failed with: %s"),
5575 target_pid_to_str (pid_to_ptid (pid)),
5578 case PACKET_UNKNOWN:
5579 error (_("This target does not support attaching to a process"));
5581 error (_("Attaching to %s failed"),
5582 target_pid_to_str (pid_to_ptid (pid)));
5585 set_current_inferior (remote_add_inferior (0, pid, 1, 0));
5587 inferior_ptid = pid_to_ptid (pid);
5589 if (target_is_non_stop_p ())
5591 struct thread_info *thread;
5593 /* Get list of threads. */
5594 update_thread_list ();
5596 thread = first_thread_of_process (pid);
5598 inferior_ptid = thread->ptid;
5600 inferior_ptid = pid_to_ptid (pid);
5602 /* Invalidate our notion of the remote current thread. */
5603 record_currthread (rs, minus_one_ptid);
5607 /* Now, if we have thread information, update inferior_ptid. */
5608 inferior_ptid = remote_current_thread (inferior_ptid);
5610 /* Add the main thread to the thread list. */
5611 thread_info *thr = add_thread_silent (inferior_ptid);
5612 /* Don't consider the thread stopped until we've processed the
5613 saved stop reply. */
5614 set_executing (thr->ptid, true);
5617 /* Next, if the target can specify a description, read it. We do
5618 this before anything involving memory or registers. */
5619 target_find_description ();
5621 if (!target_is_non_stop_p ())
5623 /* Use the previously fetched status. */
5624 gdb_assert (wait_status != NULL);
5626 if (target_can_async_p ())
5628 struct notif_event *reply
5629 = remote_notif_parse (¬if_client_stop, wait_status);
5631 push_stop_reply ((struct stop_reply *) reply);
5637 gdb_assert (wait_status != NULL);
5638 strcpy (rs->buf, wait_status);
5639 rs->cached_wait_status = 1;
5643 gdb_assert (wait_status == NULL);
5646 /* Implementation of the to_post_attach method. */
5649 extended_remote_target::post_attach (int pid)
5651 /* Get text, data & bss offsets. */
5654 /* In certain cases GDB might not have had the chance to start
5655 symbol lookup up until now. This could happen if the debugged
5656 binary is not using shared libraries, the vsyscall page is not
5657 present (on Linux) and the binary itself hadn't changed since the
5658 debugging process was started. */
5659 if (symfile_objfile != NULL)
5660 remote_check_symbols();
5664 /* Check for the availability of vCont. This function should also check
5668 remote_vcont_probe (struct remote_state *rs)
5672 strcpy (rs->buf, "vCont?");
5674 getpkt (&rs->buf, &rs->buf_size, 0);
5677 /* Make sure that the features we assume are supported. */
5678 if (startswith (buf, "vCont"))
5681 int support_c, support_C;
5683 rs->supports_vCont.s = 0;
5684 rs->supports_vCont.S = 0;
5687 rs->supports_vCont.t = 0;
5688 rs->supports_vCont.r = 0;
5689 while (p && *p == ';')
5692 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
5693 rs->supports_vCont.s = 1;
5694 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
5695 rs->supports_vCont.S = 1;
5696 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
5698 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
5700 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
5701 rs->supports_vCont.t = 1;
5702 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
5703 rs->supports_vCont.r = 1;
5705 p = strchr (p, ';');
5708 /* If c, and C are not all supported, we can't use vCont. Clearing
5709 BUF will make packet_ok disable the packet. */
5710 if (!support_c || !support_C)
5714 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
5717 /* Helper function for building "vCont" resumptions. Write a
5718 resumption to P. ENDP points to one-passed-the-end of the buffer
5719 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
5720 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
5721 resumed thread should be single-stepped and/or signalled. If PTID
5722 equals minus_one_ptid, then all threads are resumed; if PTID
5723 represents a process, then all threads of the process are resumed;
5724 the thread to be stepped and/or signalled is given in the global
5728 append_resumption (char *p, char *endp,
5729 ptid_t ptid, int step, enum gdb_signal siggnal)
5731 struct remote_state *rs = get_remote_state ();
5733 if (step && siggnal != GDB_SIGNAL_0)
5734 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
5736 /* GDB is willing to range step. */
5737 && use_range_stepping
5738 /* Target supports range stepping. */
5739 && rs->supports_vCont.r
5740 /* We don't currently support range stepping multiple
5741 threads with a wildcard (though the protocol allows it,
5742 so stubs shouldn't make an active effort to forbid
5744 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5746 struct thread_info *tp;
5748 if (ptid_equal (ptid, minus_one_ptid))
5750 /* If we don't know about the target thread's tid, then
5751 we're resuming magic_null_ptid (see caller). */
5752 tp = find_thread_ptid (magic_null_ptid);
5755 tp = find_thread_ptid (ptid);
5756 gdb_assert (tp != NULL);
5758 if (tp->control.may_range_step)
5760 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5762 p += xsnprintf (p, endp - p, ";r%s,%s",
5763 phex_nz (tp->control.step_range_start,
5765 phex_nz (tp->control.step_range_end,
5769 p += xsnprintf (p, endp - p, ";s");
5772 p += xsnprintf (p, endp - p, ";s");
5773 else if (siggnal != GDB_SIGNAL_0)
5774 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
5776 p += xsnprintf (p, endp - p, ";c");
5778 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
5782 /* All (-1) threads of process. */
5783 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
5785 p += xsnprintf (p, endp - p, ":");
5786 p = write_ptid (p, endp, nptid);
5788 else if (!ptid_equal (ptid, minus_one_ptid))
5790 p += xsnprintf (p, endp - p, ":");
5791 p = write_ptid (p, endp, ptid);
5797 /* Clear the thread's private info on resume. */
5800 resume_clear_thread_private_info (struct thread_info *thread)
5802 if (thread->priv != NULL)
5804 remote_thread_info *priv = get_remote_thread_info (thread);
5806 priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
5807 priv->watch_data_address = 0;
5811 /* Append a vCont continue-with-signal action for threads that have a
5812 non-zero stop signal. */
5815 append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
5817 struct thread_info *thread;
5819 ALL_NON_EXITED_THREADS (thread)
5820 if (ptid_match (thread->ptid, ptid)
5821 && !ptid_equal (inferior_ptid, thread->ptid)
5822 && thread->suspend.stop_signal != GDB_SIGNAL_0)
5824 p = append_resumption (p, endp, thread->ptid,
5825 0, thread->suspend.stop_signal);
5826 thread->suspend.stop_signal = GDB_SIGNAL_0;
5827 resume_clear_thread_private_info (thread);
5833 /* Set the target running, using the packets that use Hc
5837 remote_resume_with_hc (struct target_ops *ops,
5838 ptid_t ptid, int step, enum gdb_signal siggnal)
5840 struct remote_state *rs = get_remote_state ();
5841 struct thread_info *thread;
5844 rs->last_sent_signal = siggnal;
5845 rs->last_sent_step = step;
5847 /* The c/s/C/S resume packets use Hc, so set the continue
5849 if (ptid_equal (ptid, minus_one_ptid))
5850 set_continue_thread (any_thread_ptid);
5852 set_continue_thread (ptid);
5854 ALL_NON_EXITED_THREADS (thread)
5855 resume_clear_thread_private_info (thread);
5858 if (execution_direction == EXEC_REVERSE)
5860 /* We don't pass signals to the target in reverse exec mode. */
5861 if (info_verbose && siggnal != GDB_SIGNAL_0)
5862 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
5865 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
5866 error (_("Remote reverse-step not supported."));
5867 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
5868 error (_("Remote reverse-continue not supported."));
5870 strcpy (buf, step ? "bs" : "bc");
5872 else if (siggnal != GDB_SIGNAL_0)
5874 buf[0] = step ? 'S' : 'C';
5875 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
5876 buf[2] = tohex (((int) siggnal) & 0xf);
5880 strcpy (buf, step ? "s" : "c");
5885 /* Resume the remote inferior by using a "vCont" packet. The thread
5886 to be resumed is PTID; STEP and SIGGNAL indicate whether the
5887 resumed thread should be single-stepped and/or signalled. If PTID
5888 equals minus_one_ptid, then all threads are resumed; the thread to
5889 be stepped and/or signalled is given in the global INFERIOR_PTID.
5890 This function returns non-zero iff it resumes the inferior.
5892 This function issues a strict subset of all possible vCont commands
5896 remote_resume_with_vcont (ptid_t ptid, int step, enum gdb_signal siggnal)
5898 struct remote_state *rs = get_remote_state ();
5902 /* No reverse execution actions defined for vCont. */
5903 if (execution_direction == EXEC_REVERSE)
5906 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
5907 remote_vcont_probe (rs);
5909 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
5913 endp = rs->buf + get_remote_packet_size ();
5915 /* If we could generate a wider range of packets, we'd have to worry
5916 about overflowing BUF. Should there be a generic
5917 "multi-part-packet" packet? */
5919 p += xsnprintf (p, endp - p, "vCont");
5921 if (ptid_equal (ptid, magic_null_ptid))
5923 /* MAGIC_NULL_PTID means that we don't have any active threads,
5924 so we don't have any TID numbers the inferior will
5925 understand. Make sure to only send forms that do not specify
5927 append_resumption (p, endp, minus_one_ptid, step, siggnal);
5929 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
5931 /* Resume all threads (of all processes, or of a single
5932 process), with preference for INFERIOR_PTID. This assumes
5933 inferior_ptid belongs to the set of all threads we are about
5935 if (step || siggnal != GDB_SIGNAL_0)
5937 /* Step inferior_ptid, with or without signal. */
5938 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
5941 /* Also pass down any pending signaled resumption for other
5942 threads not the current. */
5943 p = append_pending_thread_resumptions (p, endp, ptid);
5945 /* And continue others without a signal. */
5946 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
5950 /* Scheduler locking; resume only PTID. */
5951 append_resumption (p, endp, ptid, step, siggnal);
5954 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
5957 if (target_is_non_stop_p ())
5959 /* In non-stop, the stub replies to vCont with "OK". The stop
5960 reply will be reported asynchronously by means of a `%Stop'
5962 getpkt (&rs->buf, &rs->buf_size, 0);
5963 if (strcmp (rs->buf, "OK") != 0)
5964 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5970 /* Tell the remote machine to resume. */
5973 remote_target::resume (ptid_t ptid, int step, enum gdb_signal siggnal)
5975 struct remote_state *rs = get_remote_state ();
5977 /* When connected in non-stop mode, the core resumes threads
5978 individually. Resuming remote threads directly in target_resume
5979 would thus result in sending one packet per thread. Instead, to
5980 minimize roundtrip latency, here we just store the resume
5981 request; the actual remote resumption will be done in
5982 target_commit_resume / remote_commit_resume, where we'll be able
5983 to do vCont action coalescing. */
5984 if (target_is_non_stop_p () && ::execution_direction != EXEC_REVERSE)
5986 remote_thread_info *remote_thr;
5988 if (ptid_equal (minus_one_ptid, ptid) || ptid_is_pid (ptid))
5989 remote_thr = get_remote_thread_info (inferior_ptid);
5991 remote_thr = get_remote_thread_info (ptid);
5993 remote_thr->last_resume_step = step;
5994 remote_thr->last_resume_sig = siggnal;
5998 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
5999 (explained in remote-notif.c:handle_notification) so
6000 remote_notif_process is not called. We need find a place where
6001 it is safe to start a 'vNotif' sequence. It is good to do it
6002 before resuming inferior, because inferior was stopped and no RSP
6003 traffic at that moment. */
6004 if (!target_is_non_stop_p ())
6005 remote_notif_process (rs->notif_state, ¬if_client_stop);
6007 rs->last_resume_exec_dir = ::execution_direction;
6009 /* Prefer vCont, and fallback to s/c/S/C, which use Hc. */
6010 if (!remote_resume_with_vcont (ptid, step, siggnal))
6011 remote_resume_with_hc (this, ptid, step, siggnal);
6013 /* We are about to start executing the inferior, let's register it
6014 with the event loop. NOTE: this is the one place where all the
6015 execution commands end up. We could alternatively do this in each
6016 of the execution commands in infcmd.c. */
6017 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
6018 into infcmd.c in order to allow inferior function calls to work
6019 NOT asynchronously. */
6020 if (target_can_async_p ())
6023 /* We've just told the target to resume. The remote server will
6024 wait for the inferior to stop, and then send a stop reply. In
6025 the mean time, we can't start another command/query ourselves
6026 because the stub wouldn't be ready to process it. This applies
6027 only to the base all-stop protocol, however. In non-stop (which
6028 only supports vCont), the stub replies with an "OK", and is
6029 immediate able to process further serial input. */
6030 if (!target_is_non_stop_p ())
6031 rs->waiting_for_stop_reply = 1;
6034 static void check_pending_events_prevent_wildcard_vcont
6035 (int *may_global_wildcard_vcont);
6036 static int is_pending_fork_parent_thread (struct thread_info *thread);
6038 /* Private per-inferior info for target remote processes. */
6040 struct remote_inferior : public private_inferior
6042 /* Whether we can send a wildcard vCont for this process. */
6043 bool may_wildcard_vcont = true;
6046 /* Get the remote private inferior data associated to INF. */
6048 static remote_inferior *
6049 get_remote_inferior (inferior *inf)
6051 if (inf->priv == NULL)
6052 inf->priv.reset (new remote_inferior);
6054 return static_cast<remote_inferior *> (inf->priv.get ());
6057 /* Structure used to track the construction of a vCont packet in the
6058 outgoing packet buffer. This is used to send multiple vCont
6059 packets if we have more actions than would fit a single packet. */
6061 struct vcont_builder
6063 /* Pointer to the first action. P points here if no action has been
6067 /* Where the next action will be appended. */
6070 /* The end of the buffer. Must never write past this. */
6074 /* Prepare the outgoing buffer for a new vCont packet. */
6077 vcont_builder_restart (struct vcont_builder *builder)
6079 struct remote_state *rs = get_remote_state ();
6081 builder->p = rs->buf;
6082 builder->endp = rs->buf + get_remote_packet_size ();
6083 builder->p += xsnprintf (builder->p, builder->endp - builder->p, "vCont");
6084 builder->first_action = builder->p;
6087 /* If the vCont packet being built has any action, send it to the
6091 vcont_builder_flush (struct vcont_builder *builder)
6093 struct remote_state *rs;
6095 if (builder->p == builder->first_action)
6098 rs = get_remote_state ();
6100 getpkt (&rs->buf, &rs->buf_size, 0);
6101 if (strcmp (rs->buf, "OK") != 0)
6102 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
6105 /* The largest action is range-stepping, with its two addresses. This
6106 is more than sufficient. If a new, bigger action is created, it'll
6107 quickly trigger a failed assertion in append_resumption (and we'll
6109 #define MAX_ACTION_SIZE 200
6111 /* Append a new vCont action in the outgoing packet being built. If
6112 the action doesn't fit the packet along with previous actions, push
6113 what we've got so far to the remote end and start over a new vCont
6114 packet (with the new action). */
6117 vcont_builder_push_action (struct vcont_builder *builder,
6118 ptid_t ptid, int step, enum gdb_signal siggnal)
6120 char buf[MAX_ACTION_SIZE + 1];
6124 endp = append_resumption (buf, buf + sizeof (buf),
6125 ptid, step, siggnal);
6127 /* Check whether this new action would fit in the vCont packet along
6128 with previous actions. If not, send what we've got so far and
6129 start a new vCont packet. */
6131 if (rsize > builder->endp - builder->p)
6133 vcont_builder_flush (builder);
6134 vcont_builder_restart (builder);
6136 /* Should now fit. */
6137 gdb_assert (rsize <= builder->endp - builder->p);
6140 memcpy (builder->p, buf, rsize);
6141 builder->p += rsize;
6145 /* to_commit_resume implementation. */
6148 remote_target::commit_resume ()
6150 struct inferior *inf;
6151 struct thread_info *tp;
6152 int any_process_wildcard;
6153 int may_global_wildcard_vcont;
6154 struct vcont_builder vcont_builder;
6156 /* If connected in all-stop mode, we'd send the remote resume
6157 request directly from remote_resume. Likewise if
6158 reverse-debugging, as there are no defined vCont actions for
6159 reverse execution. */
6160 if (!target_is_non_stop_p () || ::execution_direction == EXEC_REVERSE)
6163 /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
6164 instead of resuming all threads of each process individually.
6165 However, if any thread of a process must remain halted, we can't
6166 send wildcard resumes and must send one action per thread.
6168 Care must be taken to not resume threads/processes the server
6169 side already told us are stopped, but the core doesn't know about
6170 yet, because the events are still in the vStopped notification
6173 #1 => vCont s:p1.1;c
6175 #3 <= %Stopped T05 p1.1
6180 #8 (infrun handles the stop for p1.1 and continues stepping)
6181 #9 => vCont s:p1.1;c
6183 The last vCont above would resume thread p1.2 by mistake, because
6184 the server has no idea that the event for p1.2 had not been
6187 The server side must similarly ignore resume actions for the
6188 thread that has a pending %Stopped notification (and any other
6189 threads with events pending), until GDB acks the notification
6190 with vStopped. Otherwise, e.g., the following case is
6193 #1 => g (or any other packet)
6195 #3 <= %Stopped T05 p1.2
6196 #4 => vCont s:p1.1;c
6199 Above, the server must not resume thread p1.2. GDB can't know
6200 that p1.2 stopped until it acks the %Stopped notification, and
6201 since from GDB's perspective all threads should be running, it
6204 Finally, special care must also be given to handling fork/vfork
6205 events. A (v)fork event actually tells us that two processes
6206 stopped -- the parent and the child. Until we follow the fork,
6207 we must not resume the child. Therefore, if we have a pending
6208 fork follow, we must not send a global wildcard resume action
6209 (vCont;c). We can still send process-wide wildcards though. */
6211 /* Start by assuming a global wildcard (vCont;c) is possible. */
6212 may_global_wildcard_vcont = 1;
6214 /* And assume every process is individually wildcard-able too. */
6215 ALL_NON_EXITED_INFERIORS (inf)
6217 remote_inferior *priv = get_remote_inferior (inf);
6219 priv->may_wildcard_vcont = true;
6222 /* Check for any pending events (not reported or processed yet) and
6223 disable process and global wildcard resumes appropriately. */
6224 check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
6226 ALL_NON_EXITED_THREADS (tp)
6228 /* If a thread of a process is not meant to be resumed, then we
6229 can't wildcard that process. */
6232 get_remote_inferior (tp->inf)->may_wildcard_vcont = false;
6234 /* And if we can't wildcard a process, we can't wildcard
6235 everything either. */
6236 may_global_wildcard_vcont = 0;
6240 /* If a thread is the parent of an unfollowed fork, then we
6241 can't do a global wildcard, as that would resume the fork
6243 if (is_pending_fork_parent_thread (tp))
6244 may_global_wildcard_vcont = 0;
6247 /* Now let's build the vCont packet(s). Actions must be appended
6248 from narrower to wider scopes (thread -> process -> global). If
6249 we end up with too many actions for a single packet vcont_builder
6250 flushes the current vCont packet to the remote side and starts a
6252 vcont_builder_restart (&vcont_builder);
6254 /* Threads first. */
6255 ALL_NON_EXITED_THREADS (tp)
6257 remote_thread_info *remote_thr = get_remote_thread_info (tp);
6259 if (!tp->executing || remote_thr->vcont_resumed)
6262 gdb_assert (!thread_is_in_step_over_chain (tp));
6264 if (!remote_thr->last_resume_step
6265 && remote_thr->last_resume_sig == GDB_SIGNAL_0
6266 && get_remote_inferior (tp->inf)->may_wildcard_vcont)
6268 /* We'll send a wildcard resume instead. */
6269 remote_thr->vcont_resumed = 1;
6273 vcont_builder_push_action (&vcont_builder, tp->ptid,
6274 remote_thr->last_resume_step,
6275 remote_thr->last_resume_sig);
6276 remote_thr->vcont_resumed = 1;
6279 /* Now check whether we can send any process-wide wildcard. This is
6280 to avoid sending a global wildcard in the case nothing is
6281 supposed to be resumed. */
6282 any_process_wildcard = 0;
6284 ALL_NON_EXITED_INFERIORS (inf)
6286 if (get_remote_inferior (inf)->may_wildcard_vcont)
6288 any_process_wildcard = 1;
6293 if (any_process_wildcard)
6295 /* If all processes are wildcard-able, then send a single "c"
6296 action, otherwise, send an "all (-1) threads of process"
6297 continue action for each running process, if any. */
6298 if (may_global_wildcard_vcont)
6300 vcont_builder_push_action (&vcont_builder, minus_one_ptid,
6305 ALL_NON_EXITED_INFERIORS (inf)
6307 if (get_remote_inferior (inf)->may_wildcard_vcont)
6309 vcont_builder_push_action (&vcont_builder,
6310 pid_to_ptid (inf->pid),
6317 vcont_builder_flush (&vcont_builder);
6322 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
6323 thread, all threads of a remote process, or all threads of all
6327 remote_stop_ns (ptid_t ptid)
6329 struct remote_state *rs = get_remote_state ();
6331 char *endp = rs->buf + get_remote_packet_size ();
6333 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6334 remote_vcont_probe (rs);
6336 if (!rs->supports_vCont.t)
6337 error (_("Remote server does not support stopping threads"));
6339 if (ptid_equal (ptid, minus_one_ptid)
6340 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
6341 p += xsnprintf (p, endp - p, "vCont;t");
6346 p += xsnprintf (p, endp - p, "vCont;t:");
6348 if (ptid_is_pid (ptid))
6349 /* All (-1) threads of process. */
6350 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
6353 /* Small optimization: if we already have a stop reply for
6354 this thread, no use in telling the stub we want this
6356 if (peek_stop_reply (ptid))
6362 write_ptid (p, endp, nptid);
6365 /* In non-stop, we get an immediate OK reply. The stop reply will
6366 come in asynchronously by notification. */
6368 getpkt (&rs->buf, &rs->buf_size, 0);
6369 if (strcmp (rs->buf, "OK") != 0)
6370 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
6373 /* All-stop version of target_interrupt. Sends a break or a ^C to
6374 interrupt the remote target. It is undefined which thread of which
6375 process reports the interrupt. */
6378 remote_interrupt_as (void)
6380 struct remote_state *rs = get_remote_state ();
6382 rs->ctrlc_pending_p = 1;
6384 /* If the inferior is stopped already, but the core didn't know
6385 about it yet, just ignore the request. The cached wait status
6386 will be collected in remote_wait. */
6387 if (rs->cached_wait_status)
6390 /* Send interrupt_sequence to remote target. */
6391 send_interrupt_sequence ();
6394 /* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
6395 the remote target. It is undefined which thread of which process
6396 reports the interrupt. Throws an error if the packet is not
6397 supported by the server. */
6400 remote_interrupt_ns (void)
6402 struct remote_state *rs = get_remote_state ();
6404 char *endp = rs->buf + get_remote_packet_size ();
6406 xsnprintf (p, endp - p, "vCtrlC");
6408 /* In non-stop, we get an immediate OK reply. The stop reply will
6409 come in asynchronously by notification. */
6411 getpkt (&rs->buf, &rs->buf_size, 0);
6413 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
6417 case PACKET_UNKNOWN:
6418 error (_("No support for interrupting the remote target."));
6420 error (_("Interrupting target failed: %s"), rs->buf);
6424 /* Implement the to_stop function for the remote targets. */
6427 remote_target::stop (ptid_t ptid)
6430 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
6432 if (target_is_non_stop_p ())
6433 remote_stop_ns (ptid);
6436 /* We don't currently have a way to transparently pause the
6437 remote target in all-stop mode. Interrupt it instead. */
6438 remote_interrupt_as ();
6442 /* Implement the to_interrupt function for the remote targets. */
6445 remote_target::interrupt ()
6448 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
6450 if (target_is_non_stop_p ())
6451 remote_interrupt_ns ();
6453 remote_interrupt_as ();
6456 /* Implement the to_pass_ctrlc function for the remote targets. */
6459 remote_target::pass_ctrlc ()
6461 struct remote_state *rs = get_remote_state ();
6464 fprintf_unfiltered (gdb_stdlog, "remote_pass_ctrlc called\n");
6466 /* If we're starting up, we're not fully synced yet. Quit
6468 if (rs->starting_up)
6470 /* If ^C has already been sent once, offer to disconnect. */
6471 else if (rs->ctrlc_pending_p)
6474 target_interrupt ();
6477 /* Ask the user what to do when an interrupt is received. */
6480 interrupt_query (void)
6482 struct remote_state *rs = get_remote_state ();
6484 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
6486 if (query (_("The target is not responding to interrupt requests.\n"
6487 "Stop debugging it? ")))
6489 remote_unpush_target ();
6490 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
6495 if (query (_("Interrupted while waiting for the program.\n"
6496 "Give up waiting? ")))
6501 /* Enable/disable target terminal ownership. Most targets can use
6502 terminal groups to control terminal ownership. Remote targets are
6503 different in that explicit transfer of ownership to/from GDB/target
6507 remote_target::terminal_inferior ()
6509 /* NOTE: At this point we could also register our selves as the
6510 recipient of all input. Any characters typed could then be
6511 passed on down to the target. */
6515 remote_target::terminal_ours ()
6520 remote_console_output (char *msg)
6524 for (p = msg; p[0] && p[1]; p += 2)
6527 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
6531 fputs_unfiltered (tb, gdb_stdtarg);
6533 gdb_flush (gdb_stdtarg);
6536 DEF_VEC_O(cached_reg_t);
6538 typedef struct stop_reply
6540 struct notif_event base;
6542 /* The identifier of the thread about this event */
6545 /* The remote state this event is associated with. When the remote
6546 connection, represented by a remote_state object, is closed,
6547 all the associated stop_reply events should be released. */
6548 struct remote_state *rs;
6550 struct target_waitstatus ws;
6552 /* The architecture associated with the expedited registers. */
6555 /* Expedited registers. This makes remote debugging a bit more
6556 efficient for those targets that provide critical registers as
6557 part of their normal status mechanism (as another roundtrip to
6558 fetch them is avoided). */
6559 VEC(cached_reg_t) *regcache;
6561 enum target_stop_reason stop_reason;
6563 CORE_ADDR watch_data_address;
6568 DECLARE_QUEUE_P (stop_reply_p);
6569 DEFINE_QUEUE_P (stop_reply_p);
6570 /* The list of already fetched and acknowledged stop events. This
6571 queue is used for notification Stop, and other notifications
6572 don't need queue for their events, because the notification events
6573 of Stop can't be consumed immediately, so that events should be
6574 queued first, and be consumed by remote_wait_{ns,as} one per
6575 time. Other notifications can consume their events immediately,
6576 so queue is not needed for them. */
6577 static QUEUE (stop_reply_p) *stop_reply_queue;
6580 stop_reply_xfree (struct stop_reply *r)
6582 notif_event_xfree ((struct notif_event *) r);
6585 /* Return the length of the stop reply queue. */
6588 stop_reply_queue_length (void)
6590 return QUEUE_length (stop_reply_p, stop_reply_queue);
6594 remote_notif_stop_parse (struct notif_client *self, char *buf,
6595 struct notif_event *event)
6597 remote_parse_stop_reply (buf, (struct stop_reply *) event);
6601 remote_notif_stop_ack (struct notif_client *self, char *buf,
6602 struct notif_event *event)
6604 struct stop_reply *stop_reply = (struct stop_reply *) event;
6607 putpkt (self->ack_command);
6609 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
6610 /* We got an unknown stop reply. */
6611 error (_("Unknown stop reply"));
6613 push_stop_reply (stop_reply);
6617 remote_notif_stop_can_get_pending_events (struct notif_client *self)
6619 /* We can't get pending events in remote_notif_process for
6620 notification stop, and we have to do this in remote_wait_ns
6621 instead. If we fetch all queued events from stub, remote stub
6622 may exit and we have no chance to process them back in
6624 mark_async_event_handler (remote_async_inferior_event_token);
6629 stop_reply_dtr (struct notif_event *event)
6631 struct stop_reply *r = (struct stop_reply *) event;
6636 VEC_iterate (cached_reg_t, r->regcache, ix, reg);
6640 VEC_free (cached_reg_t, r->regcache);
6643 static struct notif_event *
6644 remote_notif_stop_alloc_reply (void)
6646 /* We cast to a pointer to the "base class". */
6647 struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
6649 r->dtr = stop_reply_dtr;
6654 /* A client of notification Stop. */
6656 struct notif_client notif_client_stop =
6660 remote_notif_stop_parse,
6661 remote_notif_stop_ack,
6662 remote_notif_stop_can_get_pending_events,
6663 remote_notif_stop_alloc_reply,
6667 /* A parameter to pass data in and out. */
6669 struct queue_iter_param
6672 struct stop_reply *output;
6675 /* Determine if THREAD_PTID is a pending fork parent thread. ARG contains
6676 the pid of the process that owns the threads we want to check, or
6677 -1 if we want to check all threads. */
6680 is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
6683 if (ws->kind == TARGET_WAITKIND_FORKED
6684 || ws->kind == TARGET_WAITKIND_VFORKED)
6686 if (event_pid == -1 || event_pid == ptid_get_pid (thread_ptid))
6693 /* Return the thread's pending status used to determine whether the
6694 thread is a fork parent stopped at a fork event. */
6696 static struct target_waitstatus *
6697 thread_pending_fork_status (struct thread_info *thread)
6699 if (thread->suspend.waitstatus_pending_p)
6700 return &thread->suspend.waitstatus;
6702 return &thread->pending_follow;
6705 /* Determine if THREAD is a pending fork parent thread. */
6708 is_pending_fork_parent_thread (struct thread_info *thread)
6710 struct target_waitstatus *ws = thread_pending_fork_status (thread);
6713 return is_pending_fork_parent (ws, pid, thread->ptid);
6716 /* Check whether EVENT is a fork event, and if it is, remove the
6717 fork child from the context list passed in DATA. */
6720 remove_child_of_pending_fork (QUEUE (stop_reply_p) *q,
6721 QUEUE_ITER (stop_reply_p) *iter,
6725 struct queue_iter_param *param = (struct queue_iter_param *) data;
6726 struct threads_listing_context *context
6727 = (struct threads_listing_context *) param->input;
6729 if (event->ws.kind == TARGET_WAITKIND_FORKED
6730 || event->ws.kind == TARGET_WAITKIND_VFORKED
6731 || event->ws.kind == TARGET_WAITKIND_THREAD_EXITED)
6732 context->remove_thread (event->ws.value.related_pid);
6737 /* If CONTEXT contains any fork child threads that have not been
6738 reported yet, remove them from the CONTEXT list. If such a
6739 thread exists it is because we are stopped at a fork catchpoint
6740 and have not yet called follow_fork, which will set up the
6741 host-side data structures for the new process. */
6744 remove_new_fork_children (struct threads_listing_context *context)
6746 struct thread_info * thread;
6748 struct notif_client *notif = ¬if_client_stop;
6749 struct queue_iter_param param;
6751 /* For any threads stopped at a fork event, remove the corresponding
6752 fork child threads from the CONTEXT list. */
6753 ALL_NON_EXITED_THREADS (thread)
6755 struct target_waitstatus *ws = thread_pending_fork_status (thread);
6757 if (is_pending_fork_parent (ws, pid, thread->ptid))
6758 context->remove_thread (ws->value.related_pid);
6761 /* Check for any pending fork events (not reported or processed yet)
6762 in process PID and remove those fork child threads from the
6763 CONTEXT list as well. */
6764 remote_notif_get_pending_events (notif);
6765 param.input = context;
6766 param.output = NULL;
6767 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6768 remove_child_of_pending_fork, ¶m);
6771 /* Check whether EVENT would prevent a global or process wildcard
6775 check_pending_event_prevents_wildcard_vcont_callback
6776 (QUEUE (stop_reply_p) *q,
6777 QUEUE_ITER (stop_reply_p) *iter,
6781 struct inferior *inf;
6782 int *may_global_wildcard_vcont = (int *) data;
6784 if (event->ws.kind == TARGET_WAITKIND_NO_RESUMED
6785 || event->ws.kind == TARGET_WAITKIND_NO_HISTORY)
6788 if (event->ws.kind == TARGET_WAITKIND_FORKED
6789 || event->ws.kind == TARGET_WAITKIND_VFORKED)
6790 *may_global_wildcard_vcont = 0;
6792 inf = find_inferior_ptid (event->ptid);
6794 /* This may be the first time we heard about this process.
6795 Regardless, we must not do a global wildcard resume, otherwise
6796 we'd resume this process too. */
6797 *may_global_wildcard_vcont = 0;
6799 get_remote_inferior (inf)->may_wildcard_vcont = false;
6804 /* Check whether any event pending in the vStopped queue would prevent
6805 a global or process wildcard vCont action. Clear
6806 *may_global_wildcard if we can't do a global wildcard (vCont;c),
6807 and clear the event inferior's may_wildcard_vcont flag if we can't
6808 do a process-wide wildcard resume (vCont;c:pPID.-1). */
6811 check_pending_events_prevent_wildcard_vcont (int *may_global_wildcard)
6813 struct notif_client *notif = ¬if_client_stop;
6815 remote_notif_get_pending_events (notif);
6816 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6817 check_pending_event_prevents_wildcard_vcont_callback,
6818 may_global_wildcard);
6821 /* Remove stop replies in the queue if its pid is equal to the given
6825 remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
6826 QUEUE_ITER (stop_reply_p) *iter,
6830 struct queue_iter_param *param = (struct queue_iter_param *) data;
6831 struct inferior *inf = (struct inferior *) param->input;
6833 if (ptid_get_pid (event->ptid) == inf->pid)
6835 stop_reply_xfree (event);
6836 QUEUE_remove_elem (stop_reply_p, q, iter);
6842 /* Discard all pending stop replies of inferior INF. */
6845 discard_pending_stop_replies (struct inferior *inf)
6847 struct queue_iter_param param;
6848 struct stop_reply *reply;
6849 struct remote_state *rs = get_remote_state ();
6850 struct remote_notif_state *rns = rs->notif_state;
6852 /* This function can be notified when an inferior exists. When the
6853 target is not remote, the notification state is NULL. */
6854 if (rs->remote_desc == NULL)
6857 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
6859 /* Discard the in-flight notification. */
6860 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
6862 stop_reply_xfree (reply);
6863 rns->pending_event[notif_client_stop.id] = NULL;
6867 param.output = NULL;
6868 /* Discard the stop replies we have already pulled with
6870 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6871 remove_stop_reply_for_inferior, ¶m);
6874 /* If its remote state is equal to the given remote state,
6875 remove EVENT from the stop reply queue. */
6878 remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
6879 QUEUE_ITER (stop_reply_p) *iter,
6883 struct queue_iter_param *param = (struct queue_iter_param *) data;
6884 struct remote_state *rs = (struct remote_state *) param->input;
6886 if (event->rs == rs)
6888 stop_reply_xfree (event);
6889 QUEUE_remove_elem (stop_reply_p, q, iter);
6895 /* Discard the stop replies for RS in stop_reply_queue. */
6898 discard_pending_stop_replies_in_queue (struct remote_state *rs)
6900 struct queue_iter_param param;
6903 param.output = NULL;
6904 /* Discard the stop replies we have already pulled with
6906 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6907 remove_stop_reply_of_remote_state, ¶m);
6910 /* A parameter to pass data in and out. */
6913 remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
6914 QUEUE_ITER (stop_reply_p) *iter,
6918 struct queue_iter_param *param = (struct queue_iter_param *) data;
6919 ptid_t *ptid = (ptid_t *) param->input;
6921 if (ptid_match (event->ptid, *ptid))
6923 param->output = event;
6924 QUEUE_remove_elem (stop_reply_p, q, iter);
6931 /* Remove the first reply in 'stop_reply_queue' which matches
6934 static struct stop_reply *
6935 remote_notif_remove_queued_reply (ptid_t ptid)
6937 struct queue_iter_param param;
6939 param.input = &ptid;
6940 param.output = NULL;
6942 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6943 remote_notif_remove_once_on_match, ¶m);
6945 fprintf_unfiltered (gdb_stdlog,
6946 "notif: discard queued event: 'Stop' in %s\n",
6947 target_pid_to_str (ptid));
6949 return param.output;
6952 /* Look for a queued stop reply belonging to PTID. If one is found,
6953 remove it from the queue, and return it. Returns NULL if none is
6954 found. If there are still queued events left to process, tell the
6955 event loop to get back to target_wait soon. */
6957 static struct stop_reply *
6958 queued_stop_reply (ptid_t ptid)
6960 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
6962 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
6963 /* There's still at least an event left. */
6964 mark_async_event_handler (remote_async_inferior_event_token);
6969 /* Push a fully parsed stop reply in the stop reply queue. Since we
6970 know that we now have at least one queued event left to pass to the
6971 core side, tell the event loop to get back to target_wait soon. */
6974 push_stop_reply (struct stop_reply *new_event)
6976 QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
6979 fprintf_unfiltered (gdb_stdlog,
6980 "notif: push 'Stop' %s to queue %d\n",
6981 target_pid_to_str (new_event->ptid),
6982 QUEUE_length (stop_reply_p,
6985 mark_async_event_handler (remote_async_inferior_event_token);
6989 stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
6990 QUEUE_ITER (stop_reply_p) *iter,
6991 struct stop_reply *event,
6994 ptid_t *ptid = (ptid_t *) data;
6996 return !(ptid_equal (*ptid, event->ptid)
6997 && event->ws.kind == TARGET_WAITKIND_STOPPED);
7000 /* Returns true if we have a stop reply for PTID. */
7003 peek_stop_reply (ptid_t ptid)
7005 return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
7006 stop_reply_match_ptid_and_ws, &ptid);
7009 /* Helper for remote_parse_stop_reply. Return nonzero if the substring
7010 starting with P and ending with PEND matches PREFIX. */
7013 strprefix (const char *p, const char *pend, const char *prefix)
7015 for ( ; p < pend; p++, prefix++)
7018 return *prefix == '\0';
7021 /* Parse the stop reply in BUF. Either the function succeeds, and the
7022 result is stored in EVENT, or throws an error. */
7025 remote_parse_stop_reply (char *buf, struct stop_reply *event)
7027 remote_arch_state *rsa = NULL;
7032 event->ptid = null_ptid;
7033 event->rs = get_remote_state ();
7034 event->ws.kind = TARGET_WAITKIND_IGNORE;
7035 event->ws.value.integer = 0;
7036 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
7037 event->regcache = NULL;
7042 case 'T': /* Status with PC, SP, FP, ... */
7043 /* Expedited reply, containing Signal, {regno, reg} repeat. */
7044 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
7046 n... = register number
7047 r... = register contents
7050 p = &buf[3]; /* after Txx */
7056 p1 = strchr (p, ':');
7058 error (_("Malformed packet(a) (missing colon): %s\n\
7062 error (_("Malformed packet(a) (missing register number): %s\n\
7066 /* Some "registers" are actually extended stop information.
7067 Note if you're adding a new entry here: GDB 7.9 and
7068 earlier assume that all register "numbers" that start
7069 with an hex digit are real register numbers. Make sure
7070 the server only sends such a packet if it knows the
7071 client understands it. */
7073 if (strprefix (p, p1, "thread"))
7074 event->ptid = read_ptid (++p1, &p);
7075 else if (strprefix (p, p1, "syscall_entry"))
7079 event->ws.kind = TARGET_WAITKIND_SYSCALL_ENTRY;
7080 p = unpack_varlen_hex (++p1, &sysno);
7081 event->ws.value.syscall_number = (int) sysno;
7083 else if (strprefix (p, p1, "syscall_return"))
7087 event->ws.kind = TARGET_WAITKIND_SYSCALL_RETURN;
7088 p = unpack_varlen_hex (++p1, &sysno);
7089 event->ws.value.syscall_number = (int) sysno;
7091 else if (strprefix (p, p1, "watch")
7092 || strprefix (p, p1, "rwatch")
7093 || strprefix (p, p1, "awatch"))
7095 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
7096 p = unpack_varlen_hex (++p1, &addr);
7097 event->watch_data_address = (CORE_ADDR) addr;
7099 else if (strprefix (p, p1, "swbreak"))
7101 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
7103 /* Make sure the stub doesn't forget to indicate support
7105 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
7106 error (_("Unexpected swbreak stop reason"));
7108 /* The value part is documented as "must be empty",
7109 though we ignore it, in case we ever decide to make
7110 use of it in a backward compatible way. */
7111 p = strchrnul (p1 + 1, ';');
7113 else if (strprefix (p, p1, "hwbreak"))
7115 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
7117 /* Make sure the stub doesn't forget to indicate support
7119 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
7120 error (_("Unexpected hwbreak stop reason"));
7123 p = strchrnul (p1 + 1, ';');
7125 else if (strprefix (p, p1, "library"))
7127 event->ws.kind = TARGET_WAITKIND_LOADED;
7128 p = strchrnul (p1 + 1, ';');
7130 else if (strprefix (p, p1, "replaylog"))
7132 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
7133 /* p1 will indicate "begin" or "end", but it makes
7134 no difference for now, so ignore it. */
7135 p = strchrnul (p1 + 1, ';');
7137 else if (strprefix (p, p1, "core"))
7141 p = unpack_varlen_hex (++p1, &c);
7144 else if (strprefix (p, p1, "fork"))
7146 event->ws.value.related_pid = read_ptid (++p1, &p);
7147 event->ws.kind = TARGET_WAITKIND_FORKED;
7149 else if (strprefix (p, p1, "vfork"))
7151 event->ws.value.related_pid = read_ptid (++p1, &p);
7152 event->ws.kind = TARGET_WAITKIND_VFORKED;
7154 else if (strprefix (p, p1, "vforkdone"))
7156 event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
7157 p = strchrnul (p1 + 1, ';');
7159 else if (strprefix (p, p1, "exec"))
7162 char pathname[PATH_MAX];
7165 /* Determine the length of the execd pathname. */
7166 p = unpack_varlen_hex (++p1, &ignored);
7167 pathlen = (p - p1) / 2;
7169 /* Save the pathname for event reporting and for
7170 the next run command. */
7171 hex2bin (p1, (gdb_byte *) pathname, pathlen);
7172 pathname[pathlen] = '\0';
7174 /* This is freed during event handling. */
7175 event->ws.value.execd_pathname = xstrdup (pathname);
7176 event->ws.kind = TARGET_WAITKIND_EXECD;
7178 /* Skip the registers included in this packet, since
7179 they may be for an architecture different from the
7180 one used by the original program. */
7183 else if (strprefix (p, p1, "create"))
7185 event->ws.kind = TARGET_WAITKIND_THREAD_CREATED;
7186 p = strchrnul (p1 + 1, ';');
7195 p = strchrnul (p1 + 1, ';');
7200 /* Maybe a real ``P'' register number. */
7201 p_temp = unpack_varlen_hex (p, &pnum);
7202 /* If the first invalid character is the colon, we got a
7203 register number. Otherwise, it's an unknown stop
7207 /* If we haven't parsed the event's thread yet, find
7208 it now, in order to find the architecture of the
7209 reported expedited registers. */
7210 if (event->ptid == null_ptid)
7212 const char *thr = strstr (p1 + 1, ";thread:");
7214 event->ptid = read_ptid (thr + strlen (";thread:"),
7218 /* Either the current thread hasn't changed,
7219 or the inferior is not multi-threaded.
7220 The event must be for the thread we last
7221 set as (or learned as being) current. */
7222 event->ptid = event->rs->general_thread;
7228 inferior *inf = (event->ptid == null_ptid
7230 : find_inferior_ptid (event->ptid));
7231 /* If this is the first time we learn anything
7232 about this process, skip the registers
7233 included in this packet, since we don't yet
7234 know which architecture to use to parse them.
7235 We'll determine the architecture later when
7236 we process the stop reply and retrieve the
7237 target description, via
7238 remote_notice_new_inferior ->
7239 post_create_inferior. */
7242 p = strchrnul (p1 + 1, ';');
7247 event->arch = inf->gdbarch;
7248 rsa = get_remote_arch_state (event->arch);
7252 = packet_reg_from_pnum (event->arch, rsa, pnum);
7253 cached_reg_t cached_reg;
7256 error (_("Remote sent bad register number %s: %s\n\
7258 hex_string (pnum), p, buf);
7260 cached_reg.num = reg->regnum;
7261 cached_reg.data = (gdb_byte *)
7262 xmalloc (register_size (event->arch, reg->regnum));
7265 fieldsize = hex2bin (p, cached_reg.data,
7266 register_size (event->arch, reg->regnum));
7268 if (fieldsize < register_size (event->arch, reg->regnum))
7269 warning (_("Remote reply is too short: %s"), buf);
7271 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
7275 /* Not a number. Silently skip unknown optional
7277 p = strchrnul (p1 + 1, ';');
7282 error (_("Remote register badly formatted: %s\nhere: %s"),
7287 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
7291 case 'S': /* Old style status, just signal only. */
7295 event->ws.kind = TARGET_WAITKIND_STOPPED;
7296 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
7297 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
7298 event->ws.value.sig = (enum gdb_signal) sig;
7300 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
7303 case 'w': /* Thread exited. */
7308 event->ws.kind = TARGET_WAITKIND_THREAD_EXITED;
7309 p = unpack_varlen_hex (&buf[1], &value);
7310 event->ws.value.integer = value;
7312 error (_("stop reply packet badly formatted: %s"), buf);
7313 event->ptid = read_ptid (++p, NULL);
7316 case 'W': /* Target exited. */
7323 /* GDB used to accept only 2 hex chars here. Stubs should
7324 only send more if they detect GDB supports multi-process
7326 p = unpack_varlen_hex (&buf[1], &value);
7330 /* The remote process exited. */
7331 event->ws.kind = TARGET_WAITKIND_EXITED;
7332 event->ws.value.integer = value;
7336 /* The remote process exited with a signal. */
7337 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
7338 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
7339 event->ws.value.sig = (enum gdb_signal) value;
7341 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
7344 /* If no process is specified, assume inferior_ptid. */
7345 pid = ptid_get_pid (inferior_ptid);
7354 else if (startswith (p, "process:"))
7358 p += sizeof ("process:") - 1;
7359 unpack_varlen_hex (p, &upid);
7363 error (_("unknown stop reply packet: %s"), buf);
7366 error (_("unknown stop reply packet: %s"), buf);
7367 event->ptid = pid_to_ptid (pid);
7371 event->ws.kind = TARGET_WAITKIND_NO_RESUMED;
7372 event->ptid = minus_one_ptid;
7376 if (target_is_non_stop_p () && ptid_equal (event->ptid, null_ptid))
7377 error (_("No process or thread specified in stop reply: %s"), buf);
7380 /* When the stub wants to tell GDB about a new notification reply, it
7381 sends a notification (%Stop, for example). Those can come it at
7382 any time, hence, we have to make sure that any pending
7383 putpkt/getpkt sequence we're making is finished, before querying
7384 the stub for more events with the corresponding ack command
7385 (vStopped, for example). E.g., if we started a vStopped sequence
7386 immediately upon receiving the notification, something like this
7394 1.6) <-- (registers reply to step #1.3)
7396 Obviously, the reply in step #1.6 would be unexpected to a vStopped
7399 To solve this, whenever we parse a %Stop notification successfully,
7400 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
7401 doing whatever we were doing:
7407 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
7408 2.5) <-- (registers reply to step #2.3)
7410 Eventualy after step #2.5, we return to the event loop, which
7411 notices there's an event on the
7412 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
7413 associated callback --- the function below. At this point, we're
7414 always safe to start a vStopped sequence. :
7417 2.7) <-- T05 thread:2
7423 remote_notif_get_pending_events (struct notif_client *nc)
7425 struct remote_state *rs = get_remote_state ();
7427 if (rs->notif_state->pending_event[nc->id] != NULL)
7430 fprintf_unfiltered (gdb_stdlog,
7431 "notif: process: '%s' ack pending event\n",
7435 nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
7436 rs->notif_state->pending_event[nc->id] = NULL;
7440 getpkt (&rs->buf, &rs->buf_size, 0);
7441 if (strcmp (rs->buf, "OK") == 0)
7444 remote_notif_ack (nc, rs->buf);
7450 fprintf_unfiltered (gdb_stdlog,
7451 "notif: process: '%s' no pending reply\n",
7456 /* Called when it is decided that STOP_REPLY holds the info of the
7457 event that is to be returned to the core. This function always
7458 destroys STOP_REPLY. */
7461 process_stop_reply (struct stop_reply *stop_reply,
7462 struct target_waitstatus *status)
7466 *status = stop_reply->ws;
7467 ptid = stop_reply->ptid;
7469 /* If no thread/process was reported by the stub, assume the current
7471 if (ptid_equal (ptid, null_ptid))
7472 ptid = inferior_ptid;
7474 if (status->kind != TARGET_WAITKIND_EXITED
7475 && status->kind != TARGET_WAITKIND_SIGNALLED
7476 && status->kind != TARGET_WAITKIND_NO_RESUMED)
7478 /* Expedited registers. */
7479 if (stop_reply->regcache)
7481 struct regcache *regcache
7482 = get_thread_arch_regcache (ptid, stop_reply->arch);
7487 VEC_iterate (cached_reg_t, stop_reply->regcache, ix, reg);
7490 regcache_raw_supply (regcache, reg->num, reg->data);
7494 VEC_free (cached_reg_t, stop_reply->regcache);
7497 remote_notice_new_inferior (ptid, 0);
7498 remote_thread_info *remote_thr = get_remote_thread_info (ptid);
7499 remote_thr->core = stop_reply->core;
7500 remote_thr->stop_reason = stop_reply->stop_reason;
7501 remote_thr->watch_data_address = stop_reply->watch_data_address;
7502 remote_thr->vcont_resumed = 0;
7505 stop_reply_xfree (stop_reply);
7509 /* The non-stop mode version of target_wait. */
7512 remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
7514 struct remote_state *rs = get_remote_state ();
7515 struct stop_reply *stop_reply;
7519 /* If in non-stop mode, get out of getpkt even if a
7520 notification is received. */
7522 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7523 0 /* forever */, &is_notif);
7526 if (ret != -1 && !is_notif)
7529 case 'E': /* Error of some sort. */
7530 /* We're out of sync with the target now. Did it continue
7531 or not? We can't tell which thread it was in non-stop,
7532 so just ignore this. */
7533 warning (_("Remote failure reply: %s"), rs->buf);
7535 case 'O': /* Console output. */
7536 remote_console_output (rs->buf + 1);
7539 warning (_("Invalid remote reply: %s"), rs->buf);
7543 /* Acknowledge a pending stop reply that may have arrived in the
7545 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
7546 remote_notif_get_pending_events (¬if_client_stop);
7548 /* If indeed we noticed a stop reply, we're done. */
7549 stop_reply = queued_stop_reply (ptid);
7550 if (stop_reply != NULL)
7551 return process_stop_reply (stop_reply, status);
7553 /* Still no event. If we're just polling for an event, then
7554 return to the event loop. */
7555 if (options & TARGET_WNOHANG)
7557 status->kind = TARGET_WAITKIND_IGNORE;
7558 return minus_one_ptid;
7561 /* Otherwise do a blocking wait. */
7562 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7563 1 /* forever */, &is_notif);
7567 /* Wait until the remote machine stops, then return, storing status in
7568 STATUS just as `wait' would. */
7571 remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
7573 struct remote_state *rs = get_remote_state ();
7574 ptid_t event_ptid = null_ptid;
7576 struct stop_reply *stop_reply;
7580 status->kind = TARGET_WAITKIND_IGNORE;
7581 status->value.integer = 0;
7583 stop_reply = queued_stop_reply (ptid);
7584 if (stop_reply != NULL)
7585 return process_stop_reply (stop_reply, status);
7587 if (rs->cached_wait_status)
7588 /* Use the cached wait status, but only once. */
7589 rs->cached_wait_status = 0;
7594 int forever = ((options & TARGET_WNOHANG) == 0
7595 && wait_forever_enabled_p);
7597 if (!rs->waiting_for_stop_reply)
7599 status->kind = TARGET_WAITKIND_NO_RESUMED;
7600 return minus_one_ptid;
7603 /* FIXME: cagney/1999-09-27: If we're in async mode we should
7604 _never_ wait for ever -> test on target_is_async_p().
7605 However, before we do that we need to ensure that the caller
7606 knows how to take the target into/out of async mode. */
7607 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7608 forever, &is_notif);
7610 /* GDB gets a notification. Return to core as this event is
7612 if (ret != -1 && is_notif)
7613 return minus_one_ptid;
7615 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
7616 return minus_one_ptid;
7621 /* Assume that the target has acknowledged Ctrl-C unless we receive
7622 an 'F' or 'O' packet. */
7623 if (buf[0] != 'F' && buf[0] != 'O')
7624 rs->ctrlc_pending_p = 0;
7628 case 'E': /* Error of some sort. */
7629 /* We're out of sync with the target now. Did it continue or
7630 not? Not is more likely, so report a stop. */
7631 rs->waiting_for_stop_reply = 0;
7633 warning (_("Remote failure reply: %s"), buf);
7634 status->kind = TARGET_WAITKIND_STOPPED;
7635 status->value.sig = GDB_SIGNAL_0;
7637 case 'F': /* File-I/O request. */
7638 /* GDB may access the inferior memory while handling the File-I/O
7639 request, but we don't want GDB accessing memory while waiting
7640 for a stop reply. See the comments in putpkt_binary. Set
7641 waiting_for_stop_reply to 0 temporarily. */
7642 rs->waiting_for_stop_reply = 0;
7643 remote_fileio_request (buf, rs->ctrlc_pending_p);
7644 rs->ctrlc_pending_p = 0;
7645 /* GDB handled the File-I/O request, and the target is running
7646 again. Keep waiting for events. */
7647 rs->waiting_for_stop_reply = 1;
7649 case 'N': case 'T': case 'S': case 'X': case 'W':
7651 struct stop_reply *stop_reply;
7653 /* There is a stop reply to handle. */
7654 rs->waiting_for_stop_reply = 0;
7657 = (struct stop_reply *) remote_notif_parse (¬if_client_stop,
7660 event_ptid = process_stop_reply (stop_reply, status);
7663 case 'O': /* Console output. */
7664 remote_console_output (buf + 1);
7667 if (rs->last_sent_signal != GDB_SIGNAL_0)
7669 /* Zero length reply means that we tried 'S' or 'C' and the
7670 remote system doesn't support it. */
7671 target_terminal::ours_for_output ();
7673 ("Can't send signals to this remote system. %s not sent.\n",
7674 gdb_signal_to_name (rs->last_sent_signal));
7675 rs->last_sent_signal = GDB_SIGNAL_0;
7676 target_terminal::inferior ();
7678 strcpy (buf, rs->last_sent_step ? "s" : "c");
7682 /* else fallthrough */
7684 warning (_("Invalid remote reply: %s"), buf);
7688 if (status->kind == TARGET_WAITKIND_NO_RESUMED)
7689 return minus_one_ptid;
7690 else if (status->kind == TARGET_WAITKIND_IGNORE)
7692 /* Nothing interesting happened. If we're doing a non-blocking
7693 poll, we're done. Otherwise, go back to waiting. */
7694 if (options & TARGET_WNOHANG)
7695 return minus_one_ptid;
7699 else if (status->kind != TARGET_WAITKIND_EXITED
7700 && status->kind != TARGET_WAITKIND_SIGNALLED)
7702 if (!ptid_equal (event_ptid, null_ptid))
7703 record_currthread (rs, event_ptid);
7705 event_ptid = inferior_ptid;
7708 /* A process exit. Invalidate our notion of current thread. */
7709 record_currthread (rs, minus_one_ptid);
7714 /* Wait until the remote machine stops, then return, storing status in
7715 STATUS just as `wait' would. */
7718 remote_target::wait (ptid_t ptid, struct target_waitstatus *status, int options)
7722 if (target_is_non_stop_p ())
7723 event_ptid = remote_wait_ns (ptid, status, options);
7725 event_ptid = remote_wait_as (ptid, status, options);
7727 if (target_is_async_p ())
7729 /* If there are are events left in the queue tell the event loop
7731 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
7732 mark_async_event_handler (remote_async_inferior_event_token);
7738 /* Fetch a single register using a 'p' packet. */
7741 fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
7743 struct gdbarch *gdbarch = regcache->arch ();
7744 struct remote_state *rs = get_remote_state ();
7746 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
7749 if (packet_support (PACKET_p) == PACKET_DISABLE)
7752 if (reg->pnum == -1)
7757 p += hexnumstr (p, reg->pnum);
7760 getpkt (&rs->buf, &rs->buf_size, 0);
7764 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
7768 case PACKET_UNKNOWN:
7771 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
7772 gdbarch_register_name (regcache->arch (),
7777 /* If this register is unfetchable, tell the regcache. */
7780 regcache_raw_supply (regcache, reg->regnum, NULL);
7784 /* Otherwise, parse and supply the value. */
7790 error (_("fetch_register_using_p: early buf termination"));
7792 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
7795 regcache_raw_supply (regcache, reg->regnum, regp);
7799 /* Fetch the registers included in the target's 'g' packet. */
7802 send_g_packet (void)
7804 struct remote_state *rs = get_remote_state ();
7807 xsnprintf (rs->buf, get_remote_packet_size (), "g");
7809 getpkt (&rs->buf, &rs->buf_size, 0);
7810 if (packet_check_result (rs->buf) == PACKET_ERROR)
7811 error (_("Could not read registers; remote failure reply '%s'"),
7814 /* We can get out of synch in various cases. If the first character
7815 in the buffer is not a hex character, assume that has happened
7816 and try to fetch another packet to read. */
7817 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
7818 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
7819 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
7820 && rs->buf[0] != 'x') /* New: unavailable register value. */
7823 fprintf_unfiltered (gdb_stdlog,
7824 "Bad register packet; fetching a new packet\n");
7825 getpkt (&rs->buf, &rs->buf_size, 0);
7828 buf_len = strlen (rs->buf);
7830 /* Sanity check the received packet. */
7831 if (buf_len % 2 != 0)
7832 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
7838 process_g_packet (struct regcache *regcache)
7840 struct gdbarch *gdbarch = regcache->arch ();
7841 struct remote_state *rs = get_remote_state ();
7842 remote_arch_state *rsa = get_remote_arch_state (gdbarch);
7847 buf_len = strlen (rs->buf);
7849 /* Further sanity checks, with knowledge of the architecture. */
7850 if (buf_len > 2 * rsa->sizeof_g_packet)
7851 error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
7852 "bytes): %s"), rsa->sizeof_g_packet, buf_len / 2, rs->buf);
7854 /* Save the size of the packet sent to us by the target. It is used
7855 as a heuristic when determining the max size of packets that the
7856 target can safely receive. */
7857 if (rsa->actual_register_packet_size == 0)
7858 rsa->actual_register_packet_size = buf_len;
7860 /* If this is smaller than we guessed the 'g' packet would be,
7861 update our records. A 'g' reply that doesn't include a register's
7862 value implies either that the register is not available, or that
7863 the 'p' packet must be used. */
7864 if (buf_len < 2 * rsa->sizeof_g_packet)
7866 long sizeof_g_packet = buf_len / 2;
7868 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7870 long offset = rsa->regs[i].offset;
7871 long reg_size = register_size (gdbarch, i);
7873 if (rsa->regs[i].pnum == -1)
7876 if (offset >= sizeof_g_packet)
7877 rsa->regs[i].in_g_packet = 0;
7878 else if (offset + reg_size > sizeof_g_packet)
7879 error (_("Truncated register %d in remote 'g' packet"), i);
7881 rsa->regs[i].in_g_packet = 1;
7884 /* Looks valid enough, we can assume this is the correct length
7885 for a 'g' packet. It's important not to adjust
7886 rsa->sizeof_g_packet if we have truncated registers otherwise
7887 this "if" won't be run the next time the method is called
7888 with a packet of the same size and one of the internal errors
7889 below will trigger instead. */
7890 rsa->sizeof_g_packet = sizeof_g_packet;
7893 regs = (char *) alloca (rsa->sizeof_g_packet);
7895 /* Unimplemented registers read as all bits zero. */
7896 memset (regs, 0, rsa->sizeof_g_packet);
7898 /* Reply describes registers byte by byte, each byte encoded as two
7899 hex characters. Suck them all up, then supply them to the
7900 register cacheing/storage mechanism. */
7903 for (i = 0; i < rsa->sizeof_g_packet; i++)
7905 if (p[0] == 0 || p[1] == 0)
7906 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
7907 internal_error (__FILE__, __LINE__,
7908 _("unexpected end of 'g' packet reply"));
7910 if (p[0] == 'x' && p[1] == 'x')
7911 regs[i] = 0; /* 'x' */
7913 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
7917 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7919 struct packet_reg *r = &rsa->regs[i];
7920 long reg_size = register_size (gdbarch, i);
7924 if ((r->offset + reg_size) * 2 > strlen (rs->buf))
7925 /* This shouldn't happen - we adjusted in_g_packet above. */
7926 internal_error (__FILE__, __LINE__,
7927 _("unexpected end of 'g' packet reply"));
7928 else if (rs->buf[r->offset * 2] == 'x')
7930 gdb_assert (r->offset * 2 < strlen (rs->buf));
7931 /* The register isn't available, mark it as such (at
7932 the same time setting the value to zero). */
7933 regcache_raw_supply (regcache, r->regnum, NULL);
7936 regcache_raw_supply (regcache, r->regnum,
7943 fetch_registers_using_g (struct regcache *regcache)
7946 process_g_packet (regcache);
7949 /* Make the remote selected traceframe match GDB's selected
7953 set_remote_traceframe (void)
7956 struct remote_state *rs = get_remote_state ();
7958 if (rs->remote_traceframe_number == get_traceframe_number ())
7961 /* Avoid recursion, remote_trace_find calls us again. */
7962 rs->remote_traceframe_number = get_traceframe_number ();
7964 newnum = target_trace_find (tfind_number,
7965 get_traceframe_number (), 0, 0, NULL);
7967 /* Should not happen. If it does, all bets are off. */
7968 if (newnum != get_traceframe_number ())
7969 warning (_("could not set remote traceframe"));
7973 remote_target::fetch_registers (struct regcache *regcache, int regnum)
7975 struct gdbarch *gdbarch = regcache->arch ();
7976 remote_arch_state *rsa = get_remote_arch_state (gdbarch);
7979 set_remote_traceframe ();
7980 set_general_thread (regcache_get_ptid (regcache));
7984 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
7986 gdb_assert (reg != NULL);
7988 /* If this register might be in the 'g' packet, try that first -
7989 we are likely to read more than one register. If this is the
7990 first 'g' packet, we might be overly optimistic about its
7991 contents, so fall back to 'p'. */
7992 if (reg->in_g_packet)
7994 fetch_registers_using_g (regcache);
7995 if (reg->in_g_packet)
7999 if (fetch_register_using_p (regcache, reg))
8002 /* This register is not available. */
8003 regcache_raw_supply (regcache, reg->regnum, NULL);
8008 fetch_registers_using_g (regcache);
8010 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8011 if (!rsa->regs[i].in_g_packet)
8012 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
8014 /* This register is not available. */
8015 regcache_raw_supply (regcache, i, NULL);
8019 /* Prepare to store registers. Since we may send them all (using a
8020 'G' request), we have to read out the ones we don't want to change
8024 remote_target::prepare_to_store (struct regcache *regcache)
8026 remote_arch_state *rsa = get_remote_arch_state (regcache->arch ());
8029 /* Make sure the entire registers array is valid. */
8030 switch (packet_support (PACKET_P))
8032 case PACKET_DISABLE:
8033 case PACKET_SUPPORT_UNKNOWN:
8034 /* Make sure all the necessary registers are cached. */
8035 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8036 if (rsa->regs[i].in_g_packet)
8037 regcache_raw_update (regcache, rsa->regs[i].regnum);
8044 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
8045 packet was not recognized. */
8048 store_register_using_P (const struct regcache *regcache,
8049 struct packet_reg *reg)
8051 struct gdbarch *gdbarch = regcache->arch ();
8052 struct remote_state *rs = get_remote_state ();
8053 /* Try storing a single register. */
8054 char *buf = rs->buf;
8055 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
8058 if (packet_support (PACKET_P) == PACKET_DISABLE)
8061 if (reg->pnum == -1)
8064 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
8065 p = buf + strlen (buf);
8066 regcache_raw_collect (regcache, reg->regnum, regp);
8067 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
8069 getpkt (&rs->buf, &rs->buf_size, 0);
8071 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
8076 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
8077 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
8078 case PACKET_UNKNOWN:
8081 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8085 /* Store register REGNUM, or all registers if REGNUM == -1, from the
8086 contents of the register cache buffer. FIXME: ignores errors. */
8089 store_registers_using_G (const struct regcache *regcache)
8091 struct remote_state *rs = get_remote_state ();
8092 remote_arch_state *rsa = get_remote_arch_state (regcache->arch ());
8096 /* Extract all the registers in the regcache copying them into a
8101 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
8102 memset (regs, 0, rsa->sizeof_g_packet);
8103 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8105 struct packet_reg *r = &rsa->regs[i];
8108 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
8112 /* Command describes registers byte by byte,
8113 each byte encoded as two hex characters. */
8116 bin2hex (regs, p, rsa->sizeof_g_packet);
8118 getpkt (&rs->buf, &rs->buf_size, 0);
8119 if (packet_check_result (rs->buf) == PACKET_ERROR)
8120 error (_("Could not write registers; remote failure reply '%s'"),
8124 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
8125 of the register cache buffer. FIXME: ignores errors. */
8128 remote_target::store_registers (struct regcache *regcache, int regnum)
8130 struct gdbarch *gdbarch = regcache->arch ();
8131 remote_arch_state *rsa = get_remote_arch_state (gdbarch);
8134 set_remote_traceframe ();
8135 set_general_thread (regcache_get_ptid (regcache));
8139 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8141 gdb_assert (reg != NULL);
8143 /* Always prefer to store registers using the 'P' packet if
8144 possible; we often change only a small number of registers.
8145 Sometimes we change a larger number; we'd need help from a
8146 higher layer to know to use 'G'. */
8147 if (store_register_using_P (regcache, reg))
8150 /* For now, don't complain if we have no way to write the
8151 register. GDB loses track of unavailable registers too
8152 easily. Some day, this may be an error. We don't have
8153 any way to read the register, either... */
8154 if (!reg->in_g_packet)
8157 store_registers_using_G (regcache);
8161 store_registers_using_G (regcache);
8163 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8164 if (!rsa->regs[i].in_g_packet)
8165 if (!store_register_using_P (regcache, &rsa->regs[i]))
8166 /* See above for why we do not issue an error here. */
8171 /* Return the number of hex digits in num. */
8174 hexnumlen (ULONGEST num)
8178 for (i = 0; num != 0; i++)
8181 return std::max (i, 1);
8184 /* Set BUF to the minimum number of hex digits representing NUM. */
8187 hexnumstr (char *buf, ULONGEST num)
8189 int len = hexnumlen (num);
8191 return hexnumnstr (buf, num, len);
8195 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
8198 hexnumnstr (char *buf, ULONGEST num, int width)
8204 for (i = width - 1; i >= 0; i--)
8206 buf[i] = "0123456789abcdef"[(num & 0xf)];
8213 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
8216 remote_address_masked (CORE_ADDR addr)
8218 unsigned int address_size = remote_address_size;
8220 /* If "remoteaddresssize" was not set, default to target address size. */
8222 address_size = gdbarch_addr_bit (target_gdbarch ());
8224 if (address_size > 0
8225 && address_size < (sizeof (ULONGEST) * 8))
8227 /* Only create a mask when that mask can safely be constructed
8228 in a ULONGEST variable. */
8231 mask = (mask << address_size) - 1;
8237 /* Determine whether the remote target supports binary downloading.
8238 This is accomplished by sending a no-op memory write of zero length
8239 to the target at the specified address. It does not suffice to send
8240 the whole packet, since many stubs strip the eighth bit and
8241 subsequently compute a wrong checksum, which causes real havoc with
8244 NOTE: This can still lose if the serial line is not eight-bit
8245 clean. In cases like this, the user should clear "remote
8249 check_binary_download (CORE_ADDR addr)
8251 struct remote_state *rs = get_remote_state ();
8253 switch (packet_support (PACKET_X))
8255 case PACKET_DISABLE:
8259 case PACKET_SUPPORT_UNKNOWN:
8265 p += hexnumstr (p, (ULONGEST) addr);
8267 p += hexnumstr (p, (ULONGEST) 0);
8271 putpkt_binary (rs->buf, (int) (p - rs->buf));
8272 getpkt (&rs->buf, &rs->buf_size, 0);
8274 if (rs->buf[0] == '\0')
8277 fprintf_unfiltered (gdb_stdlog,
8278 "binary downloading NOT "
8279 "supported by target\n");
8280 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
8285 fprintf_unfiltered (gdb_stdlog,
8286 "binary downloading supported by target\n");
8287 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
8294 /* Helper function to resize the payload in order to try to get a good
8295 alignment. We try to write an amount of data such that the next write will
8296 start on an address aligned on REMOTE_ALIGN_WRITES. */
8299 align_for_efficient_write (int todo, CORE_ADDR memaddr)
8301 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
8304 /* Write memory data directly to the remote machine.
8305 This does not inform the data cache; the data cache uses this.
8306 HEADER is the starting part of the packet.
8307 MEMADDR is the address in the remote memory space.
8308 MYADDR is the address of the buffer in our space.
8309 LEN_UNITS is the number of addressable units to write.
8310 UNIT_SIZE is the length in bytes of an addressable unit.
8311 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
8312 should send data as binary ('X'), or hex-encoded ('M').
8314 The function creates packet of the form
8315 <HEADER><ADDRESS>,<LENGTH>:<DATA>
8317 where encoding of <DATA> is terminated by PACKET_FORMAT.
8319 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
8322 Return the transferred status, error or OK (an
8323 'enum target_xfer_status' value). Save the number of addressable units
8324 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
8326 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
8327 exchange between gdb and the stub could look like (?? in place of the
8333 -> $M1000,3:eeeeffffeeee#??
8337 <- eeeeffffeeeedddd */
8339 static enum target_xfer_status
8340 remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
8341 const gdb_byte *myaddr, ULONGEST len_units,
8342 int unit_size, ULONGEST *xfered_len_units,
8343 char packet_format, int use_length)
8345 struct remote_state *rs = get_remote_state ();
8351 int payload_capacity_bytes;
8352 int payload_length_bytes;
8354 if (packet_format != 'X' && packet_format != 'M')
8355 internal_error (__FILE__, __LINE__,
8356 _("remote_write_bytes_aux: bad packet format"));
8359 return TARGET_XFER_EOF;
8361 payload_capacity_bytes = get_memory_write_packet_size ();
8363 /* The packet buffer will be large enough for the payload;
8364 get_memory_packet_size ensures this. */
8367 /* Compute the size of the actual payload by subtracting out the
8368 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
8370 payload_capacity_bytes -= strlen ("$,:#NN");
8372 /* The comma won't be used. */
8373 payload_capacity_bytes += 1;
8374 payload_capacity_bytes -= strlen (header);
8375 payload_capacity_bytes -= hexnumlen (memaddr);
8377 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
8379 strcat (rs->buf, header);
8380 p = rs->buf + strlen (header);
8382 /* Compute a best guess of the number of bytes actually transfered. */
8383 if (packet_format == 'X')
8385 /* Best guess at number of bytes that will fit. */
8386 todo_units = std::min (len_units,
8387 (ULONGEST) payload_capacity_bytes / unit_size);
8389 payload_capacity_bytes -= hexnumlen (todo_units);
8390 todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
8394 /* Number of bytes that will fit. */
8396 = std::min (len_units,
8397 (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
8399 payload_capacity_bytes -= hexnumlen (todo_units);
8400 todo_units = std::min (todo_units,
8401 (payload_capacity_bytes / unit_size) / 2);
8404 if (todo_units <= 0)
8405 internal_error (__FILE__, __LINE__,
8406 _("minimum packet size too small to write data"));
8408 /* If we already need another packet, then try to align the end
8409 of this packet to a useful boundary. */
8410 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
8411 todo_units = align_for_efficient_write (todo_units, memaddr);
8413 /* Append "<memaddr>". */
8414 memaddr = remote_address_masked (memaddr);
8415 p += hexnumstr (p, (ULONGEST) memaddr);
8422 /* Append the length and retain its location and size. It may need to be
8423 adjusted once the packet body has been created. */
8425 plenlen = hexnumstr (p, (ULONGEST) todo_units);
8433 /* Append the packet body. */
8434 if (packet_format == 'X')
8436 /* Binary mode. Send target system values byte by byte, in
8437 increasing byte addresses. Only escape certain critical
8439 payload_length_bytes =
8440 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
8441 &units_written, payload_capacity_bytes);
8443 /* If not all TODO units fit, then we'll need another packet. Make
8444 a second try to keep the end of the packet aligned. Don't do
8445 this if the packet is tiny. */
8446 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
8450 new_todo_units = align_for_efficient_write (units_written, memaddr);
8452 if (new_todo_units != units_written)
8453 payload_length_bytes =
8454 remote_escape_output (myaddr, new_todo_units, unit_size,
8455 (gdb_byte *) p, &units_written,
8456 payload_capacity_bytes);
8459 p += payload_length_bytes;
8460 if (use_length && units_written < todo_units)
8462 /* Escape chars have filled up the buffer prematurely,
8463 and we have actually sent fewer units than planned.
8464 Fix-up the length field of the packet. Use the same
8465 number of characters as before. */
8466 plen += hexnumnstr (plen, (ULONGEST) units_written,
8468 *plen = ':'; /* overwrite \0 from hexnumnstr() */
8473 /* Normal mode: Send target system values byte by byte, in
8474 increasing byte addresses. Each byte is encoded as a two hex
8476 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
8477 units_written = todo_units;
8480 putpkt_binary (rs->buf, (int) (p - rs->buf));
8481 getpkt (&rs->buf, &rs->buf_size, 0);
8483 if (rs->buf[0] == 'E')
8484 return TARGET_XFER_E_IO;
8486 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
8487 send fewer units than we'd planned. */
8488 *xfered_len_units = (ULONGEST) units_written;
8489 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
8492 /* Write memory data directly to the remote machine.
8493 This does not inform the data cache; the data cache uses this.
8494 MEMADDR is the address in the remote memory space.
8495 MYADDR is the address of the buffer in our space.
8496 LEN is the number of bytes.
8498 Return the transferred status, error or OK (an
8499 'enum target_xfer_status' value). Save the number of bytes
8500 transferred in *XFERED_LEN. Only transfer a single packet. */
8502 static enum target_xfer_status
8503 remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
8504 int unit_size, ULONGEST *xfered_len)
8506 const char *packet_format = NULL;
8508 /* Check whether the target supports binary download. */
8509 check_binary_download (memaddr);
8511 switch (packet_support (PACKET_X))
8514 packet_format = "X";
8516 case PACKET_DISABLE:
8517 packet_format = "M";
8519 case PACKET_SUPPORT_UNKNOWN:
8520 internal_error (__FILE__, __LINE__,
8521 _("remote_write_bytes: bad internal state"));
8523 internal_error (__FILE__, __LINE__, _("bad switch"));
8526 return remote_write_bytes_aux (packet_format,
8527 memaddr, myaddr, len, unit_size, xfered_len,
8528 packet_format[0], 1);
8531 /* Read memory data directly from the remote machine.
8532 This does not use the data cache; the data cache uses this.
8533 MEMADDR is the address in the remote memory space.
8534 MYADDR is the address of the buffer in our space.
8535 LEN_UNITS is the number of addressable memory units to read..
8536 UNIT_SIZE is the length in bytes of an addressable unit.
8538 Return the transferred status, error or OK (an
8539 'enum target_xfer_status' value). Save the number of bytes
8540 transferred in *XFERED_LEN_UNITS.
8542 See the comment of remote_write_bytes_aux for an example of
8543 memory read/write exchange between gdb and the stub. */
8545 static enum target_xfer_status
8546 remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len_units,
8547 int unit_size, ULONGEST *xfered_len_units)
8549 struct remote_state *rs = get_remote_state ();
8550 int buf_size_bytes; /* Max size of packet output buffer. */
8555 buf_size_bytes = get_memory_read_packet_size ();
8556 /* The packet buffer will be large enough for the payload;
8557 get_memory_packet_size ensures this. */
8559 /* Number of units that will fit. */
8560 todo_units = std::min (len_units,
8561 (ULONGEST) (buf_size_bytes / unit_size) / 2);
8563 /* Construct "m"<memaddr>","<len>". */
8564 memaddr = remote_address_masked (memaddr);
8567 p += hexnumstr (p, (ULONGEST) memaddr);
8569 p += hexnumstr (p, (ULONGEST) todo_units);
8572 getpkt (&rs->buf, &rs->buf_size, 0);
8573 if (rs->buf[0] == 'E'
8574 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
8575 && rs->buf[3] == '\0')
8576 return TARGET_XFER_E_IO;
8577 /* Reply describes memory byte by byte, each byte encoded as two hex
8580 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
8581 /* Return what we have. Let higher layers handle partial reads. */
8582 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
8583 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
8586 /* Using the set of read-only target sections of remote, read live
8589 For interface/parameters/return description see target.h,
8592 static enum target_xfer_status
8593 remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
8594 ULONGEST memaddr, ULONGEST len,
8595 int unit_size, ULONGEST *xfered_len)
8597 struct target_section *secp;
8598 struct target_section_table *table;
8600 secp = target_section_by_addr (ops, memaddr);
8602 && (bfd_get_section_flags (secp->the_bfd_section->owner,
8603 secp->the_bfd_section)
8606 struct target_section *p;
8607 ULONGEST memend = memaddr + len;
8609 table = target_get_section_table (ops);
8611 for (p = table->sections; p < table->sections_end; p++)
8613 if (memaddr >= p->addr)
8615 if (memend <= p->endaddr)
8617 /* Entire transfer is within this section. */
8618 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
8621 else if (memaddr >= p->endaddr)
8623 /* This section ends before the transfer starts. */
8628 /* This section overlaps the transfer. Just do half. */
8629 len = p->endaddr - memaddr;
8630 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
8637 return TARGET_XFER_EOF;
8640 /* Similar to remote_read_bytes_1, but it reads from the remote stub
8641 first if the requested memory is unavailable in traceframe.
8642 Otherwise, fall back to remote_read_bytes_1. */
8644 static enum target_xfer_status
8645 remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
8646 gdb_byte *myaddr, ULONGEST len, int unit_size,
8647 ULONGEST *xfered_len)
8650 return TARGET_XFER_EOF;
8652 if (get_traceframe_number () != -1)
8654 std::vector<mem_range> available;
8656 /* If we fail to get the set of available memory, then the
8657 target does not support querying traceframe info, and so we
8658 attempt reading from the traceframe anyway (assuming the
8659 target implements the old QTro packet then). */
8660 if (traceframe_available_memory (&available, memaddr, len))
8662 if (available.empty () || available[0].start != memaddr)
8664 enum target_xfer_status res;
8666 /* Don't read into the traceframe's available
8668 if (!available.empty ())
8670 LONGEST oldlen = len;
8672 len = available[0].start - memaddr;
8673 gdb_assert (len <= oldlen);
8676 /* This goes through the topmost target again. */
8677 res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
8678 len, unit_size, xfered_len);
8679 if (res == TARGET_XFER_OK)
8680 return TARGET_XFER_OK;
8683 /* No use trying further, we know some memory starting
8684 at MEMADDR isn't available. */
8686 return (*xfered_len != 0) ?
8687 TARGET_XFER_UNAVAILABLE : TARGET_XFER_EOF;
8691 /* Don't try to read more than how much is available, in
8692 case the target implements the deprecated QTro packet to
8693 cater for older GDBs (the target's knowledge of read-only
8694 sections may be outdated by now). */
8695 len = available[0].length;
8699 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
8704 /* Sends a packet with content determined by the printf format string
8705 FORMAT and the remaining arguments, then gets the reply. Returns
8706 whether the packet was a success, a failure, or unknown. */
8708 static enum packet_result remote_send_printf (const char *format, ...)
8709 ATTRIBUTE_PRINTF (1, 2);
8711 static enum packet_result
8712 remote_send_printf (const char *format, ...)
8714 struct remote_state *rs = get_remote_state ();
8715 int max_size = get_remote_packet_size ();
8718 va_start (ap, format);
8721 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
8722 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
8724 if (putpkt (rs->buf) < 0)
8725 error (_("Communication problem with target."));
8728 getpkt (&rs->buf, &rs->buf_size, 0);
8730 return packet_check_result (rs->buf);
8733 /* Flash writing can take quite some time. We'll set
8734 effectively infinite timeout for flash operations.
8735 In future, we'll need to decide on a better approach. */
8736 static const int remote_flash_timeout = 1000;
8739 remote_target::flash_erase (ULONGEST address, LONGEST length)
8741 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
8742 enum packet_result ret;
8743 scoped_restore restore_timeout
8744 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8746 ret = remote_send_printf ("vFlashErase:%s,%s",
8747 phex (address, addr_size),
8751 case PACKET_UNKNOWN:
8752 error (_("Remote target does not support flash erase"));
8754 error (_("Error erasing flash with vFlashErase packet"));
8760 static enum target_xfer_status
8761 remote_flash_write (struct target_ops *ops, ULONGEST address,
8762 ULONGEST length, ULONGEST *xfered_len,
8763 const gdb_byte *data)
8765 scoped_restore restore_timeout
8766 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8767 return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
8772 remote_target::flash_done ()
8776 scoped_restore restore_timeout
8777 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8779 ret = remote_send_printf ("vFlashDone");
8783 case PACKET_UNKNOWN:
8784 error (_("Remote target does not support vFlashDone"));
8786 error (_("Error finishing flash operation"));
8793 remote_target::files_info ()
8795 puts_filtered ("Debugging a target over a serial line.\n");
8798 /* Stuff for dealing with the packets which are part of this protocol.
8799 See comment at top of file for details. */
8801 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
8802 error to higher layers. Called when a serial error is detected.
8803 The exception message is STRING, followed by a colon and a blank,
8804 the system error message for errno at function entry and final dot
8805 for output compatibility with throw_perror_with_name. */
8808 unpush_and_perror (const char *string)
8810 int saved_errno = errno;
8812 remote_unpush_target ();
8813 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
8814 safe_strerror (saved_errno));
8817 /* Read a single character from the remote end. The current quit
8818 handler is overridden to avoid quitting in the middle of packet
8819 sequence, as that would break communication with the remote server.
8820 See remote_serial_quit_handler for more detail. */
8823 readchar (int timeout)
8826 struct remote_state *rs = get_remote_state ();
8829 scoped_restore restore_quit
8830 = make_scoped_restore (&quit_handler, remote_serial_quit_handler);
8832 rs->got_ctrlc_during_io = 0;
8834 ch = serial_readchar (rs->remote_desc, timeout);
8836 if (rs->got_ctrlc_during_io)
8843 switch ((enum serial_rc) ch)
8846 remote_unpush_target ();
8847 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
8850 unpush_and_perror (_("Remote communication error. "
8851 "Target disconnected."));
8853 case SERIAL_TIMEOUT:
8859 /* Wrapper for serial_write that closes the target and throws if
8860 writing fails. The current quit handler is overridden to avoid
8861 quitting in the middle of packet sequence, as that would break
8862 communication with the remote server. See
8863 remote_serial_quit_handler for more detail. */
8866 remote_serial_write (const char *str, int len)
8868 struct remote_state *rs = get_remote_state ();
8870 scoped_restore restore_quit
8871 = make_scoped_restore (&quit_handler, remote_serial_quit_handler);
8873 rs->got_ctrlc_during_io = 0;
8875 if (serial_write (rs->remote_desc, str, len))
8877 unpush_and_perror (_("Remote communication error. "
8878 "Target disconnected."));
8881 if (rs->got_ctrlc_during_io)
8885 /* Return a string representing an escaped version of BUF, of len N.
8886 E.g. \n is converted to \\n, \t to \\t, etc. */
8889 escape_buffer (const char *buf, int n)
8893 stb.putstrn (buf, n, '\\');
8894 return std::move (stb.string ());
8897 /* Display a null-terminated packet on stdout, for debugging, using C
8901 print_packet (const char *buf)
8903 puts_filtered ("\"");
8904 fputstr_filtered (buf, '"', gdb_stdout);
8905 puts_filtered ("\"");
8909 putpkt (const char *buf)
8911 return putpkt_binary (buf, strlen (buf));
8914 /* Send a packet to the remote machine, with error checking. The data
8915 of the packet is in BUF. The string in BUF can be at most
8916 get_remote_packet_size () - 5 to account for the $, # and checksum,
8917 and for a possible /0 if we are debugging (remote_debug) and want
8918 to print the sent packet as a string. */
8921 putpkt_binary (const char *buf, int cnt)
8923 struct remote_state *rs = get_remote_state ();
8925 unsigned char csum = 0;
8926 gdb::def_vector<char> data (cnt + 6);
8927 char *buf2 = data.data ();
8933 /* Catch cases like trying to read memory or listing threads while
8934 we're waiting for a stop reply. The remote server wouldn't be
8935 ready to handle this request, so we'd hang and timeout. We don't
8936 have to worry about this in synchronous mode, because in that
8937 case it's not possible to issue a command while the target is
8938 running. This is not a problem in non-stop mode, because in that
8939 case, the stub is always ready to process serial input. */
8940 if (!target_is_non_stop_p ()
8941 && target_is_async_p ()
8942 && rs->waiting_for_stop_reply)
8944 error (_("Cannot execute this command while the target is running.\n"
8945 "Use the \"interrupt\" command to stop the target\n"
8946 "and then try again."));
8949 /* We're sending out a new packet. Make sure we don't look at a
8950 stale cached response. */
8951 rs->cached_wait_status = 0;
8953 /* Copy the packet into buffer BUF2, encapsulating it
8954 and giving it a checksum. */
8959 for (i = 0; i < cnt; i++)
8965 *p++ = tohex ((csum >> 4) & 0xf);
8966 *p++ = tohex (csum & 0xf);
8968 /* Send it over and over until we get a positive ack. */
8972 int started_error_output = 0;
8978 int len = (int) (p - buf2);
8981 = escape_buffer (buf2, std::min (len, REMOTE_DEBUG_MAX_CHAR));
8983 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s", str.c_str ());
8985 if (len > REMOTE_DEBUG_MAX_CHAR)
8986 fprintf_unfiltered (gdb_stdlog, "[%d bytes omitted]",
8987 len - REMOTE_DEBUG_MAX_CHAR);
8989 fprintf_unfiltered (gdb_stdlog, "...");
8991 gdb_flush (gdb_stdlog);
8993 remote_serial_write (buf2, p - buf2);
8995 /* If this is a no acks version of the remote protocol, send the
8996 packet and move on. */
9000 /* Read until either a timeout occurs (-2) or '+' is read.
9001 Handle any notification that arrives in the mean time. */
9004 ch = readchar (remote_timeout);
9012 case SERIAL_TIMEOUT:
9015 if (started_error_output)
9017 putchar_unfiltered ('\n');
9018 started_error_output = 0;
9027 fprintf_unfiltered (gdb_stdlog, "Ack\n");
9031 fprintf_unfiltered (gdb_stdlog, "Nak\n");
9033 case SERIAL_TIMEOUT:
9037 break; /* Retransmit buffer. */
9041 fprintf_unfiltered (gdb_stdlog,
9042 "Packet instead of Ack, ignoring it\n");
9043 /* It's probably an old response sent because an ACK
9044 was lost. Gobble up the packet and ack it so it
9045 doesn't get retransmitted when we resend this
9048 remote_serial_write ("+", 1);
9049 continue; /* Now, go look for +. */
9056 /* If we got a notification, handle it, and go back to looking
9058 /* We've found the start of a notification. Now
9059 collect the data. */
9060 val = read_frame (&rs->buf, &rs->buf_size);
9065 std::string str = escape_buffer (rs->buf, val);
9067 fprintf_unfiltered (gdb_stdlog,
9068 " Notification received: %s\n",
9071 handle_notification (rs->notif_state, rs->buf);
9072 /* We're in sync now, rewait for the ack. */
9079 if (!started_error_output)
9081 started_error_output = 1;
9082 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
9084 fputc_unfiltered (ch & 0177, gdb_stdlog);
9085 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
9094 if (!started_error_output)
9096 started_error_output = 1;
9097 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
9099 fputc_unfiltered (ch & 0177, gdb_stdlog);
9103 break; /* Here to retransmit. */
9107 /* This is wrong. If doing a long backtrace, the user should be
9108 able to get out next time we call QUIT, without anything as
9109 violent as interrupt_query. If we want to provide a way out of
9110 here without getting to the next QUIT, it should be based on
9111 hitting ^C twice as in remote_wait. */
9123 /* Come here after finding the start of a frame when we expected an
9124 ack. Do our best to discard the rest of this packet. */
9133 c = readchar (remote_timeout);
9136 case SERIAL_TIMEOUT:
9137 /* Nothing we can do. */
9140 /* Discard the two bytes of checksum and stop. */
9141 c = readchar (remote_timeout);
9143 c = readchar (remote_timeout);
9146 case '*': /* Run length encoding. */
9147 /* Discard the repeat count. */
9148 c = readchar (remote_timeout);
9153 /* A regular character. */
9159 /* Come here after finding the start of the frame. Collect the rest
9160 into *BUF, verifying the checksum, length, and handling run-length
9161 compression. NUL terminate the buffer. If there is not enough room,
9162 expand *BUF using xrealloc.
9164 Returns -1 on error, number of characters in buffer (ignoring the
9165 trailing NULL) on success. (could be extended to return one of the
9166 SERIAL status indications). */
9169 read_frame (char **buf_p,
9176 struct remote_state *rs = get_remote_state ();
9183 c = readchar (remote_timeout);
9186 case SERIAL_TIMEOUT:
9188 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
9192 fputs_filtered ("Saw new packet start in middle of old one\n",
9194 return -1; /* Start a new packet, count retries. */
9197 unsigned char pktcsum;
9203 check_0 = readchar (remote_timeout);
9205 check_1 = readchar (remote_timeout);
9207 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
9210 fputs_filtered ("Timeout in checksum, retrying\n",
9214 else if (check_0 < 0 || check_1 < 0)
9217 fputs_filtered ("Communication error in checksum\n",
9222 /* Don't recompute the checksum; with no ack packets we
9223 don't have any way to indicate a packet retransmission
9228 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
9229 if (csum == pktcsum)
9234 std::string str = escape_buffer (buf, bc);
9236 fprintf_unfiltered (gdb_stdlog,
9237 "Bad checksum, sentsum=0x%x, "
9238 "csum=0x%x, buf=%s\n",
9239 pktcsum, csum, str.c_str ());
9241 /* Number of characters in buffer ignoring trailing
9245 case '*': /* Run length encoding. */
9250 c = readchar (remote_timeout);
9252 repeat = c - ' ' + 3; /* Compute repeat count. */
9254 /* The character before ``*'' is repeated. */
9256 if (repeat > 0 && repeat <= 255 && bc > 0)
9258 if (bc + repeat - 1 >= *sizeof_buf - 1)
9260 /* Make some more room in the buffer. */
9261 *sizeof_buf += repeat;
9262 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
9266 memset (&buf[bc], buf[bc - 1], repeat);
9272 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
9276 if (bc >= *sizeof_buf - 1)
9278 /* Make some more room in the buffer. */
9280 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
9291 /* Read a packet from the remote machine, with error checking, and
9292 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
9293 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
9294 rather than timing out; this is used (in synchronous mode) to wait
9295 for a target that is is executing user code to stop. */
9296 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
9297 don't have to change all the calls to getpkt to deal with the
9298 return value, because at the moment I don't know what the right
9299 thing to do it for those. */
9305 getpkt_sane (buf, sizeof_buf, forever);
9309 /* Read a packet from the remote machine, with error checking, and
9310 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
9311 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
9312 rather than timing out; this is used (in synchronous mode) to wait
9313 for a target that is is executing user code to stop. If FOREVER ==
9314 0, this function is allowed to time out gracefully and return an
9315 indication of this to the caller. Otherwise return the number of
9316 bytes read. If EXPECTING_NOTIF, consider receiving a notification
9317 enough reason to return to the caller. *IS_NOTIF is an output
9318 boolean that indicates whether *BUF holds a notification or not
9319 (a regular packet). */
9322 getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
9323 int expecting_notif, int *is_notif)
9325 struct remote_state *rs = get_remote_state ();
9331 /* We're reading a new response. Make sure we don't look at a
9332 previously cached response. */
9333 rs->cached_wait_status = 0;
9335 strcpy (*buf, "timeout");
9338 timeout = watchdog > 0 ? watchdog : -1;
9339 else if (expecting_notif)
9340 timeout = 0; /* There should already be a char in the buffer. If
9343 timeout = remote_timeout;
9347 /* Process any number of notifications, and then return when
9351 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
9353 for (tries = 1; tries <= MAX_TRIES; tries++)
9355 /* This can loop forever if the remote side sends us
9356 characters continuously, but if it pauses, we'll get
9357 SERIAL_TIMEOUT from readchar because of timeout. Then
9358 we'll count that as a retry.
9360 Note that even when forever is set, we will only wait
9361 forever prior to the start of a packet. After that, we
9362 expect characters to arrive at a brisk pace. They should
9363 show up within remote_timeout intervals. */
9365 c = readchar (timeout);
9366 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
9368 if (c == SERIAL_TIMEOUT)
9370 if (expecting_notif)
9371 return -1; /* Don't complain, it's normal to not get
9372 anything in this case. */
9374 if (forever) /* Watchdog went off? Kill the target. */
9376 remote_unpush_target ();
9377 throw_error (TARGET_CLOSE_ERROR,
9378 _("Watchdog timeout has expired. "
9379 "Target detached."));
9382 fputs_filtered ("Timed out.\n", gdb_stdlog);
9386 /* We've found the start of a packet or notification.
9387 Now collect the data. */
9388 val = read_frame (buf, sizeof_buf);
9393 remote_serial_write ("-", 1);
9396 if (tries > MAX_TRIES)
9398 /* We have tried hard enough, and just can't receive the
9399 packet/notification. Give up. */
9400 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
9402 /* Skip the ack char if we're in no-ack mode. */
9403 if (!rs->noack_mode)
9404 remote_serial_write ("+", 1);
9408 /* If we got an ordinary packet, return that to our caller. */
9414 = escape_buffer (*buf,
9415 std::min (val, REMOTE_DEBUG_MAX_CHAR));
9417 fprintf_unfiltered (gdb_stdlog, "Packet received: %s",
9420 if (val > REMOTE_DEBUG_MAX_CHAR)
9421 fprintf_unfiltered (gdb_stdlog, "[%d bytes omitted]",
9422 val - REMOTE_DEBUG_MAX_CHAR);
9424 fprintf_unfiltered (gdb_stdlog, "\n");
9427 /* Skip the ack char if we're in no-ack mode. */
9428 if (!rs->noack_mode)
9429 remote_serial_write ("+", 1);
9430 if (is_notif != NULL)
9435 /* If we got a notification, handle it, and go back to looking
9439 gdb_assert (c == '%');
9443 std::string str = escape_buffer (*buf, val);
9445 fprintf_unfiltered (gdb_stdlog,
9446 " Notification received: %s\n",
9449 if (is_notif != NULL)
9452 handle_notification (rs->notif_state, *buf);
9454 /* Notifications require no acknowledgement. */
9456 if (expecting_notif)
9463 getpkt_sane (char **buf, long *sizeof_buf, int forever)
9465 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
9469 getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
9472 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
9476 /* Check whether EVENT is a fork event for the process specified
9477 by the pid passed in DATA, and if it is, kill the fork child. */
9480 kill_child_of_pending_fork (QUEUE (stop_reply_p) *q,
9481 QUEUE_ITER (stop_reply_p) *iter,
9485 struct queue_iter_param *param = (struct queue_iter_param *) data;
9486 int parent_pid = *(int *) param->input;
9488 if (is_pending_fork_parent (&event->ws, parent_pid, event->ptid))
9490 struct remote_state *rs = get_remote_state ();
9491 int child_pid = ptid_get_pid (event->ws.value.related_pid);
9494 res = remote_vkill (child_pid, rs);
9496 error (_("Can't kill fork child process %d"), child_pid);
9502 /* Kill any new fork children of process PID that haven't been
9503 processed by follow_fork. */
9506 kill_new_fork_children (int pid, struct remote_state *rs)
9508 struct thread_info *thread;
9509 struct notif_client *notif = ¬if_client_stop;
9510 struct queue_iter_param param;
9512 /* Kill the fork child threads of any threads in process PID
9513 that are stopped at a fork event. */
9514 ALL_NON_EXITED_THREADS (thread)
9516 struct target_waitstatus *ws = &thread->pending_follow;
9518 if (is_pending_fork_parent (ws, pid, thread->ptid))
9520 struct remote_state *rs = get_remote_state ();
9521 int child_pid = ptid_get_pid (ws->value.related_pid);
9524 res = remote_vkill (child_pid, rs);
9526 error (_("Can't kill fork child process %d"), child_pid);
9530 /* Check for any pending fork events (not reported or processed yet)
9531 in process PID and kill those fork child threads as well. */
9532 remote_notif_get_pending_events (notif);
9534 param.output = NULL;
9535 QUEUE_iterate (stop_reply_p, stop_reply_queue,
9536 kill_child_of_pending_fork, ¶m);
9540 /* Target hook to kill the current inferior. */
9543 remote_target::kill ()
9546 int pid = ptid_get_pid (inferior_ptid);
9547 struct remote_state *rs = get_remote_state ();
9549 if (packet_support (PACKET_vKill) != PACKET_DISABLE)
9551 /* If we're stopped while forking and we haven't followed yet,
9552 kill the child task. We need to do this before killing the
9553 parent task because if this is a vfork then the parent will
9555 kill_new_fork_children (pid, rs);
9557 res = remote_vkill (pid, rs);
9560 target_mourn_inferior (inferior_ptid);
9565 /* If we are in 'target remote' mode and we are killing the only
9566 inferior, then we will tell gdbserver to exit and unpush the
9568 if (res == -1 && !remote_multi_process_p (rs)
9569 && number_of_live_inferiors () == 1)
9573 /* We've killed the remote end, we get to mourn it. If we are
9574 not in extended mode, mourning the inferior also unpushes
9575 remote_ops from the target stack, which closes the remote
9577 target_mourn_inferior (inferior_ptid);
9582 error (_("Can't kill process"));
9585 /* Send a kill request to the target using the 'vKill' packet. */
9588 remote_vkill (int pid, struct remote_state *rs)
9590 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
9593 /* Tell the remote target to detach. */
9594 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
9596 getpkt (&rs->buf, &rs->buf_size, 0);
9598 switch (packet_ok (rs->buf,
9599 &remote_protocol_packets[PACKET_vKill]))
9605 case PACKET_UNKNOWN:
9608 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
9612 /* Send a kill request to the target using the 'k' packet. */
9615 remote_kill_k (void)
9617 /* Catch errors so the user can quit from gdb even when we
9618 aren't on speaking terms with the remote system. */
9623 CATCH (ex, RETURN_MASK_ERROR)
9625 if (ex.error == TARGET_CLOSE_ERROR)
9627 /* If we got an (EOF) error that caused the target
9628 to go away, then we're done, that's what we wanted.
9629 "k" is susceptible to cause a premature EOF, given
9630 that the remote server isn't actually required to
9631 reply to "k", and it can happen that it doesn't
9632 even get to reply ACK to the "k". */
9636 /* Otherwise, something went wrong. We didn't actually kill
9637 the target. Just propagate the exception, and let the
9638 user or higher layers decide what to do. */
9639 throw_exception (ex);
9645 remote_target::mourn_inferior ()
9647 struct remote_state *rs = get_remote_state ();
9649 /* In 'target remote' mode with one inferior, we close the connection. */
9650 if (!rs->extended && number_of_live_inferiors () <= 1)
9652 unpush_target (this);
9654 /* remote_close takes care of doing most of the clean up. */
9655 generic_mourn_inferior ();
9659 /* In case we got here due to an error, but we're going to stay
9661 rs->waiting_for_stop_reply = 0;
9663 /* If the current general thread belonged to the process we just
9664 detached from or has exited, the remote side current general
9665 thread becomes undefined. Considering a case like this:
9667 - We just got here due to a detach.
9668 - The process that we're detaching from happens to immediately
9669 report a global breakpoint being hit in non-stop mode, in the
9670 same thread we had selected before.
9671 - GDB attaches to this process again.
9672 - This event happens to be the next event we handle.
9674 GDB would consider that the current general thread didn't need to
9675 be set on the stub side (with Hg), since for all it knew,
9676 GENERAL_THREAD hadn't changed.
9678 Notice that although in all-stop mode, the remote server always
9679 sets the current thread to the thread reporting the stop event,
9680 that doesn't happen in non-stop mode; in non-stop, the stub *must
9681 not* change the current thread when reporting a breakpoint hit,
9682 due to the decoupling of event reporting and event handling.
9684 To keep things simple, we always invalidate our notion of the
9686 record_currthread (rs, minus_one_ptid);
9688 /* Call common code to mark the inferior as not running. */
9689 generic_mourn_inferior ();
9691 if (!have_inferiors ())
9693 if (!remote_multi_process_p (rs))
9695 /* Check whether the target is running now - some remote stubs
9696 automatically restart after kill. */
9698 getpkt (&rs->buf, &rs->buf_size, 0);
9700 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
9702 /* Assume that the target has been restarted. Set
9703 inferior_ptid so that bits of core GDB realizes
9704 there's something here, e.g., so that the user can
9705 say "kill" again. */
9706 inferior_ptid = magic_null_ptid;
9713 extended_remote_target::supports_disable_randomization ()
9715 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
9719 extended_remote_disable_randomization (int val)
9721 struct remote_state *rs = get_remote_state ();
9724 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
9727 reply = remote_get_noisy_reply ();
9729 error (_("Target does not support QDisableRandomization."));
9730 if (strcmp (reply, "OK") != 0)
9731 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
9735 extended_remote_run (const std::string &args)
9737 struct remote_state *rs = get_remote_state ();
9739 const char *remote_exec_file = get_remote_exec_file ();
9741 /* If the user has disabled vRun support, or we have detected that
9742 support is not available, do not try it. */
9743 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
9746 strcpy (rs->buf, "vRun;");
9747 len = strlen (rs->buf);
9749 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
9750 error (_("Remote file name too long for run packet"));
9751 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
9752 strlen (remote_exec_file));
9758 gdb_argv argv (args.c_str ());
9759 for (i = 0; argv[i] != NULL; i++)
9761 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
9762 error (_("Argument list too long for run packet"));
9763 rs->buf[len++] = ';';
9764 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
9769 rs->buf[len++] = '\0';
9772 getpkt (&rs->buf, &rs->buf_size, 0);
9774 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
9777 /* We have a wait response. All is well. */
9779 case PACKET_UNKNOWN:
9782 if (remote_exec_file[0] == '\0')
9783 error (_("Running the default executable on the remote target failed; "
9784 "try \"set remote exec-file\"?"));
9786 error (_("Running \"%s\" on the remote target failed"),
9789 gdb_assert_not_reached (_("bad switch"));
9793 /* Helper function to send set/unset environment packets. ACTION is
9794 either "set" or "unset". PACKET is either "QEnvironmentHexEncoded"
9795 or "QEnvironmentUnsetVariable". VALUE is the variable to be
9799 send_environment_packet (struct remote_state *rs,
9804 /* Convert the environment variable to an hex string, which
9805 is the best format to be transmitted over the wire. */
9806 std::string encoded_value = bin2hex ((const gdb_byte *) value,
9809 xsnprintf (rs->buf, get_remote_packet_size (),
9810 "%s:%s", packet, encoded_value.c_str ());
9813 getpkt (&rs->buf, &rs->buf_size, 0);
9814 if (strcmp (rs->buf, "OK") != 0)
9815 warning (_("Unable to %s environment variable '%s' on remote."),
9819 /* Helper function to handle the QEnvironment* packets. */
9822 extended_remote_environment_support (struct remote_state *rs)
9824 if (packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
9826 putpkt ("QEnvironmentReset");
9827 getpkt (&rs->buf, &rs->buf_size, 0);
9828 if (strcmp (rs->buf, "OK") != 0)
9829 warning (_("Unable to reset environment on remote."));
9832 gdb_environ *e = ¤t_inferior ()->environment;
9834 if (packet_support (PACKET_QEnvironmentHexEncoded) != PACKET_DISABLE)
9835 for (const std::string &el : e->user_set_env ())
9836 send_environment_packet (rs, "set", "QEnvironmentHexEncoded",
9839 if (packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
9840 for (const std::string &el : e->user_unset_env ())
9841 send_environment_packet (rs, "unset", "QEnvironmentUnset", el.c_str ());
9844 /* Helper function to set the current working directory for the
9845 inferior in the remote target. */
9848 extended_remote_set_inferior_cwd (struct remote_state *rs)
9850 if (packet_support (PACKET_QSetWorkingDir) != PACKET_DISABLE)
9852 const char *inferior_cwd = get_inferior_cwd ();
9854 if (inferior_cwd != NULL)
9856 std::string hexpath = bin2hex ((const gdb_byte *) inferior_cwd,
9857 strlen (inferior_cwd));
9859 xsnprintf (rs->buf, get_remote_packet_size (),
9860 "QSetWorkingDir:%s", hexpath.c_str ());
9864 /* An empty inferior_cwd means that the user wants us to
9865 reset the remote server's inferior's cwd. */
9866 xsnprintf (rs->buf, get_remote_packet_size (),
9871 getpkt (&rs->buf, &rs->buf_size, 0);
9872 if (packet_ok (rs->buf,
9873 &remote_protocol_packets[PACKET_QSetWorkingDir])
9876 Remote replied unexpectedly while setting the inferior's working\n\
9883 /* In the extended protocol we want to be able to do things like
9884 "run" and have them basically work as expected. So we need
9885 a special create_inferior function. We support changing the
9886 executable file and the command line arguments, but not the
9890 extended_remote_target::create_inferior (const char *exec_file,
9891 const std::string &args,
9892 char **env, int from_tty)
9896 struct remote_state *rs = get_remote_state ();
9897 const char *remote_exec_file = get_remote_exec_file ();
9899 /* If running asynchronously, register the target file descriptor
9900 with the event loop. */
9901 if (target_can_async_p ())
9904 /* Disable address space randomization if requested (and supported). */
9905 if (supports_disable_randomization ())
9906 extended_remote_disable_randomization (disable_randomization);
9908 /* If startup-with-shell is on, we inform gdbserver to start the
9909 remote inferior using a shell. */
9910 if (packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
9912 xsnprintf (rs->buf, get_remote_packet_size (),
9913 "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
9915 getpkt (&rs->buf, &rs->buf_size, 0);
9916 if (strcmp (rs->buf, "OK") != 0)
9918 Remote replied unexpectedly while setting startup-with-shell: %s"),
9922 extended_remote_environment_support (rs);
9924 extended_remote_set_inferior_cwd (rs);
9926 /* Now restart the remote server. */
9927 run_worked = extended_remote_run (args) != -1;
9930 /* vRun was not supported. Fail if we need it to do what the
9932 if (remote_exec_file[0])
9933 error (_("Remote target does not support \"set remote exec-file\""));
9935 error (_("Remote target does not support \"set args\" or run <ARGS>"));
9937 /* Fall back to "R". */
9938 extended_remote_restart ();
9941 if (!have_inferiors ())
9943 /* Clean up from the last time we ran, before we mark the target
9944 running again. This will mark breakpoints uninserted, and
9945 get_offsets may insert breakpoints. */
9946 init_thread_list ();
9947 init_wait_for_inferior ();
9950 /* vRun's success return is a stop reply. */
9951 stop_reply = run_worked ? rs->buf : NULL;
9952 add_current_inferior_and_thread (stop_reply);
9954 /* Get updated offsets, if the stub uses qOffsets. */
9959 /* Given a location's target info BP_TGT and the packet buffer BUF, output
9960 the list of conditions (in agent expression bytecode format), if any, the
9961 target needs to evaluate. The output is placed into the packet buffer
9962 started from BUF and ended at BUF_END. */
9965 remote_add_target_side_condition (struct gdbarch *gdbarch,
9966 struct bp_target_info *bp_tgt, char *buf,
9969 if (bp_tgt->conditions.empty ())
9972 buf += strlen (buf);
9973 xsnprintf (buf, buf_end - buf, "%s", ";");
9976 /* Send conditions to the target. */
9977 for (agent_expr *aexpr : bp_tgt->conditions)
9979 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
9980 buf += strlen (buf);
9981 for (int i = 0; i < aexpr->len; ++i)
9982 buf = pack_hex_byte (buf, aexpr->buf[i]);
9989 remote_add_target_side_commands (struct gdbarch *gdbarch,
9990 struct bp_target_info *bp_tgt, char *buf)
9992 if (bp_tgt->tcommands.empty ())
9995 buf += strlen (buf);
9997 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
9998 buf += strlen (buf);
10000 /* Concatenate all the agent expressions that are commands into the
10002 for (agent_expr *aexpr : bp_tgt->tcommands)
10004 sprintf (buf, "X%x,", aexpr->len);
10005 buf += strlen (buf);
10006 for (int i = 0; i < aexpr->len; ++i)
10007 buf = pack_hex_byte (buf, aexpr->buf[i]);
10012 /* Insert a breakpoint. On targets that have software breakpoint
10013 support, we ask the remote target to do the work; on targets
10014 which don't, we insert a traditional memory breakpoint. */
10017 remote_target::insert_breakpoint (struct gdbarch *gdbarch,
10018 struct bp_target_info *bp_tgt)
10020 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
10021 If it succeeds, then set the support to PACKET_ENABLE. If it
10022 fails, and the user has explicitly requested the Z support then
10023 report an error, otherwise, mark it disabled and go on. */
10025 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
10027 CORE_ADDR addr = bp_tgt->reqstd_address;
10028 struct remote_state *rs;
10031 /* Make sure the remote is pointing at the right process, if
10033 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10034 set_general_process ();
10036 rs = get_remote_state ();
10038 endbuf = rs->buf + get_remote_packet_size ();
10043 addr = (ULONGEST) remote_address_masked (addr);
10044 p += hexnumstr (p, addr);
10045 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10047 if (supports_evaluation_of_breakpoint_conditions ())
10048 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10050 if (can_run_breakpoint_commands ())
10051 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10054 getpkt (&rs->buf, &rs->buf_size, 0);
10056 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
10062 case PACKET_UNKNOWN:
10067 /* If this breakpoint has target-side commands but this stub doesn't
10068 support Z0 packets, throw error. */
10069 if (!bp_tgt->tcommands.empty ())
10070 throw_error (NOT_SUPPORTED_ERROR, _("\
10071 Target doesn't support breakpoints that have target side commands."));
10073 return memory_insert_breakpoint (this, gdbarch, bp_tgt);
10077 remote_target::remove_breakpoint (struct gdbarch *gdbarch,
10078 struct bp_target_info *bp_tgt,
10079 enum remove_bp_reason reason)
10081 CORE_ADDR addr = bp_tgt->placed_address;
10082 struct remote_state *rs = get_remote_state ();
10084 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
10087 char *endbuf = rs->buf + get_remote_packet_size ();
10089 /* Make sure the remote is pointing at the right process, if
10091 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10092 set_general_process ();
10098 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
10099 p += hexnumstr (p, addr);
10100 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10103 getpkt (&rs->buf, &rs->buf_size, 0);
10105 return (rs->buf[0] == 'E');
10108 return memory_remove_breakpoint (this, gdbarch, bp_tgt, reason);
10111 static enum Z_packet_type
10112 watchpoint_to_Z_packet (int type)
10117 return Z_PACKET_WRITE_WP;
10120 return Z_PACKET_READ_WP;
10123 return Z_PACKET_ACCESS_WP;
10126 internal_error (__FILE__, __LINE__,
10127 _("hw_bp_to_z: bad watchpoint type %d"), type);
10132 remote_target::insert_watchpoint (CORE_ADDR addr, int len,
10133 enum target_hw_bp_type type, struct expression *cond)
10135 struct remote_state *rs = get_remote_state ();
10136 char *endbuf = rs->buf + get_remote_packet_size ();
10138 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10140 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
10143 /* Make sure the remote is pointing at the right process, if
10145 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10146 set_general_process ();
10148 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
10149 p = strchr (rs->buf, '\0');
10150 addr = remote_address_masked (addr);
10151 p += hexnumstr (p, (ULONGEST) addr);
10152 xsnprintf (p, endbuf - p, ",%x", len);
10155 getpkt (&rs->buf, &rs->buf_size, 0);
10157 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
10161 case PACKET_UNKNOWN:
10166 internal_error (__FILE__, __LINE__,
10167 _("remote_insert_watchpoint: reached end of function"));
10171 remote_target::watchpoint_addr_within_range (CORE_ADDR addr,
10172 CORE_ADDR start, int length)
10174 CORE_ADDR diff = remote_address_masked (addr - start);
10176 return diff < length;
10181 remote_target::remove_watchpoint (CORE_ADDR addr, int len,
10182 enum target_hw_bp_type type, struct expression *cond)
10184 struct remote_state *rs = get_remote_state ();
10185 char *endbuf = rs->buf + get_remote_packet_size ();
10187 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10189 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
10192 /* Make sure the remote is pointing at the right process, if
10194 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10195 set_general_process ();
10197 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
10198 p = strchr (rs->buf, '\0');
10199 addr = remote_address_masked (addr);
10200 p += hexnumstr (p, (ULONGEST) addr);
10201 xsnprintf (p, endbuf - p, ",%x", len);
10203 getpkt (&rs->buf, &rs->buf_size, 0);
10205 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
10208 case PACKET_UNKNOWN:
10213 internal_error (__FILE__, __LINE__,
10214 _("remote_remove_watchpoint: reached end of function"));
10218 int remote_hw_watchpoint_limit = -1;
10219 int remote_hw_watchpoint_length_limit = -1;
10220 int remote_hw_breakpoint_limit = -1;
10223 remote_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
10225 if (remote_hw_watchpoint_length_limit == 0)
10227 else if (remote_hw_watchpoint_length_limit < 0)
10229 else if (len <= remote_hw_watchpoint_length_limit)
10236 remote_target::can_use_hw_breakpoint (enum bptype type, int cnt, int ot)
10238 if (type == bp_hardware_breakpoint)
10240 if (remote_hw_breakpoint_limit == 0)
10242 else if (remote_hw_breakpoint_limit < 0)
10244 else if (cnt <= remote_hw_breakpoint_limit)
10249 if (remote_hw_watchpoint_limit == 0)
10251 else if (remote_hw_watchpoint_limit < 0)
10255 else if (cnt <= remote_hw_watchpoint_limit)
10261 /* The to_stopped_by_sw_breakpoint method of target remote. */
10264 remote_target::stopped_by_sw_breakpoint ()
10266 struct thread_info *thread = inferior_thread ();
10268 return (thread->priv != NULL
10269 && (get_remote_thread_info (thread)->stop_reason
10270 == TARGET_STOPPED_BY_SW_BREAKPOINT));
10273 /* The to_supports_stopped_by_sw_breakpoint method of target
10277 remote_target::supports_stopped_by_sw_breakpoint ()
10279 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
10282 /* The to_stopped_by_hw_breakpoint method of target remote. */
10285 remote_target::stopped_by_hw_breakpoint ()
10287 struct thread_info *thread = inferior_thread ();
10289 return (thread->priv != NULL
10290 && (get_remote_thread_info (thread)->stop_reason
10291 == TARGET_STOPPED_BY_HW_BREAKPOINT));
10294 /* The to_supports_stopped_by_hw_breakpoint method of target
10298 remote_target::supports_stopped_by_hw_breakpoint ()
10300 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
10304 remote_target::stopped_by_watchpoint ()
10306 struct thread_info *thread = inferior_thread ();
10308 return (thread->priv != NULL
10309 && (get_remote_thread_info (thread)->stop_reason
10310 == TARGET_STOPPED_BY_WATCHPOINT));
10314 remote_target::stopped_data_address (CORE_ADDR *addr_p)
10316 struct thread_info *thread = inferior_thread ();
10318 if (thread->priv != NULL
10319 && (get_remote_thread_info (thread)->stop_reason
10320 == TARGET_STOPPED_BY_WATCHPOINT))
10322 *addr_p = get_remote_thread_info (thread)->watch_data_address;
10331 remote_target::insert_hw_breakpoint (struct gdbarch *gdbarch,
10332 struct bp_target_info *bp_tgt)
10334 CORE_ADDR addr = bp_tgt->reqstd_address;
10335 struct remote_state *rs;
10339 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10342 /* Make sure the remote is pointing at the right process, if
10344 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10345 set_general_process ();
10347 rs = get_remote_state ();
10349 endbuf = rs->buf + get_remote_packet_size ();
10355 addr = remote_address_masked (addr);
10356 p += hexnumstr (p, (ULONGEST) addr);
10357 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
10359 if (supports_evaluation_of_breakpoint_conditions ())
10360 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10362 if (can_run_breakpoint_commands ())
10363 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10366 getpkt (&rs->buf, &rs->buf_size, 0);
10368 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10371 if (rs->buf[1] == '.')
10373 message = strchr (rs->buf + 2, '.');
10375 error (_("Remote failure reply: %s"), message + 1);
10378 case PACKET_UNKNOWN:
10383 internal_error (__FILE__, __LINE__,
10384 _("remote_insert_hw_breakpoint: reached end of function"));
10389 remote_target::remove_hw_breakpoint (struct gdbarch *gdbarch,
10390 struct bp_target_info *bp_tgt)
10393 struct remote_state *rs = get_remote_state ();
10395 char *endbuf = rs->buf + get_remote_packet_size ();
10397 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10400 /* Make sure the remote is pointing at the right process, if
10402 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10403 set_general_process ();
10409 addr = remote_address_masked (bp_tgt->placed_address);
10410 p += hexnumstr (p, (ULONGEST) addr);
10411 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
10414 getpkt (&rs->buf, &rs->buf_size, 0);
10416 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10419 case PACKET_UNKNOWN:
10424 internal_error (__FILE__, __LINE__,
10425 _("remote_remove_hw_breakpoint: reached end of function"));
10428 /* Verify memory using the "qCRC:" request. */
10431 remote_target::verify_memory (const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
10433 struct remote_state *rs = get_remote_state ();
10434 unsigned long host_crc, target_crc;
10437 /* It doesn't make sense to use qCRC if the remote target is
10438 connected but not running. */
10439 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
10441 enum packet_result result;
10443 /* Make sure the remote is pointing at the right process. */
10444 set_general_process ();
10446 /* FIXME: assumes lma can fit into long. */
10447 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
10448 (long) lma, (long) size);
10451 /* Be clever; compute the host_crc before waiting for target
10453 host_crc = xcrc32 (data, size, 0xffffffff);
10455 getpkt (&rs->buf, &rs->buf_size, 0);
10457 result = packet_ok (rs->buf,
10458 &remote_protocol_packets[PACKET_qCRC]);
10459 if (result == PACKET_ERROR)
10461 else if (result == PACKET_OK)
10463 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
10464 target_crc = target_crc * 16 + fromhex (*tmp);
10466 return (host_crc == target_crc);
10470 return simple_verify_memory (this, data, lma, size);
10473 /* compare-sections command
10475 With no arguments, compares each loadable section in the exec bfd
10476 with the same memory range on the target, and reports mismatches.
10477 Useful for verifying the image on the target against the exec file. */
10480 compare_sections_command (const char *args, int from_tty)
10483 const char *sectname;
10484 bfd_size_type size;
10487 int mismatched = 0;
10492 error (_("command cannot be used without an exec file"));
10494 /* Make sure the remote is pointing at the right process. */
10495 set_general_process ();
10497 if (args != NULL && strcmp (args, "-r") == 0)
10503 for (s = exec_bfd->sections; s; s = s->next)
10505 if (!(s->flags & SEC_LOAD))
10506 continue; /* Skip non-loadable section. */
10508 if (read_only && (s->flags & SEC_READONLY) == 0)
10509 continue; /* Skip writeable sections */
10511 size = bfd_get_section_size (s);
10513 continue; /* Skip zero-length section. */
10515 sectname = bfd_get_section_name (exec_bfd, s);
10516 if (args && strcmp (args, sectname) != 0)
10517 continue; /* Not the section selected by user. */
10519 matched = 1; /* Do this section. */
10522 gdb::byte_vector sectdata (size);
10523 bfd_get_section_contents (exec_bfd, s, sectdata.data (), 0, size);
10525 res = target_verify_memory (sectdata.data (), lma, size);
10528 error (_("target memory fault, section %s, range %s -- %s"), sectname,
10529 paddress (target_gdbarch (), lma),
10530 paddress (target_gdbarch (), lma + size));
10532 printf_filtered ("Section %s, range %s -- %s: ", sectname,
10533 paddress (target_gdbarch (), lma),
10534 paddress (target_gdbarch (), lma + size));
10536 printf_filtered ("matched.\n");
10539 printf_filtered ("MIS-MATCHED!\n");
10543 if (mismatched > 0)
10544 warning (_("One or more sections of the target image does not match\n\
10545 the loaded file\n"));
10546 if (args && !matched)
10547 printf_filtered (_("No loaded section named '%s'.\n"), args);
10550 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
10551 into remote target. The number of bytes written to the remote
10552 target is returned, or -1 for error. */
10554 static enum target_xfer_status
10555 remote_write_qxfer (const char *object_name,
10556 const char *annex, const gdb_byte *writebuf,
10557 ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
10558 struct packet_config *packet)
10562 struct remote_state *rs = get_remote_state ();
10563 int max_size = get_memory_write_packet_size ();
10565 if (packet_config_support (packet) == PACKET_DISABLE)
10566 return TARGET_XFER_E_IO;
10568 /* Insert header. */
10569 i = snprintf (rs->buf, max_size,
10570 "qXfer:%s:write:%s:%s:",
10571 object_name, annex ? annex : "",
10572 phex_nz (offset, sizeof offset));
10573 max_size -= (i + 1);
10575 /* Escape as much data as fits into rs->buf. */
10576 buf_len = remote_escape_output
10577 (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
10579 if (putpkt_binary (rs->buf, i + buf_len) < 0
10580 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10581 || packet_ok (rs->buf, packet) != PACKET_OK)
10582 return TARGET_XFER_E_IO;
10584 unpack_varlen_hex (rs->buf, &n);
10587 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
10590 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
10591 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
10592 number of bytes read is returned, or 0 for EOF, or -1 for error.
10593 The number of bytes read may be less than LEN without indicating an
10594 EOF. PACKET is checked and updated to indicate whether the remote
10595 target supports this object. */
10597 static enum target_xfer_status
10598 remote_read_qxfer (const char *object_name,
10600 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
10601 ULONGEST *xfered_len,
10602 struct packet_config *packet)
10604 struct remote_state *rs = get_remote_state ();
10605 LONGEST i, n, packet_len;
10607 if (packet_config_support (packet) == PACKET_DISABLE)
10608 return TARGET_XFER_E_IO;
10610 /* Check whether we've cached an end-of-object packet that matches
10612 if (rs->finished_object)
10614 if (strcmp (object_name, rs->finished_object) == 0
10615 && strcmp (annex ? annex : "", rs->finished_annex) == 0
10616 && offset == rs->finished_offset)
10617 return TARGET_XFER_EOF;
10620 /* Otherwise, we're now reading something different. Discard
10622 xfree (rs->finished_object);
10623 xfree (rs->finished_annex);
10624 rs->finished_object = NULL;
10625 rs->finished_annex = NULL;
10628 /* Request only enough to fit in a single packet. The actual data
10629 may not, since we don't know how much of it will need to be escaped;
10630 the target is free to respond with slightly less data. We subtract
10631 five to account for the response type and the protocol frame. */
10632 n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
10633 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
10634 object_name, annex ? annex : "",
10635 phex_nz (offset, sizeof offset),
10636 phex_nz (n, sizeof n));
10637 i = putpkt (rs->buf);
10639 return TARGET_XFER_E_IO;
10642 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10643 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
10644 return TARGET_XFER_E_IO;
10646 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
10647 error (_("Unknown remote qXfer reply: %s"), rs->buf);
10649 /* 'm' means there is (or at least might be) more data after this
10650 batch. That does not make sense unless there's at least one byte
10651 of data in this reply. */
10652 if (rs->buf[0] == 'm' && packet_len == 1)
10653 error (_("Remote qXfer reply contained no data."));
10655 /* Got some data. */
10656 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
10657 packet_len - 1, readbuf, n);
10659 /* 'l' is an EOF marker, possibly including a final block of data,
10660 or possibly empty. If we have the final block of a non-empty
10661 object, record this fact to bypass a subsequent partial read. */
10662 if (rs->buf[0] == 'l' && offset + i > 0)
10664 rs->finished_object = xstrdup (object_name);
10665 rs->finished_annex = xstrdup (annex ? annex : "");
10666 rs->finished_offset = offset + i;
10670 return TARGET_XFER_EOF;
10674 return TARGET_XFER_OK;
10678 enum target_xfer_status
10679 remote_target::xfer_partial (enum target_object object,
10680 const char *annex, gdb_byte *readbuf,
10681 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
10682 ULONGEST *xfered_len)
10684 struct remote_state *rs;
10688 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
10690 set_remote_traceframe ();
10691 set_general_thread (inferior_ptid);
10693 rs = get_remote_state ();
10695 /* Handle memory using the standard memory routines. */
10696 if (object == TARGET_OBJECT_MEMORY)
10698 /* If the remote target is connected but not running, we should
10699 pass this request down to a lower stratum (e.g. the executable
10701 if (!target_has_execution)
10702 return TARGET_XFER_EOF;
10704 if (writebuf != NULL)
10705 return remote_write_bytes (offset, writebuf, len, unit_size,
10708 return remote_read_bytes (this, offset, readbuf, len, unit_size,
10712 /* Handle SPU memory using qxfer packets. */
10713 if (object == TARGET_OBJECT_SPU)
10716 return remote_read_qxfer ("spu", annex, readbuf, offset, len,
10717 xfered_len, &remote_protocol_packets
10718 [PACKET_qXfer_spu_read]);
10720 return remote_write_qxfer ("spu", annex, writebuf, offset, len,
10721 xfered_len, &remote_protocol_packets
10722 [PACKET_qXfer_spu_write]);
10725 /* Handle extra signal info using qxfer packets. */
10726 if (object == TARGET_OBJECT_SIGNAL_INFO)
10729 return remote_read_qxfer ("siginfo", annex, readbuf, offset, len,
10730 xfered_len, &remote_protocol_packets
10731 [PACKET_qXfer_siginfo_read]);
10733 return remote_write_qxfer ("siginfo", annex,
10734 writebuf, offset, len, xfered_len,
10735 &remote_protocol_packets
10736 [PACKET_qXfer_siginfo_write]);
10739 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
10742 return remote_read_qxfer ("statictrace", annex,
10743 readbuf, offset, len, xfered_len,
10744 &remote_protocol_packets
10745 [PACKET_qXfer_statictrace_read]);
10747 return TARGET_XFER_E_IO;
10750 /* Only handle flash writes. */
10751 if (writebuf != NULL)
10755 case TARGET_OBJECT_FLASH:
10756 return remote_flash_write (this, offset, len, xfered_len,
10760 return TARGET_XFER_E_IO;
10764 /* Map pre-existing objects onto letters. DO NOT do this for new
10765 objects!!! Instead specify new query packets. */
10768 case TARGET_OBJECT_AVR:
10772 case TARGET_OBJECT_AUXV:
10773 gdb_assert (annex == NULL);
10774 return remote_read_qxfer ("auxv", annex, readbuf, offset, len,
10776 &remote_protocol_packets[PACKET_qXfer_auxv]);
10778 case TARGET_OBJECT_AVAILABLE_FEATURES:
10779 return remote_read_qxfer
10780 ("features", annex, readbuf, offset, len, xfered_len,
10781 &remote_protocol_packets[PACKET_qXfer_features]);
10783 case TARGET_OBJECT_LIBRARIES:
10784 return remote_read_qxfer
10785 ("libraries", annex, readbuf, offset, len, xfered_len,
10786 &remote_protocol_packets[PACKET_qXfer_libraries]);
10788 case TARGET_OBJECT_LIBRARIES_SVR4:
10789 return remote_read_qxfer
10790 ("libraries-svr4", annex, readbuf, offset, len, xfered_len,
10791 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
10793 case TARGET_OBJECT_MEMORY_MAP:
10794 gdb_assert (annex == NULL);
10795 return remote_read_qxfer ("memory-map", annex, readbuf, offset, len,
10797 &remote_protocol_packets[PACKET_qXfer_memory_map]);
10799 case TARGET_OBJECT_OSDATA:
10800 /* Should only get here if we're connected. */
10801 gdb_assert (rs->remote_desc);
10802 return remote_read_qxfer
10803 ("osdata", annex, readbuf, offset, len, xfered_len,
10804 &remote_protocol_packets[PACKET_qXfer_osdata]);
10806 case TARGET_OBJECT_THREADS:
10807 gdb_assert (annex == NULL);
10808 return remote_read_qxfer ("threads", annex, readbuf, offset, len,
10810 &remote_protocol_packets[PACKET_qXfer_threads]);
10812 case TARGET_OBJECT_TRACEFRAME_INFO:
10813 gdb_assert (annex == NULL);
10814 return remote_read_qxfer
10815 ("traceframe-info", annex, readbuf, offset, len, xfered_len,
10816 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
10818 case TARGET_OBJECT_FDPIC:
10819 return remote_read_qxfer ("fdpic", annex, readbuf, offset, len,
10821 &remote_protocol_packets[PACKET_qXfer_fdpic]);
10823 case TARGET_OBJECT_OPENVMS_UIB:
10824 return remote_read_qxfer ("uib", annex, readbuf, offset, len,
10826 &remote_protocol_packets[PACKET_qXfer_uib]);
10828 case TARGET_OBJECT_BTRACE:
10829 return remote_read_qxfer ("btrace", annex, readbuf, offset, len,
10831 &remote_protocol_packets[PACKET_qXfer_btrace]);
10833 case TARGET_OBJECT_BTRACE_CONF:
10834 return remote_read_qxfer ("btrace-conf", annex, readbuf, offset,
10836 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
10838 case TARGET_OBJECT_EXEC_FILE:
10839 return remote_read_qxfer ("exec-file", annex, readbuf, offset,
10841 &remote_protocol_packets[PACKET_qXfer_exec_file]);
10844 return TARGET_XFER_E_IO;
10847 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
10848 large enough let the caller deal with it. */
10849 if (len < get_remote_packet_size ())
10850 return TARGET_XFER_E_IO;
10851 len = get_remote_packet_size ();
10853 /* Except for querying the minimum buffer size, target must be open. */
10854 if (!rs->remote_desc)
10855 error (_("remote query is only available after target open"));
10857 gdb_assert (annex != NULL);
10858 gdb_assert (readbuf != NULL);
10862 *p2++ = query_type;
10864 /* We used one buffer char for the remote protocol q command and
10865 another for the query type. As the remote protocol encapsulation
10866 uses 4 chars plus one extra in case we are debugging
10867 (remote_debug), we have PBUFZIZ - 7 left to pack the query
10870 while (annex[i] && (i < (get_remote_packet_size () - 8)))
10872 /* Bad caller may have sent forbidden characters. */
10873 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
10878 gdb_assert (annex[i] == '\0');
10880 i = putpkt (rs->buf);
10882 return TARGET_XFER_E_IO;
10884 getpkt (&rs->buf, &rs->buf_size, 0);
10885 strcpy ((char *) readbuf, rs->buf);
10887 *xfered_len = strlen ((char *) readbuf);
10888 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
10891 /* Implementation of to_get_memory_xfer_limit. */
10894 remote_target::get_memory_xfer_limit ()
10896 return get_memory_write_packet_size ();
10900 remote_target::search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
10901 const gdb_byte *pattern, ULONGEST pattern_len,
10902 CORE_ADDR *found_addrp)
10904 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
10905 struct remote_state *rs = get_remote_state ();
10906 int max_size = get_memory_write_packet_size ();
10907 struct packet_config *packet =
10908 &remote_protocol_packets[PACKET_qSearch_memory];
10909 /* Number of packet bytes used to encode the pattern;
10910 this could be more than PATTERN_LEN due to escape characters. */
10911 int escaped_pattern_len;
10912 /* Amount of pattern that was encodable in the packet. */
10913 int used_pattern_len;
10916 ULONGEST found_addr;
10918 /* Don't go to the target if we don't have to. This is done before
10919 checking packet_config_support to avoid the possibility that a
10920 success for this edge case means the facility works in
10922 if (pattern_len > search_space_len)
10924 if (pattern_len == 0)
10926 *found_addrp = start_addr;
10930 /* If we already know the packet isn't supported, fall back to the simple
10931 way of searching memory. */
10933 if (packet_config_support (packet) == PACKET_DISABLE)
10935 /* Target doesn't provided special support, fall back and use the
10936 standard support (copy memory and do the search here). */
10937 return simple_search_memory (this, start_addr, search_space_len,
10938 pattern, pattern_len, found_addrp);
10941 /* Make sure the remote is pointing at the right process. */
10942 set_general_process ();
10944 /* Insert header. */
10945 i = snprintf (rs->buf, max_size,
10946 "qSearch:memory:%s;%s;",
10947 phex_nz (start_addr, addr_size),
10948 phex_nz (search_space_len, sizeof (search_space_len)));
10949 max_size -= (i + 1);
10951 /* Escape as much data as fits into rs->buf. */
10952 escaped_pattern_len =
10953 remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
10954 &used_pattern_len, max_size);
10956 /* Bail if the pattern is too large. */
10957 if (used_pattern_len != pattern_len)
10958 error (_("Pattern is too large to transmit to remote target."));
10960 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
10961 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10962 || packet_ok (rs->buf, packet) != PACKET_OK)
10964 /* The request may not have worked because the command is not
10965 supported. If so, fall back to the simple way. */
10966 if (packet_config_support (packet) == PACKET_DISABLE)
10968 return simple_search_memory (this, start_addr, search_space_len,
10969 pattern, pattern_len, found_addrp);
10974 if (rs->buf[0] == '0')
10976 else if (rs->buf[0] == '1')
10979 if (rs->buf[1] != ',')
10980 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
10981 unpack_varlen_hex (rs->buf + 2, &found_addr);
10982 *found_addrp = found_addr;
10985 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
10991 remote_target::rcmd (const char *command, struct ui_file *outbuf)
10993 struct remote_state *rs = get_remote_state ();
10996 if (!rs->remote_desc)
10997 error (_("remote rcmd is only available after target open"));
10999 /* Send a NULL command across as an empty command. */
11000 if (command == NULL)
11003 /* The query prefix. */
11004 strcpy (rs->buf, "qRcmd,");
11005 p = strchr (rs->buf, '\0');
11007 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
11008 > get_remote_packet_size ())
11009 error (_("\"monitor\" command ``%s'' is too long."), command);
11011 /* Encode the actual command. */
11012 bin2hex ((const gdb_byte *) command, p, strlen (command));
11014 if (putpkt (rs->buf) < 0)
11015 error (_("Communication problem with target."));
11017 /* get/display the response */
11022 /* XXX - see also remote_get_noisy_reply(). */
11023 QUIT; /* Allow user to bail out with ^C. */
11025 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
11027 /* Timeout. Continue to (try to) read responses.
11028 This is better than stopping with an error, assuming the stub
11029 is still executing the (long) monitor command.
11030 If needed, the user can interrupt gdb using C-c, obtaining
11031 an effect similar to stop on timeout. */
11035 if (buf[0] == '\0')
11036 error (_("Target does not support this command."));
11037 if (buf[0] == 'O' && buf[1] != 'K')
11039 remote_console_output (buf + 1); /* 'O' message from stub. */
11042 if (strcmp (buf, "OK") == 0)
11044 if (strlen (buf) == 3 && buf[0] == 'E'
11045 && isdigit (buf[1]) && isdigit (buf[2]))
11047 error (_("Protocol error with Rcmd"));
11049 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
11051 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
11053 fputc_unfiltered (c, outbuf);
11059 std::vector<mem_region>
11060 remote_target::memory_map ()
11062 std::vector<mem_region> result;
11063 gdb::optional<gdb::char_vector> text
11064 = target_read_stralloc (target_stack, TARGET_OBJECT_MEMORY_MAP, NULL);
11067 result = parse_memory_map (text->data ());
11073 packet_command (const char *args, int from_tty)
11075 struct remote_state *rs = get_remote_state ();
11077 if (!rs->remote_desc)
11078 error (_("command can only be used with remote target"));
11081 error (_("remote-packet command requires packet text as argument"));
11083 puts_filtered ("sending: ");
11084 print_packet (args);
11085 puts_filtered ("\n");
11088 getpkt (&rs->buf, &rs->buf_size, 0);
11089 puts_filtered ("received: ");
11090 print_packet (rs->buf);
11091 puts_filtered ("\n");
11095 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
11097 static void display_thread_info (struct gdb_ext_thread_info *info);
11099 static void threadset_test_cmd (char *cmd, int tty);
11101 static void threadalive_test (char *cmd, int tty);
11103 static void threadlist_test_cmd (char *cmd, int tty);
11105 int get_and_display_threadinfo (threadref *ref);
11107 static void threadinfo_test_cmd (char *cmd, int tty);
11109 static int thread_display_step (threadref *ref, void *context);
11111 static void threadlist_update_test_cmd (char *cmd, int tty);
11113 static void init_remote_threadtests (void);
11115 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
11118 threadset_test_cmd (const char *cmd, int tty)
11120 int sample_thread = SAMPLE_THREAD;
11122 printf_filtered (_("Remote threadset test\n"));
11123 set_general_thread (sample_thread);
11128 threadalive_test (const char *cmd, int tty)
11130 int sample_thread = SAMPLE_THREAD;
11131 int pid = ptid_get_pid (inferior_ptid);
11132 ptid_t ptid = ptid_build (pid, sample_thread, 0);
11134 if (remote_thread_alive (ptid))
11135 printf_filtered ("PASS: Thread alive test\n");
11137 printf_filtered ("FAIL: Thread alive test\n");
11140 void output_threadid (char *title, threadref *ref);
11143 output_threadid (char *title, threadref *ref)
11147 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
11149 printf_filtered ("%s %s\n", title, (&hexid[0]));
11153 threadlist_test_cmd (const char *cmd, int tty)
11156 threadref nextthread;
11157 int done, result_count;
11158 threadref threadlist[3];
11160 printf_filtered ("Remote Threadlist test\n");
11161 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
11162 &result_count, &threadlist[0]))
11163 printf_filtered ("FAIL: threadlist test\n");
11166 threadref *scan = threadlist;
11167 threadref *limit = scan + result_count;
11169 while (scan < limit)
11170 output_threadid (" thread ", scan++);
11175 display_thread_info (struct gdb_ext_thread_info *info)
11177 output_threadid ("Threadid: ", &info->threadid);
11178 printf_filtered ("Name: %s\n ", info->shortname);
11179 printf_filtered ("State: %s\n", info->display);
11180 printf_filtered ("other: %s\n\n", info->more_display);
11184 get_and_display_threadinfo (threadref *ref)
11188 struct gdb_ext_thread_info threadinfo;
11190 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
11191 | TAG_MOREDISPLAY | TAG_DISPLAY;
11192 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
11193 display_thread_info (&threadinfo);
11198 threadinfo_test_cmd (const char *cmd, int tty)
11200 int athread = SAMPLE_THREAD;
11204 int_to_threadref (&thread, athread);
11205 printf_filtered ("Remote Threadinfo test\n");
11206 if (!get_and_display_threadinfo (&thread))
11207 printf_filtered ("FAIL cannot get thread info\n");
11211 thread_display_step (threadref *ref, void *context)
11213 /* output_threadid(" threadstep ",ref); *//* simple test */
11214 return get_and_display_threadinfo (ref);
11218 threadlist_update_test_cmd (const char *cmd, int tty)
11220 printf_filtered ("Remote Threadlist update test\n");
11221 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
11225 init_remote_threadtests (void)
11227 add_com ("tlist", class_obscure, threadlist_test_cmd,
11228 _("Fetch and print the remote list of "
11229 "thread identifiers, one pkt only"));
11230 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
11231 _("Fetch and display info about one thread"));
11232 add_com ("tset", class_obscure, threadset_test_cmd,
11233 _("Test setting to a different thread"));
11234 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
11235 _("Iterate through updating all remote thread info"));
11236 add_com ("talive", class_obscure, threadalive_test,
11237 _(" Remote thread alive test "));
11242 /* Convert a thread ID to a string. Returns the string in a static
11246 remote_target::pid_to_str (ptid_t ptid)
11248 static char buf[64];
11249 struct remote_state *rs = get_remote_state ();
11251 if (ptid_equal (ptid, null_ptid))
11252 return normal_pid_to_str (ptid);
11253 else if (ptid_is_pid (ptid))
11255 /* Printing an inferior target id. */
11257 /* When multi-process extensions are off, there's no way in the
11258 remote protocol to know the remote process id, if there's any
11259 at all. There's one exception --- when we're connected with
11260 target extended-remote, and we manually attached to a process
11261 with "attach PID". We don't record anywhere a flag that
11262 allows us to distinguish that case from the case of
11263 connecting with extended-remote and the stub already being
11264 attached to a process, and reporting yes to qAttached, hence
11265 no smart special casing here. */
11266 if (!remote_multi_process_p (rs))
11268 xsnprintf (buf, sizeof buf, "Remote target");
11272 return normal_pid_to_str (ptid);
11276 if (ptid_equal (magic_null_ptid, ptid))
11277 xsnprintf (buf, sizeof buf, "Thread <main>");
11278 else if (remote_multi_process_p (rs))
11279 if (ptid_get_lwp (ptid) == 0)
11280 return normal_pid_to_str (ptid);
11282 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
11283 ptid_get_pid (ptid), ptid_get_lwp (ptid));
11285 xsnprintf (buf, sizeof buf, "Thread %ld",
11286 ptid_get_lwp (ptid));
11291 /* Get the address of the thread local variable in OBJFILE which is
11292 stored at OFFSET within the thread local storage for thread PTID. */
11295 remote_target::get_thread_local_address (ptid_t ptid, CORE_ADDR lm,
11298 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
11300 struct remote_state *rs = get_remote_state ();
11302 char *endp = rs->buf + get_remote_packet_size ();
11303 enum packet_result result;
11305 strcpy (p, "qGetTLSAddr:");
11307 p = write_ptid (p, endp, ptid);
11309 p += hexnumstr (p, offset);
11311 p += hexnumstr (p, lm);
11315 getpkt (&rs->buf, &rs->buf_size, 0);
11316 result = packet_ok (rs->buf,
11317 &remote_protocol_packets[PACKET_qGetTLSAddr]);
11318 if (result == PACKET_OK)
11322 unpack_varlen_hex (rs->buf, &result);
11325 else if (result == PACKET_UNKNOWN)
11326 throw_error (TLS_GENERIC_ERROR,
11327 _("Remote target doesn't support qGetTLSAddr packet"));
11329 throw_error (TLS_GENERIC_ERROR,
11330 _("Remote target failed to process qGetTLSAddr request"));
11333 throw_error (TLS_GENERIC_ERROR,
11334 _("TLS not supported or disabled on this target"));
11339 /* Provide thread local base, i.e. Thread Information Block address.
11340 Returns 1 if ptid is found and thread_local_base is non zero. */
11343 remote_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
11345 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
11347 struct remote_state *rs = get_remote_state ();
11349 char *endp = rs->buf + get_remote_packet_size ();
11350 enum packet_result result;
11352 strcpy (p, "qGetTIBAddr:");
11354 p = write_ptid (p, endp, ptid);
11358 getpkt (&rs->buf, &rs->buf_size, 0);
11359 result = packet_ok (rs->buf,
11360 &remote_protocol_packets[PACKET_qGetTIBAddr]);
11361 if (result == PACKET_OK)
11365 unpack_varlen_hex (rs->buf, &result);
11367 *addr = (CORE_ADDR) result;
11370 else if (result == PACKET_UNKNOWN)
11371 error (_("Remote target doesn't support qGetTIBAddr packet"));
11373 error (_("Remote target failed to process qGetTIBAddr request"));
11376 error (_("qGetTIBAddr not supported or disabled on this target"));
11381 /* Support for inferring a target description based on the current
11382 architecture and the size of a 'g' packet. While the 'g' packet
11383 can have any size (since optional registers can be left off the
11384 end), some sizes are easily recognizable given knowledge of the
11385 approximate architecture. */
11387 struct remote_g_packet_guess
11390 const struct target_desc *tdesc;
11392 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
11393 DEF_VEC_O(remote_g_packet_guess_s);
11395 struct remote_g_packet_data
11397 VEC(remote_g_packet_guess_s) *guesses;
11400 static struct gdbarch_data *remote_g_packet_data_handle;
11403 remote_g_packet_data_init (struct obstack *obstack)
11405 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
11409 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
11410 const struct target_desc *tdesc)
11412 struct remote_g_packet_data *data
11413 = ((struct remote_g_packet_data *)
11414 gdbarch_data (gdbarch, remote_g_packet_data_handle));
11415 struct remote_g_packet_guess new_guess, *guess;
11418 gdb_assert (tdesc != NULL);
11421 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
11423 if (guess->bytes == bytes)
11424 internal_error (__FILE__, __LINE__,
11425 _("Duplicate g packet description added for size %d"),
11428 new_guess.bytes = bytes;
11429 new_guess.tdesc = tdesc;
11430 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
11433 /* Return 1 if remote_read_description would do anything on this target
11434 and architecture, 0 otherwise. */
11437 remote_read_description_p (struct target_ops *target)
11439 struct remote_g_packet_data *data
11440 = ((struct remote_g_packet_data *)
11441 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
11443 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
11449 const struct target_desc *
11450 remote_target::read_description ()
11452 struct remote_g_packet_data *data
11453 = ((struct remote_g_packet_data *)
11454 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
11456 /* Do not try this during initial connection, when we do not know
11457 whether there is a running but stopped thread. */
11458 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
11459 return beneath->read_description ();
11461 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
11463 struct remote_g_packet_guess *guess;
11465 int bytes = send_g_packet ();
11468 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
11470 if (guess->bytes == bytes)
11471 return guess->tdesc;
11473 /* We discard the g packet. A minor optimization would be to
11474 hold on to it, and fill the register cache once we have selected
11475 an architecture, but it's too tricky to do safely. */
11478 return beneath->read_description ();
11481 /* Remote file transfer support. This is host-initiated I/O, not
11482 target-initiated; for target-initiated, see remote-fileio.c. */
11484 /* If *LEFT is at least the length of STRING, copy STRING to
11485 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11486 decrease *LEFT. Otherwise raise an error. */
11489 remote_buffer_add_string (char **buffer, int *left, const char *string)
11491 int len = strlen (string);
11494 error (_("Packet too long for target."));
11496 memcpy (*buffer, string, len);
11500 /* NUL-terminate the buffer as a convenience, if there is
11506 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
11507 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11508 decrease *LEFT. Otherwise raise an error. */
11511 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
11514 if (2 * len > *left)
11515 error (_("Packet too long for target."));
11517 bin2hex (bytes, *buffer, len);
11518 *buffer += 2 * len;
11521 /* NUL-terminate the buffer as a convenience, if there is
11527 /* If *LEFT is large enough, convert VALUE to hex and add it to
11528 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11529 decrease *LEFT. Otherwise raise an error. */
11532 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
11534 int len = hexnumlen (value);
11537 error (_("Packet too long for target."));
11539 hexnumstr (*buffer, value);
11543 /* NUL-terminate the buffer as a convenience, if there is
11549 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
11550 value, *REMOTE_ERRNO to the remote error number or zero if none
11551 was included, and *ATTACHMENT to point to the start of the annex
11552 if any. The length of the packet isn't needed here; there may
11553 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
11555 Return 0 if the packet could be parsed, -1 if it could not. If
11556 -1 is returned, the other variables may not be initialized. */
11559 remote_hostio_parse_result (char *buffer, int *retcode,
11560 int *remote_errno, char **attachment)
11565 *attachment = NULL;
11567 if (buffer[0] != 'F')
11571 *retcode = strtol (&buffer[1], &p, 16);
11572 if (errno != 0 || p == &buffer[1])
11575 /* Check for ",errno". */
11579 *remote_errno = strtol (p + 1, &p2, 16);
11580 if (errno != 0 || p + 1 == p2)
11585 /* Check for ";attachment". If there is no attachment, the
11586 packet should end here. */
11589 *attachment = p + 1;
11592 else if (*p == '\0')
11598 /* Send a prepared I/O packet to the target and read its response.
11599 The prepared packet is in the global RS->BUF before this function
11600 is called, and the answer is there when we return.
11602 COMMAND_BYTES is the length of the request to send, which may include
11603 binary data. WHICH_PACKET is the packet configuration to check
11604 before attempting a packet. If an error occurs, *REMOTE_ERRNO
11605 is set to the error number and -1 is returned. Otherwise the value
11606 returned by the function is returned.
11608 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
11609 attachment is expected; an error will be reported if there's a
11610 mismatch. If one is found, *ATTACHMENT will be set to point into
11611 the packet buffer and *ATTACHMENT_LEN will be set to the
11612 attachment's length. */
11615 remote_hostio_send_command (int command_bytes, int which_packet,
11616 int *remote_errno, char **attachment,
11617 int *attachment_len)
11619 struct remote_state *rs = get_remote_state ();
11620 int ret, bytes_read;
11621 char *attachment_tmp;
11623 if (packet_support (which_packet) == PACKET_DISABLE)
11625 *remote_errno = FILEIO_ENOSYS;
11629 putpkt_binary (rs->buf, command_bytes);
11630 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
11632 /* If it timed out, something is wrong. Don't try to parse the
11634 if (bytes_read < 0)
11636 *remote_errno = FILEIO_EINVAL;
11640 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
11643 *remote_errno = FILEIO_EINVAL;
11645 case PACKET_UNKNOWN:
11646 *remote_errno = FILEIO_ENOSYS;
11652 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
11655 *remote_errno = FILEIO_EINVAL;
11659 /* Make sure we saw an attachment if and only if we expected one. */
11660 if ((attachment_tmp == NULL && attachment != NULL)
11661 || (attachment_tmp != NULL && attachment == NULL))
11663 *remote_errno = FILEIO_EINVAL;
11667 /* If an attachment was found, it must point into the packet buffer;
11668 work out how many bytes there were. */
11669 if (attachment_tmp != NULL)
11671 *attachment = attachment_tmp;
11672 *attachment_len = bytes_read - (*attachment - rs->buf);
11678 /* Invalidate the readahead cache. */
11681 readahead_cache_invalidate (void)
11683 struct remote_state *rs = get_remote_state ();
11685 rs->readahead_cache.fd = -1;
11688 /* Invalidate the readahead cache if it is holding data for FD. */
11691 readahead_cache_invalidate_fd (int fd)
11693 struct remote_state *rs = get_remote_state ();
11695 if (rs->readahead_cache.fd == fd)
11696 rs->readahead_cache.fd = -1;
11699 /* Set the filesystem remote_hostio functions that take FILENAME
11700 arguments will use. Return 0 on success, or -1 if an error
11701 occurs (and set *REMOTE_ERRNO). */
11704 remote_hostio_set_filesystem (struct inferior *inf, int *remote_errno)
11706 struct remote_state *rs = get_remote_state ();
11707 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
11709 int left = get_remote_packet_size () - 1;
11713 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11716 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
11719 remote_buffer_add_string (&p, &left, "vFile:setfs:");
11721 xsnprintf (arg, sizeof (arg), "%x", required_pid);
11722 remote_buffer_add_string (&p, &left, arg);
11724 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
11725 remote_errno, NULL, NULL);
11727 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11731 rs->fs_pid = required_pid;
11736 /* Implementation of to_fileio_open. */
11739 remote_hostio_open (struct target_ops *self,
11740 struct inferior *inf, const char *filename,
11741 int flags, int mode, int warn_if_slow,
11744 struct remote_state *rs = get_remote_state ();
11746 int left = get_remote_packet_size () - 1;
11750 static int warning_issued = 0;
11752 printf_unfiltered (_("Reading %s from remote target...\n"),
11755 if (!warning_issued)
11757 warning (_("File transfers from remote targets can be slow."
11758 " Use \"set sysroot\" to access files locally"
11760 warning_issued = 1;
11764 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11767 remote_buffer_add_string (&p, &left, "vFile:open:");
11769 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11770 strlen (filename));
11771 remote_buffer_add_string (&p, &left, ",");
11773 remote_buffer_add_int (&p, &left, flags);
11774 remote_buffer_add_string (&p, &left, ",");
11776 remote_buffer_add_int (&p, &left, mode);
11778 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
11779 remote_errno, NULL, NULL);
11783 remote_target::fileio_open (struct inferior *inf, const char *filename,
11784 int flags, int mode, int warn_if_slow,
11787 return remote_hostio_open (this, inf, filename, flags, mode, warn_if_slow,
11791 /* Implementation of to_fileio_pwrite. */
11794 remote_hostio_pwrite (struct target_ops *self,
11795 int fd, const gdb_byte *write_buf, int len,
11796 ULONGEST offset, int *remote_errno)
11798 struct remote_state *rs = get_remote_state ();
11800 int left = get_remote_packet_size ();
11803 readahead_cache_invalidate_fd (fd);
11805 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
11807 remote_buffer_add_int (&p, &left, fd);
11808 remote_buffer_add_string (&p, &left, ",");
11810 remote_buffer_add_int (&p, &left, offset);
11811 remote_buffer_add_string (&p, &left, ",");
11813 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
11814 get_remote_packet_size () - (p - rs->buf));
11816 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
11817 remote_errno, NULL, NULL);
11821 remote_target::fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
11822 ULONGEST offset, int *remote_errno)
11824 return remote_hostio_pwrite (this, fd, write_buf, len, offset, remote_errno);
11827 /* Helper for the implementation of to_fileio_pread. Read the file
11828 from the remote side with vFile:pread. */
11831 remote_hostio_pread_vFile (struct target_ops *self,
11832 int fd, gdb_byte *read_buf, int len,
11833 ULONGEST offset, int *remote_errno)
11835 struct remote_state *rs = get_remote_state ();
11838 int left = get_remote_packet_size ();
11839 int ret, attachment_len;
11842 remote_buffer_add_string (&p, &left, "vFile:pread:");
11844 remote_buffer_add_int (&p, &left, fd);
11845 remote_buffer_add_string (&p, &left, ",");
11847 remote_buffer_add_int (&p, &left, len);
11848 remote_buffer_add_string (&p, &left, ",");
11850 remote_buffer_add_int (&p, &left, offset);
11852 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
11853 remote_errno, &attachment,
11859 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11861 if (read_len != ret)
11862 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
11867 /* Serve pread from the readahead cache. Returns number of bytes
11868 read, or 0 if the request can't be served from the cache. */
11871 remote_hostio_pread_from_cache (struct remote_state *rs,
11872 int fd, gdb_byte *read_buf, size_t len,
11875 struct readahead_cache *cache = &rs->readahead_cache;
11877 if (cache->fd == fd
11878 && cache->offset <= offset
11879 && offset < cache->offset + cache->bufsize)
11881 ULONGEST max = cache->offset + cache->bufsize;
11883 if (offset + len > max)
11884 len = max - offset;
11886 memcpy (read_buf, cache->buf + offset - cache->offset, len);
11893 /* Implementation of to_fileio_pread. */
11896 remote_hostio_pread (struct target_ops *self,
11897 int fd, gdb_byte *read_buf, int len,
11898 ULONGEST offset, int *remote_errno)
11901 struct remote_state *rs = get_remote_state ();
11902 struct readahead_cache *cache = &rs->readahead_cache;
11904 ret = remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11907 cache->hit_count++;
11910 fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
11911 pulongest (cache->hit_count));
11915 cache->miss_count++;
11917 fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
11918 pulongest (cache->miss_count));
11921 cache->offset = offset;
11922 cache->bufsize = get_remote_packet_size ();
11923 cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
11925 ret = remote_hostio_pread_vFile (self, cache->fd, cache->buf, cache->bufsize,
11926 cache->offset, remote_errno);
11929 readahead_cache_invalidate_fd (fd);
11933 cache->bufsize = ret;
11934 return remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11938 remote_target::fileio_pread (int fd, gdb_byte *read_buf, int len,
11939 ULONGEST offset, int *remote_errno)
11941 return remote_hostio_pread (this, fd, read_buf, len, offset, remote_errno);
11944 /* Implementation of to_fileio_close. */
11947 remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
11949 struct remote_state *rs = get_remote_state ();
11951 int left = get_remote_packet_size () - 1;
11953 readahead_cache_invalidate_fd (fd);
11955 remote_buffer_add_string (&p, &left, "vFile:close:");
11957 remote_buffer_add_int (&p, &left, fd);
11959 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
11960 remote_errno, NULL, NULL);
11964 remote_target::fileio_close (int fd, int *remote_errno)
11966 return remote_hostio_close (this, fd, remote_errno);
11969 /* Implementation of to_fileio_unlink. */
11972 remote_hostio_unlink (struct target_ops *self,
11973 struct inferior *inf, const char *filename,
11976 struct remote_state *rs = get_remote_state ();
11978 int left = get_remote_packet_size () - 1;
11980 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11983 remote_buffer_add_string (&p, &left, "vFile:unlink:");
11985 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11986 strlen (filename));
11988 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
11989 remote_errno, NULL, NULL);
11993 remote_target::fileio_unlink (struct inferior *inf, const char *filename,
11996 return remote_hostio_unlink (this, inf, filename, remote_errno);
11999 /* Implementation of to_fileio_readlink. */
12001 gdb::optional<std::string>
12002 remote_target::fileio_readlink (struct inferior *inf, const char *filename,
12005 struct remote_state *rs = get_remote_state ();
12008 int left = get_remote_packet_size ();
12009 int len, attachment_len;
12012 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12015 remote_buffer_add_string (&p, &left, "vFile:readlink:");
12017 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12018 strlen (filename));
12020 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
12021 remote_errno, &attachment,
12027 std::string ret (len, '\0');
12029 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12030 (gdb_byte *) &ret[0], len);
12031 if (read_len != len)
12032 error (_("Readlink returned %d, but %d bytes."), len, read_len);
12037 /* Implementation of to_fileio_fstat. */
12040 remote_target::fileio_fstat (int fd, struct stat *st, int *remote_errno)
12042 struct remote_state *rs = get_remote_state ();
12044 int left = get_remote_packet_size ();
12045 int attachment_len, ret;
12047 struct fio_stat fst;
12050 remote_buffer_add_string (&p, &left, "vFile:fstat:");
12052 remote_buffer_add_int (&p, &left, fd);
12054 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
12055 remote_errno, &attachment,
12059 if (*remote_errno != FILEIO_ENOSYS)
12062 /* Strictly we should return -1, ENOSYS here, but when
12063 "set sysroot remote:" was implemented in August 2008
12064 BFD's need for a stat function was sidestepped with
12065 this hack. This was not remedied until March 2015
12066 so we retain the previous behavior to avoid breaking
12069 Note that the memset is a March 2015 addition; older
12070 GDBs set st_size *and nothing else* so the structure
12071 would have garbage in all other fields. This might
12072 break something but retaining the previous behavior
12073 here would be just too wrong. */
12075 memset (st, 0, sizeof (struct stat));
12076 st->st_size = INT_MAX;
12080 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12081 (gdb_byte *) &fst, sizeof (fst));
12083 if (read_len != ret)
12084 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
12086 if (read_len != sizeof (fst))
12087 error (_("vFile:fstat returned %d bytes, but expecting %d."),
12088 read_len, (int) sizeof (fst));
12090 remote_fileio_to_host_stat (&fst, st);
12095 /* Implementation of to_filesystem_is_local. */
12098 remote_target::filesystem_is_local ()
12100 /* Valgrind GDB presents itself as a remote target but works
12101 on the local filesystem: it does not implement remote get
12102 and users are not expected to set a sysroot. To handle
12103 this case we treat the remote filesystem as local if the
12104 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
12105 does not support vFile:open. */
12106 if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
12108 enum packet_support ps = packet_support (PACKET_vFile_open);
12110 if (ps == PACKET_SUPPORT_UNKNOWN)
12112 int fd, remote_errno;
12114 /* Try opening a file to probe support. The supplied
12115 filename is irrelevant, we only care about whether
12116 the stub recognizes the packet or not. */
12117 fd = remote_hostio_open (this, NULL, "just probing",
12118 FILEIO_O_RDONLY, 0700, 0,
12122 remote_hostio_close (this, fd, &remote_errno);
12124 ps = packet_support (PACKET_vFile_open);
12127 if (ps == PACKET_DISABLE)
12129 static int warning_issued = 0;
12131 if (!warning_issued)
12133 warning (_("remote target does not support file"
12134 " transfer, attempting to access files"
12135 " from local filesystem."));
12136 warning_issued = 1;
12147 remote_fileio_errno_to_host (int errnum)
12153 case FILEIO_ENOENT:
12161 case FILEIO_EACCES:
12163 case FILEIO_EFAULT:
12167 case FILEIO_EEXIST:
12169 case FILEIO_ENODEV:
12171 case FILEIO_ENOTDIR:
12173 case FILEIO_EISDIR:
12175 case FILEIO_EINVAL:
12177 case FILEIO_ENFILE:
12179 case FILEIO_EMFILE:
12183 case FILEIO_ENOSPC:
12185 case FILEIO_ESPIPE:
12189 case FILEIO_ENOSYS:
12191 case FILEIO_ENAMETOOLONG:
12192 return ENAMETOOLONG;
12198 remote_hostio_error (int errnum)
12200 int host_error = remote_fileio_errno_to_host (errnum);
12202 if (host_error == -1)
12203 error (_("Unknown remote I/O error %d"), errnum);
12205 error (_("Remote I/O error: %s"), safe_strerror (host_error));
12209 remote_hostio_close_cleanup (void *opaque)
12211 int fd = *(int *) opaque;
12214 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
12218 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
12220 struct cleanup *back_to, *close_cleanup;
12221 int retcode, fd, remote_errno, bytes, io_size;
12223 int bytes_in_buffer;
12226 struct remote_state *rs = get_remote_state ();
12228 if (!rs->remote_desc)
12229 error (_("command can only be used with remote target"));
12231 gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
12233 perror_with_name (local_file);
12235 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
12236 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
12238 0700, 0, &remote_errno);
12240 remote_hostio_error (remote_errno);
12242 /* Send up to this many bytes at once. They won't all fit in the
12243 remote packet limit, so we'll transfer slightly fewer. */
12244 io_size = get_remote_packet_size ();
12245 buffer = (gdb_byte *) xmalloc (io_size);
12246 back_to = make_cleanup (xfree, buffer);
12248 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
12250 bytes_in_buffer = 0;
12253 while (bytes_in_buffer || !saw_eof)
12257 bytes = fread (buffer + bytes_in_buffer, 1,
12258 io_size - bytes_in_buffer,
12262 if (ferror (file.get ()))
12263 error (_("Error reading %s."), local_file);
12266 /* EOF. Unless there is something still in the
12267 buffer from the last iteration, we are done. */
12269 if (bytes_in_buffer == 0)
12277 bytes += bytes_in_buffer;
12278 bytes_in_buffer = 0;
12280 retcode = remote_hostio_pwrite (find_target_at (process_stratum),
12282 offset, &remote_errno);
12285 remote_hostio_error (remote_errno);
12286 else if (retcode == 0)
12287 error (_("Remote write of %d bytes returned 0!"), bytes);
12288 else if (retcode < bytes)
12290 /* Short write. Save the rest of the read data for the next
12292 bytes_in_buffer = bytes - retcode;
12293 memmove (buffer, buffer + retcode, bytes_in_buffer);
12299 discard_cleanups (close_cleanup);
12300 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
12301 remote_hostio_error (remote_errno);
12304 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
12305 do_cleanups (back_to);
12309 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
12311 struct cleanup *back_to, *close_cleanup;
12312 int fd, remote_errno, bytes, io_size;
12315 struct remote_state *rs = get_remote_state ();
12317 if (!rs->remote_desc)
12318 error (_("command can only be used with remote target"));
12320 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
12321 remote_file, FILEIO_O_RDONLY, 0, 0,
12324 remote_hostio_error (remote_errno);
12326 gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
12328 perror_with_name (local_file);
12330 /* Send up to this many bytes at once. They won't all fit in the
12331 remote packet limit, so we'll transfer slightly fewer. */
12332 io_size = get_remote_packet_size ();
12333 buffer = (gdb_byte *) xmalloc (io_size);
12334 back_to = make_cleanup (xfree, buffer);
12336 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
12341 bytes = remote_hostio_pread (find_target_at (process_stratum),
12342 fd, buffer, io_size, offset, &remote_errno);
12344 /* Success, but no bytes, means end-of-file. */
12347 remote_hostio_error (remote_errno);
12351 bytes = fwrite (buffer, 1, bytes, file.get ());
12353 perror_with_name (local_file);
12356 discard_cleanups (close_cleanup);
12357 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
12358 remote_hostio_error (remote_errno);
12361 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
12362 do_cleanups (back_to);
12366 remote_file_delete (const char *remote_file, int from_tty)
12368 int retcode, remote_errno;
12369 struct remote_state *rs = get_remote_state ();
12371 if (!rs->remote_desc)
12372 error (_("command can only be used with remote target"));
12374 retcode = remote_hostio_unlink (find_target_at (process_stratum),
12375 NULL, remote_file, &remote_errno);
12377 remote_hostio_error (remote_errno);
12380 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
12384 remote_put_command (const char *args, int from_tty)
12387 error_no_arg (_("file to put"));
12389 gdb_argv argv (args);
12390 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12391 error (_("Invalid parameters to remote put"));
12393 remote_file_put (argv[0], argv[1], from_tty);
12397 remote_get_command (const char *args, int from_tty)
12400 error_no_arg (_("file to get"));
12402 gdb_argv argv (args);
12403 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12404 error (_("Invalid parameters to remote get"));
12406 remote_file_get (argv[0], argv[1], from_tty);
12410 remote_delete_command (const char *args, int from_tty)
12413 error_no_arg (_("file to delete"));
12415 gdb_argv argv (args);
12416 if (argv[0] == NULL || argv[1] != NULL)
12417 error (_("Invalid parameters to remote delete"));
12419 remote_file_delete (argv[0], from_tty);
12423 remote_command (const char *args, int from_tty)
12425 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
12429 remote_target::can_execute_reverse ()
12431 if (packet_support (PACKET_bs) == PACKET_ENABLE
12432 || packet_support (PACKET_bc) == PACKET_ENABLE)
12439 remote_target::supports_non_stop ()
12445 remote_target::supports_disable_randomization ()
12447 /* Only supported in extended mode. */
12452 remote_target::supports_multi_process ()
12454 struct remote_state *rs = get_remote_state ();
12456 return remote_multi_process_p (rs);
12460 remote_supports_cond_tracepoints ()
12462 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
12466 remote_target::supports_evaluation_of_breakpoint_conditions ()
12468 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
12472 remote_supports_fast_tracepoints ()
12474 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
12478 remote_supports_static_tracepoints ()
12480 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
12484 remote_supports_install_in_trace ()
12486 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
12490 remote_target::supports_enable_disable_tracepoint ()
12492 return (packet_support (PACKET_EnableDisableTracepoints_feature)
12497 remote_target::supports_string_tracing ()
12499 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
12503 remote_target::can_run_breakpoint_commands ()
12505 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
12509 remote_target::trace_init ()
12511 struct remote_state *rs = get_remote_state ();
12514 remote_get_noisy_reply ();
12515 if (strcmp (rs->buf, "OK") != 0)
12516 error (_("Target does not support this command."));
12519 /* Recursive routine to walk through command list including loops, and
12520 download packets for each command. */
12523 remote_download_command_source (int num, ULONGEST addr,
12524 struct command_line *cmds)
12526 struct remote_state *rs = get_remote_state ();
12527 struct command_line *cmd;
12529 for (cmd = cmds; cmd; cmd = cmd->next)
12531 QUIT; /* Allow user to bail out with ^C. */
12532 strcpy (rs->buf, "QTDPsrc:");
12533 encode_source_string (num, addr, "cmd", cmd->line,
12534 rs->buf + strlen (rs->buf),
12535 rs->buf_size - strlen (rs->buf));
12537 remote_get_noisy_reply ();
12538 if (strcmp (rs->buf, "OK"))
12539 warning (_("Target does not support source download."));
12541 if (cmd->control_type == while_control
12542 || cmd->control_type == while_stepping_control)
12544 remote_download_command_source (num, addr, *cmd->body_list);
12546 QUIT; /* Allow user to bail out with ^C. */
12547 strcpy (rs->buf, "QTDPsrc:");
12548 encode_source_string (num, addr, "cmd", "end",
12549 rs->buf + strlen (rs->buf),
12550 rs->buf_size - strlen (rs->buf));
12552 remote_get_noisy_reply ();
12553 if (strcmp (rs->buf, "OK"))
12554 warning (_("Target does not support source download."));
12560 remote_target::download_tracepoint (struct bp_location *loc)
12562 #define BUF_SIZE 2048
12566 char buf[BUF_SIZE];
12567 std::vector<std::string> tdp_actions;
12568 std::vector<std::string> stepping_actions;
12570 struct breakpoint *b = loc->owner;
12571 struct tracepoint *t = (struct tracepoint *) b;
12572 struct remote_state *rs = get_remote_state ();
12574 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
12576 tpaddr = loc->address;
12577 sprintf_vma (addrbuf, tpaddr);
12578 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
12579 addrbuf, /* address */
12580 (b->enable_state == bp_enabled ? 'E' : 'D'),
12581 t->step_count, t->pass_count);
12582 /* Fast tracepoints are mostly handled by the target, but we can
12583 tell the target how big of an instruction block should be moved
12585 if (b->type == bp_fast_tracepoint)
12587 /* Only test for support at download time; we may not know
12588 target capabilities at definition time. */
12589 if (remote_supports_fast_tracepoints ())
12591 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
12593 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
12594 gdb_insn_length (loc->gdbarch, tpaddr));
12596 /* If it passed validation at definition but fails now,
12597 something is very wrong. */
12598 internal_error (__FILE__, __LINE__,
12599 _("Fast tracepoint not "
12600 "valid during download"));
12603 /* Fast tracepoints are functionally identical to regular
12604 tracepoints, so don't take lack of support as a reason to
12605 give up on the trace run. */
12606 warning (_("Target does not support fast tracepoints, "
12607 "downloading %d as regular tracepoint"), b->number);
12609 else if (b->type == bp_static_tracepoint)
12611 /* Only test for support at download time; we may not know
12612 target capabilities at definition time. */
12613 if (remote_supports_static_tracepoints ())
12615 struct static_tracepoint_marker marker;
12617 if (target_static_tracepoint_marker_at (tpaddr, &marker))
12618 strcat (buf, ":S");
12620 error (_("Static tracepoint not valid during download"));
12623 /* Fast tracepoints are functionally identical to regular
12624 tracepoints, so don't take lack of support as a reason
12625 to give up on the trace run. */
12626 error (_("Target does not support static tracepoints"));
12628 /* If the tracepoint has a conditional, make it into an agent
12629 expression and append to the definition. */
12632 /* Only test support at download time, we may not know target
12633 capabilities at definition time. */
12634 if (remote_supports_cond_tracepoints ())
12636 agent_expr_up aexpr = gen_eval_for_expr (tpaddr, loc->cond.get ());
12637 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
12639 pkt = buf + strlen (buf);
12640 for (int ndx = 0; ndx < aexpr->len; ++ndx)
12641 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
12645 warning (_("Target does not support conditional tracepoints, "
12646 "ignoring tp %d cond"), b->number);
12649 if (b->commands || *default_collect)
12652 remote_get_noisy_reply ();
12653 if (strcmp (rs->buf, "OK"))
12654 error (_("Target does not support tracepoints."));
12656 /* do_single_steps (t); */
12657 for (auto action_it = tdp_actions.begin ();
12658 action_it != tdp_actions.end (); action_it++)
12660 QUIT; /* Allow user to bail out with ^C. */
12662 bool has_more = (action_it != tdp_actions.end ()
12663 || !stepping_actions.empty ());
12665 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
12666 b->number, addrbuf, /* address */
12667 action_it->c_str (),
12668 has_more ? '-' : 0);
12670 remote_get_noisy_reply ();
12671 if (strcmp (rs->buf, "OK"))
12672 error (_("Error on target while setting tracepoints."));
12675 for (auto action_it = stepping_actions.begin ();
12676 action_it != stepping_actions.end (); action_it++)
12678 QUIT; /* Allow user to bail out with ^C. */
12680 bool is_first = action_it == stepping_actions.begin ();
12681 bool has_more = action_it != stepping_actions.end ();
12683 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
12684 b->number, addrbuf, /* address */
12685 is_first ? "S" : "",
12686 action_it->c_str (),
12687 has_more ? "-" : "");
12689 remote_get_noisy_reply ();
12690 if (strcmp (rs->buf, "OK"))
12691 error (_("Error on target while setting tracepoints."));
12694 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
12696 if (b->location != NULL)
12698 strcpy (buf, "QTDPsrc:");
12699 encode_source_string (b->number, loc->address, "at",
12700 event_location_to_string (b->location.get ()),
12701 buf + strlen (buf), 2048 - strlen (buf));
12703 remote_get_noisy_reply ();
12704 if (strcmp (rs->buf, "OK"))
12705 warning (_("Target does not support source download."));
12707 if (b->cond_string)
12709 strcpy (buf, "QTDPsrc:");
12710 encode_source_string (b->number, loc->address,
12711 "cond", b->cond_string, buf + strlen (buf),
12712 2048 - strlen (buf));
12714 remote_get_noisy_reply ();
12715 if (strcmp (rs->buf, "OK"))
12716 warning (_("Target does not support source download."));
12718 remote_download_command_source (b->number, loc->address,
12719 breakpoint_commands (b));
12724 remote_target::can_download_tracepoint ()
12726 struct remote_state *rs = get_remote_state ();
12727 struct trace_status *ts;
12730 /* Don't try to install tracepoints until we've relocated our
12731 symbols, and fetched and merged the target's tracepoint list with
12733 if (rs->starting_up)
12736 ts = current_trace_status ();
12737 status = get_trace_status (ts);
12739 if (status == -1 || !ts->running_known || !ts->running)
12742 /* If we are in a tracing experiment, but remote stub doesn't support
12743 installing tracepoint in trace, we have to return. */
12744 if (!remote_supports_install_in_trace ())
12752 remote_target::download_trace_state_variable (const trace_state_variable &tsv)
12754 struct remote_state *rs = get_remote_state ();
12757 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
12758 tsv.number, phex ((ULONGEST) tsv.initial_value, 8),
12760 p = rs->buf + strlen (rs->buf);
12761 if ((p - rs->buf) + tsv.name.length () * 2 >= get_remote_packet_size ())
12762 error (_("Trace state variable name too long for tsv definition packet"));
12763 p += 2 * bin2hex ((gdb_byte *) (tsv.name.data ()), p, tsv.name.length ());
12766 remote_get_noisy_reply ();
12767 if (*rs->buf == '\0')
12768 error (_("Target does not support this command."));
12769 if (strcmp (rs->buf, "OK") != 0)
12770 error (_("Error on target while downloading trace state variable."));
12774 remote_target::enable_tracepoint (struct bp_location *location)
12776 struct remote_state *rs = get_remote_state ();
12779 sprintf_vma (addr_buf, location->address);
12780 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
12781 location->owner->number, addr_buf);
12783 remote_get_noisy_reply ();
12784 if (*rs->buf == '\0')
12785 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
12786 if (strcmp (rs->buf, "OK") != 0)
12787 error (_("Error on target while enabling tracepoint."));
12791 remote_target::disable_tracepoint (struct bp_location *location)
12793 struct remote_state *rs = get_remote_state ();
12796 sprintf_vma (addr_buf, location->address);
12797 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
12798 location->owner->number, addr_buf);
12800 remote_get_noisy_reply ();
12801 if (*rs->buf == '\0')
12802 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
12803 if (strcmp (rs->buf, "OK") != 0)
12804 error (_("Error on target while disabling tracepoint."));
12808 remote_target::trace_set_readonly_regions ()
12812 bfd_size_type size;
12818 return; /* No information to give. */
12820 struct remote_state *rs = get_remote_state ();
12822 strcpy (rs->buf, "QTro");
12823 offset = strlen (rs->buf);
12824 for (s = exec_bfd->sections; s; s = s->next)
12826 char tmp1[40], tmp2[40];
12829 if ((s->flags & SEC_LOAD) == 0 ||
12830 /* (s->flags & SEC_CODE) == 0 || */
12831 (s->flags & SEC_READONLY) == 0)
12835 vma = bfd_get_section_vma (abfd, s);
12836 size = bfd_get_section_size (s);
12837 sprintf_vma (tmp1, vma);
12838 sprintf_vma (tmp2, vma + size);
12839 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
12840 if (offset + sec_length + 1 > rs->buf_size)
12842 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
12844 Too many sections for read-only sections definition packet."));
12847 xsnprintf (rs->buf + offset, rs->buf_size - offset, ":%s,%s",
12849 offset += sec_length;
12854 getpkt (&rs->buf, &rs->buf_size, 0);
12859 remote_target::trace_start ()
12861 struct remote_state *rs = get_remote_state ();
12863 putpkt ("QTStart");
12864 remote_get_noisy_reply ();
12865 if (*rs->buf == '\0')
12866 error (_("Target does not support this command."));
12867 if (strcmp (rs->buf, "OK") != 0)
12868 error (_("Bogus reply from target: %s"), rs->buf);
12872 remote_target::get_trace_status (struct trace_status *ts)
12874 /* Initialize it just to avoid a GCC false warning. */
12876 /* FIXME we need to get register block size some other way. */
12877 extern int trace_regblock_size;
12878 enum packet_result result;
12879 struct remote_state *rs = get_remote_state ();
12881 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
12884 trace_regblock_size
12885 = get_remote_arch_state (target_gdbarch ())->sizeof_g_packet;
12887 putpkt ("qTStatus");
12891 p = remote_get_noisy_reply ();
12893 CATCH (ex, RETURN_MASK_ERROR)
12895 if (ex.error != TARGET_CLOSE_ERROR)
12897 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
12900 throw_exception (ex);
12904 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
12906 /* If the remote target doesn't do tracing, flag it. */
12907 if (result == PACKET_UNKNOWN)
12910 /* We're working with a live target. */
12911 ts->filename = NULL;
12914 error (_("Bogus trace status reply from target: %s"), rs->buf);
12916 /* Function 'parse_trace_status' sets default value of each field of
12917 'ts' at first, so we don't have to do it here. */
12918 parse_trace_status (p, ts);
12920 return ts->running;
12924 remote_target::get_tracepoint_status (struct breakpoint *bp,
12925 struct uploaded_tp *utp)
12927 struct remote_state *rs = get_remote_state ();
12929 struct bp_location *loc;
12930 struct tracepoint *tp = (struct tracepoint *) bp;
12931 size_t size = get_remote_packet_size ();
12936 tp->traceframe_usage = 0;
12937 for (loc = tp->loc; loc; loc = loc->next)
12939 /* If the tracepoint was never downloaded, don't go asking for
12941 if (tp->number_on_target == 0)
12943 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
12944 phex_nz (loc->address, 0));
12946 reply = remote_get_noisy_reply ();
12947 if (reply && *reply)
12950 parse_tracepoint_status (reply + 1, bp, utp);
12956 utp->hit_count = 0;
12957 utp->traceframe_usage = 0;
12958 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
12959 phex_nz (utp->addr, 0));
12961 reply = remote_get_noisy_reply ();
12962 if (reply && *reply)
12965 parse_tracepoint_status (reply + 1, bp, utp);
12971 remote_target::trace_stop ()
12973 struct remote_state *rs = get_remote_state ();
12976 remote_get_noisy_reply ();
12977 if (*rs->buf == '\0')
12978 error (_("Target does not support this command."));
12979 if (strcmp (rs->buf, "OK") != 0)
12980 error (_("Bogus reply from target: %s"), rs->buf);
12984 remote_target::trace_find (enum trace_find_type type, int num,
12985 CORE_ADDR addr1, CORE_ADDR addr2,
12988 struct remote_state *rs = get_remote_state ();
12989 char *endbuf = rs->buf + get_remote_packet_size ();
12991 int target_frameno = -1, target_tracept = -1;
12993 /* Lookups other than by absolute frame number depend on the current
12994 trace selected, so make sure it is correct on the remote end
12996 if (type != tfind_number)
12997 set_remote_traceframe ();
13000 strcpy (p, "QTFrame:");
13001 p = strchr (p, '\0');
13005 xsnprintf (p, endbuf - p, "%x", num);
13008 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
13011 xsnprintf (p, endbuf - p, "tdp:%x", num);
13014 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
13015 phex_nz (addr2, 0));
13017 case tfind_outside:
13018 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
13019 phex_nz (addr2, 0));
13022 error (_("Unknown trace find type %d"), type);
13026 reply = remote_get_noisy_reply ();
13027 if (*reply == '\0')
13028 error (_("Target does not support this command."));
13030 while (reply && *reply)
13035 target_frameno = (int) strtol (p, &reply, 16);
13037 error (_("Unable to parse trace frame number"));
13038 /* Don't update our remote traceframe number cache on failure
13039 to select a remote traceframe. */
13040 if (target_frameno == -1)
13045 target_tracept = (int) strtol (p, &reply, 16);
13047 error (_("Unable to parse tracepoint number"));
13049 case 'O': /* "OK"? */
13050 if (reply[1] == 'K' && reply[2] == '\0')
13053 error (_("Bogus reply from target: %s"), reply);
13056 error (_("Bogus reply from target: %s"), reply);
13059 *tpp = target_tracept;
13061 rs->remote_traceframe_number = target_frameno;
13062 return target_frameno;
13066 remote_target::get_trace_state_variable_value (int tsvnum, LONGEST *val)
13068 struct remote_state *rs = get_remote_state ();
13072 set_remote_traceframe ();
13074 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
13076 reply = remote_get_noisy_reply ();
13077 if (reply && *reply)
13081 unpack_varlen_hex (reply + 1, &uval);
13082 *val = (LONGEST) uval;
13090 remote_target::save_trace_data (const char *filename)
13092 struct remote_state *rs = get_remote_state ();
13096 strcpy (p, "QTSave:");
13098 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
13099 error (_("Remote file name too long for trace save packet"));
13100 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
13103 reply = remote_get_noisy_reply ();
13104 if (*reply == '\0')
13105 error (_("Target does not support this command."));
13106 if (strcmp (reply, "OK") != 0)
13107 error (_("Bogus reply from target: %s"), reply);
13111 /* This is basically a memory transfer, but needs to be its own packet
13112 because we don't know how the target actually organizes its trace
13113 memory, plus we want to be able to ask for as much as possible, but
13114 not be unhappy if we don't get as much as we ask for. */
13117 remote_target::get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
13119 struct remote_state *rs = get_remote_state ();
13125 strcpy (p, "qTBuffer:");
13127 p += hexnumstr (p, offset);
13129 p += hexnumstr (p, len);
13133 reply = remote_get_noisy_reply ();
13134 if (reply && *reply)
13136 /* 'l' by itself means we're at the end of the buffer and
13137 there is nothing more to get. */
13141 /* Convert the reply into binary. Limit the number of bytes to
13142 convert according to our passed-in buffer size, rather than
13143 what was returned in the packet; if the target is
13144 unexpectedly generous and gives us a bigger reply than we
13145 asked for, we don't want to crash. */
13146 rslt = hex2bin (reply, buf, len);
13150 /* Something went wrong, flag as an error. */
13155 remote_target::set_disconnected_tracing (int val)
13157 struct remote_state *rs = get_remote_state ();
13159 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
13163 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
13165 reply = remote_get_noisy_reply ();
13166 if (*reply == '\0')
13167 error (_("Target does not support this command."));
13168 if (strcmp (reply, "OK") != 0)
13169 error (_("Bogus reply from target: %s"), reply);
13172 warning (_("Target does not support disconnected tracing."));
13176 remote_target::core_of_thread (ptid_t ptid)
13178 struct thread_info *info = find_thread_ptid (ptid);
13180 if (info != NULL && info->priv != NULL)
13181 return get_remote_thread_info (info)->core;
13187 remote_target::set_circular_trace_buffer (int val)
13189 struct remote_state *rs = get_remote_state ();
13192 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
13194 reply = remote_get_noisy_reply ();
13195 if (*reply == '\0')
13196 error (_("Target does not support this command."));
13197 if (strcmp (reply, "OK") != 0)
13198 error (_("Bogus reply from target: %s"), reply);
13202 remote_target::traceframe_info ()
13204 gdb::optional<gdb::char_vector> text
13205 = target_read_stralloc (target_stack, TARGET_OBJECT_TRACEFRAME_INFO,
13208 return parse_traceframe_info (text->data ());
13213 /* Handle the qTMinFTPILen packet. Returns the minimum length of
13214 instruction on which a fast tracepoint may be placed. Returns -1
13215 if the packet is not supported, and 0 if the minimum instruction
13216 length is unknown. */
13219 remote_target::get_min_fast_tracepoint_insn_len ()
13221 struct remote_state *rs = get_remote_state ();
13224 /* If we're not debugging a process yet, the IPA can't be
13226 if (!target_has_execution)
13229 /* Make sure the remote is pointing at the right process. */
13230 set_general_process ();
13232 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
13234 reply = remote_get_noisy_reply ();
13235 if (*reply == '\0')
13239 ULONGEST min_insn_len;
13241 unpack_varlen_hex (reply, &min_insn_len);
13243 return (int) min_insn_len;
13248 remote_target::set_trace_buffer_size (LONGEST val)
13250 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
13252 struct remote_state *rs = get_remote_state ();
13253 char *buf = rs->buf;
13254 char *endbuf = rs->buf + get_remote_packet_size ();
13255 enum packet_result result;
13257 gdb_assert (val >= 0 || val == -1);
13258 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
13259 /* Send -1 as literal "-1" to avoid host size dependency. */
13263 buf += hexnumstr (buf, (ULONGEST) -val);
13266 buf += hexnumstr (buf, (ULONGEST) val);
13269 remote_get_noisy_reply ();
13270 result = packet_ok (rs->buf,
13271 &remote_protocol_packets[PACKET_QTBuffer_size]);
13273 if (result != PACKET_OK)
13274 warning (_("Bogus reply from target: %s"), rs->buf);
13279 remote_target::set_trace_notes (const char *user, const char *notes,
13280 const char *stop_notes)
13282 struct remote_state *rs = get_remote_state ();
13284 char *buf = rs->buf;
13285 char *endbuf = rs->buf + get_remote_packet_size ();
13288 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
13291 buf += xsnprintf (buf, endbuf - buf, "user:");
13292 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
13298 buf += xsnprintf (buf, endbuf - buf, "notes:");
13299 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
13305 buf += xsnprintf (buf, endbuf - buf, "tstop:");
13306 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
13310 /* Ensure the buffer is terminated. */
13314 reply = remote_get_noisy_reply ();
13315 if (*reply == '\0')
13318 if (strcmp (reply, "OK") != 0)
13319 error (_("Bogus reply from target: %s"), reply);
13325 remote_target::use_agent (bool use)
13327 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
13329 struct remote_state *rs = get_remote_state ();
13331 /* If the stub supports QAgent. */
13332 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
13334 getpkt (&rs->buf, &rs->buf_size, 0);
13336 if (strcmp (rs->buf, "OK") == 0)
13347 remote_target::can_use_agent ()
13349 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
13352 struct btrace_target_info
13354 /* The ptid of the traced thread. */
13357 /* The obtained branch trace configuration. */
13358 struct btrace_config conf;
13361 /* Reset our idea of our target's btrace configuration. */
13364 remote_btrace_reset (void)
13366 struct remote_state *rs = get_remote_state ();
13368 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
13371 /* Synchronize the configuration with the target. */
13374 btrace_sync_conf (const struct btrace_config *conf)
13376 struct packet_config *packet;
13377 struct remote_state *rs;
13378 char *buf, *pos, *endbuf;
13380 rs = get_remote_state ();
13382 endbuf = buf + get_remote_packet_size ();
13384 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
13385 if (packet_config_support (packet) == PACKET_ENABLE
13386 && conf->bts.size != rs->btrace_config.bts.size)
13389 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13393 getpkt (&buf, &rs->buf_size, 0);
13395 if (packet_ok (buf, packet) == PACKET_ERROR)
13397 if (buf[0] == 'E' && buf[1] == '.')
13398 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
13400 error (_("Failed to configure the BTS buffer size."));
13403 rs->btrace_config.bts.size = conf->bts.size;
13406 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
13407 if (packet_config_support (packet) == PACKET_ENABLE
13408 && conf->pt.size != rs->btrace_config.pt.size)
13411 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13415 getpkt (&buf, &rs->buf_size, 0);
13417 if (packet_ok (buf, packet) == PACKET_ERROR)
13419 if (buf[0] == 'E' && buf[1] == '.')
13420 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
13422 error (_("Failed to configure the trace buffer size."));
13425 rs->btrace_config.pt.size = conf->pt.size;
13429 /* Read the current thread's btrace configuration from the target and
13430 store it into CONF. */
13433 btrace_read_config (struct btrace_config *conf)
13435 gdb::optional<gdb::char_vector> xml
13436 = target_read_stralloc (target_stack, TARGET_OBJECT_BTRACE_CONF, "");
13438 parse_xml_btrace_conf (conf, xml->data ());
13441 /* Maybe reopen target btrace. */
13444 remote_btrace_maybe_reopen (void)
13446 struct remote_state *rs = get_remote_state ();
13447 struct thread_info *tp;
13448 int btrace_target_pushed = 0;
13451 scoped_restore_current_thread restore_thread;
13453 ALL_NON_EXITED_THREADS (tp)
13455 set_general_thread (tp->ptid);
13457 memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
13458 btrace_read_config (&rs->btrace_config);
13460 if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
13463 #if !defined (HAVE_LIBIPT)
13464 if (rs->btrace_config.format == BTRACE_FORMAT_PT)
13469 warning (_("Target is recording using Intel Processor Trace "
13470 "but support was disabled at compile time."));
13475 #endif /* !defined (HAVE_LIBIPT) */
13477 /* Push target, once, but before anything else happens. This way our
13478 changes to the threads will be cleaned up by unpushing the target
13479 in case btrace_read_config () throws. */
13480 if (!btrace_target_pushed)
13482 btrace_target_pushed = 1;
13483 record_btrace_push_target ();
13484 printf_filtered (_("Target is recording using %s.\n"),
13485 btrace_format_string (rs->btrace_config.format));
13488 tp->btrace.target = XCNEW (struct btrace_target_info);
13489 tp->btrace.target->ptid = tp->ptid;
13490 tp->btrace.target->conf = rs->btrace_config;
13494 /* Enable branch tracing. */
13496 struct btrace_target_info *
13497 remote_target::enable_btrace (ptid_t ptid, const struct btrace_config *conf)
13499 struct btrace_target_info *tinfo = NULL;
13500 struct packet_config *packet = NULL;
13501 struct remote_state *rs = get_remote_state ();
13502 char *buf = rs->buf;
13503 char *endbuf = rs->buf + get_remote_packet_size ();
13505 switch (conf->format)
13507 case BTRACE_FORMAT_BTS:
13508 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
13511 case BTRACE_FORMAT_PT:
13512 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
13516 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
13517 error (_("Target does not support branch tracing."));
13519 btrace_sync_conf (conf);
13521 set_general_thread (ptid);
13523 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13525 getpkt (&rs->buf, &rs->buf_size, 0);
13527 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13529 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13530 error (_("Could not enable branch tracing for %s: %s"),
13531 target_pid_to_str (ptid), rs->buf + 2);
13533 error (_("Could not enable branch tracing for %s."),
13534 target_pid_to_str (ptid));
13537 tinfo = XCNEW (struct btrace_target_info);
13538 tinfo->ptid = ptid;
13540 /* If we fail to read the configuration, we lose some information, but the
13541 tracing itself is not impacted. */
13544 btrace_read_config (&tinfo->conf);
13546 CATCH (err, RETURN_MASK_ERROR)
13548 if (err.message != NULL)
13549 warning ("%s", err.message);
13556 /* Disable branch tracing. */
13559 remote_target::disable_btrace (struct btrace_target_info *tinfo)
13561 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
13562 struct remote_state *rs = get_remote_state ();
13563 char *buf = rs->buf;
13564 char *endbuf = rs->buf + get_remote_packet_size ();
13566 if (packet_config_support (packet) != PACKET_ENABLE)
13567 error (_("Target does not support branch tracing."));
13569 set_general_thread (tinfo->ptid);
13571 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13573 getpkt (&rs->buf, &rs->buf_size, 0);
13575 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13577 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13578 error (_("Could not disable branch tracing for %s: %s"),
13579 target_pid_to_str (tinfo->ptid), rs->buf + 2);
13581 error (_("Could not disable branch tracing for %s."),
13582 target_pid_to_str (tinfo->ptid));
13588 /* Teardown branch tracing. */
13591 remote_target::teardown_btrace (struct btrace_target_info *tinfo)
13593 /* We must not talk to the target during teardown. */
13597 /* Read the branch trace. */
13600 remote_target::read_btrace (struct btrace_data *btrace,
13601 struct btrace_target_info *tinfo,
13602 enum btrace_read_type type)
13604 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
13607 if (packet_config_support (packet) != PACKET_ENABLE)
13608 error (_("Target does not support branch tracing."));
13610 #if !defined(HAVE_LIBEXPAT)
13611 error (_("Cannot process branch tracing result. XML parsing not supported."));
13616 case BTRACE_READ_ALL:
13619 case BTRACE_READ_NEW:
13622 case BTRACE_READ_DELTA:
13626 internal_error (__FILE__, __LINE__,
13627 _("Bad branch tracing read type: %u."),
13628 (unsigned int) type);
13631 gdb::optional<gdb::char_vector> xml
13632 = target_read_stralloc (target_stack, TARGET_OBJECT_BTRACE, annex);
13634 return BTRACE_ERR_UNKNOWN;
13636 parse_xml_btrace (btrace, xml->data ());
13638 return BTRACE_ERR_NONE;
13641 const struct btrace_config *
13642 remote_target::btrace_conf (const struct btrace_target_info *tinfo)
13644 return &tinfo->conf;
13648 remote_target::augmented_libraries_svr4_read ()
13650 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
13654 /* Implementation of to_load. */
13657 remote_target::load (const char *name, int from_tty)
13659 generic_load (name, from_tty);
13662 /* Accepts an integer PID; returns a string representing a file that
13663 can be opened on the remote side to get the symbols for the child
13664 process. Returns NULL if the operation is not supported. */
13667 remote_target::pid_to_exec_file (int pid)
13669 static gdb::optional<gdb::char_vector> filename;
13670 struct inferior *inf;
13671 char *annex = NULL;
13673 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
13676 inf = find_inferior_pid (pid);
13678 internal_error (__FILE__, __LINE__,
13679 _("not currently attached to process %d"), pid);
13681 if (!inf->fake_pid_p)
13683 const int annex_size = 9;
13685 annex = (char *) alloca (annex_size);
13686 xsnprintf (annex, annex_size, "%x", pid);
13689 filename = target_read_stralloc (target_stack,
13690 TARGET_OBJECT_EXEC_FILE, annex);
13692 return filename ? filename->data () : nullptr;
13695 /* Implement the to_can_do_single_step target_ops method. */
13698 remote_target::can_do_single_step ()
13700 /* We can only tell whether target supports single step or not by
13701 supported s and S vCont actions if the stub supports vContSupported
13702 feature. If the stub doesn't support vContSupported feature,
13703 we have conservatively to think target doesn't supports single
13705 if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
13707 struct remote_state *rs = get_remote_state ();
13709 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
13710 remote_vcont_probe (rs);
13712 return rs->supports_vCont.s && rs->supports_vCont.S;
13718 /* Implementation of the to_execution_direction method for the remote
13721 enum exec_direction_kind
13722 remote_target::execution_direction ()
13724 struct remote_state *rs = get_remote_state ();
13726 return rs->last_resume_exec_dir;
13729 /* Return pointer to the thread_info struct which corresponds to
13730 THREAD_HANDLE (having length HANDLE_LEN). */
13733 remote_target::thread_handle_to_thread_info (const gdb_byte *thread_handle,
13737 struct thread_info *tp;
13739 ALL_NON_EXITED_THREADS (tp)
13741 remote_thread_info *priv = get_remote_thread_info (tp);
13743 if (tp->inf == inf && priv != NULL)
13745 if (handle_len != priv->thread_handle.size ())
13746 error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
13747 handle_len, priv->thread_handle.size ());
13748 if (memcmp (thread_handle, priv->thread_handle.data (),
13758 remote_target::can_async_p ()
13760 struct remote_state *rs = get_remote_state ();
13762 /* We don't go async if the user has explicitly prevented it with the
13763 "maint set target-async" command. */
13764 if (!target_async_permitted)
13767 /* We're async whenever the serial device is. */
13768 return serial_can_async_p (rs->remote_desc);
13772 remote_target::is_async_p ()
13774 struct remote_state *rs = get_remote_state ();
13776 if (!target_async_permitted)
13777 /* We only enable async when the user specifically asks for it. */
13780 /* We're async whenever the serial device is. */
13781 return serial_is_async_p (rs->remote_desc);
13784 /* Pass the SERIAL event on and up to the client. One day this code
13785 will be able to delay notifying the client of an event until the
13786 point where an entire packet has been received. */
13788 static serial_event_ftype remote_async_serial_handler;
13791 remote_async_serial_handler (struct serial *scb, void *context)
13793 /* Don't propogate error information up to the client. Instead let
13794 the client find out about the error by querying the target. */
13795 inferior_event_handler (INF_REG_EVENT, NULL);
13799 remote_async_inferior_event_handler (gdb_client_data data)
13801 inferior_event_handler (INF_REG_EVENT, NULL);
13805 remote_target::async (int enable)
13807 struct remote_state *rs = get_remote_state ();
13811 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
13813 /* If there are pending events in the stop reply queue tell the
13814 event loop to process them. */
13815 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
13816 mark_async_event_handler (remote_async_inferior_event_token);
13817 /* For simplicity, below we clear the pending events token
13818 without remembering whether it is marked, so here we always
13819 mark it. If there's actually no pending notification to
13820 process, this ends up being a no-op (other than a spurious
13821 event-loop wakeup). */
13822 if (target_is_non_stop_p ())
13823 mark_async_event_handler (rs->notif_state->get_pending_events_token);
13827 serial_async (rs->remote_desc, NULL, NULL);
13828 /* If the core is disabling async, it doesn't want to be
13829 disturbed with target events. Clear all async event sources
13831 clear_async_event_handler (remote_async_inferior_event_token);
13832 if (target_is_non_stop_p ())
13833 clear_async_event_handler (rs->notif_state->get_pending_events_token);
13837 /* Implementation of the to_thread_events method. */
13840 remote_target::thread_events (int enable)
13842 struct remote_state *rs = get_remote_state ();
13843 size_t size = get_remote_packet_size ();
13845 if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
13848 xsnprintf (rs->buf, size, "QThreadEvents:%x", enable ? 1 : 0);
13850 getpkt (&rs->buf, &rs->buf_size, 0);
13852 switch (packet_ok (rs->buf,
13853 &remote_protocol_packets[PACKET_QThreadEvents]))
13856 if (strcmp (rs->buf, "OK") != 0)
13857 error (_("Remote refused setting thread events: %s"), rs->buf);
13860 warning (_("Remote failure reply: %s"), rs->buf);
13862 case PACKET_UNKNOWN:
13868 set_remote_cmd (const char *args, int from_tty)
13870 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
13874 show_remote_cmd (const char *args, int from_tty)
13876 /* We can't just use cmd_show_list here, because we want to skip
13877 the redundant "show remote Z-packet" and the legacy aliases. */
13878 struct cmd_list_element *list = remote_show_cmdlist;
13879 struct ui_out *uiout = current_uiout;
13881 ui_out_emit_tuple tuple_emitter (uiout, "showlist");
13882 for (; list != NULL; list = list->next)
13883 if (strcmp (list->name, "Z-packet") == 0)
13885 else if (list->type == not_set_cmd)
13886 /* Alias commands are exactly like the original, except they
13887 don't have the normal type. */
13891 ui_out_emit_tuple option_emitter (uiout, "option");
13893 uiout->field_string ("name", list->name);
13894 uiout->text (": ");
13895 if (list->type == show_cmd)
13896 do_show_command (NULL, from_tty, list);
13898 cmd_func (list, NULL, from_tty);
13903 /* Function to be called whenever a new objfile (shlib) is detected. */
13905 remote_new_objfile (struct objfile *objfile)
13907 struct remote_state *rs = get_remote_state ();
13909 if (rs->remote_desc != 0) /* Have a remote connection. */
13910 remote_check_symbols ();
13913 /* Pull all the tracepoints defined on the target and create local
13914 data structures representing them. We don't want to create real
13915 tracepoints yet, we don't want to mess up the user's existing
13919 remote_target::upload_tracepoints (struct uploaded_tp **utpp)
13921 struct remote_state *rs = get_remote_state ();
13924 /* Ask for a first packet of tracepoint definition. */
13926 getpkt (&rs->buf, &rs->buf_size, 0);
13928 while (*p && *p != 'l')
13930 parse_tracepoint_definition (p, utpp);
13931 /* Ask for another packet of tracepoint definition. */
13933 getpkt (&rs->buf, &rs->buf_size, 0);
13940 remote_target::upload_trace_state_variables (struct uploaded_tsv **utsvp)
13942 struct remote_state *rs = get_remote_state ();
13945 /* Ask for a first packet of variable definition. */
13947 getpkt (&rs->buf, &rs->buf_size, 0);
13949 while (*p && *p != 'l')
13951 parse_tsv_definition (p, utsvp);
13952 /* Ask for another packet of variable definition. */
13954 getpkt (&rs->buf, &rs->buf_size, 0);
13960 /* The "set/show range-stepping" show hook. */
13963 show_range_stepping (struct ui_file *file, int from_tty,
13964 struct cmd_list_element *c,
13967 fprintf_filtered (file,
13968 _("Debugger's willingness to use range stepping "
13969 "is %s.\n"), value);
13972 /* The "set/show range-stepping" set hook. */
13975 set_range_stepping (const char *ignore_args, int from_tty,
13976 struct cmd_list_element *c)
13978 struct remote_state *rs = get_remote_state ();
13980 /* Whene enabling, check whether range stepping is actually
13981 supported by the target, and warn if not. */
13982 if (use_range_stepping)
13984 if (rs->remote_desc != NULL)
13986 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
13987 remote_vcont_probe (rs);
13989 if (packet_support (PACKET_vCont) == PACKET_ENABLE
13990 && rs->supports_vCont.r)
13994 warning (_("Range stepping is not supported by the current target"));
13999 _initialize_remote (void)
14001 struct cmd_list_element *cmd;
14002 const char *cmd_name;
14004 /* architecture specific data */
14005 remote_gdbarch_data_handle =
14006 gdbarch_data_register_post_init (init_remote_state);
14007 remote_g_packet_data_handle =
14008 gdbarch_data_register_pre_init (remote_g_packet_data_init);
14011 = register_program_space_data_with_cleanup (NULL,
14012 remote_pspace_data_cleanup);
14014 /* Initialize the per-target state. At the moment there is only one
14015 of these, not one per target. Only one target is active at a
14017 remote_state = new_remote_state ();
14019 add_target (remote_target_info, remote_target::open);
14020 add_target (extended_remote_target_info, extended_remote_target::open);
14022 /* Hook into new objfile notification. */
14023 gdb::observers::new_objfile.attach (remote_new_objfile);
14024 /* We're no longer interested in notification events of an inferior
14026 gdb::observers::inferior_exit.attach (discard_pending_stop_replies);
14029 init_remote_threadtests ();
14032 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
14033 /* set/show remote ... */
14035 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
14036 Remote protocol specific variables\n\
14037 Configure various remote-protocol specific variables such as\n\
14038 the packets being used"),
14039 &remote_set_cmdlist, "set remote ",
14040 0 /* allow-unknown */, &setlist);
14041 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
14042 Remote protocol specific variables\n\
14043 Configure various remote-protocol specific variables such as\n\
14044 the packets being used"),
14045 &remote_show_cmdlist, "show remote ",
14046 0 /* allow-unknown */, &showlist);
14048 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
14049 Compare section data on target to the exec file.\n\
14050 Argument is a single section name (default: all loaded sections).\n\
14051 To compare only read-only loaded sections, specify the -r option."),
14054 add_cmd ("packet", class_maintenance, packet_command, _("\
14055 Send an arbitrary packet to a remote target.\n\
14056 maintenance packet TEXT\n\
14057 If GDB is talking to an inferior via the GDB serial protocol, then\n\
14058 this command sends the string TEXT to the inferior, and displays the\n\
14059 response packet. GDB supplies the initial `$' character, and the\n\
14060 terminating `#' character and checksum."),
14063 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
14064 Set whether to send break if interrupted."), _("\
14065 Show whether to send break if interrupted."), _("\
14066 If set, a break, instead of a cntrl-c, is sent to the remote target."),
14067 set_remotebreak, show_remotebreak,
14068 &setlist, &showlist);
14069 cmd_name = "remotebreak";
14070 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
14071 deprecate_cmd (cmd, "set remote interrupt-sequence");
14072 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
14073 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
14074 deprecate_cmd (cmd, "show remote interrupt-sequence");
14076 add_setshow_enum_cmd ("interrupt-sequence", class_support,
14077 interrupt_sequence_modes, &interrupt_sequence_mode,
14079 Set interrupt sequence to remote target."), _("\
14080 Show interrupt sequence to remote target."), _("\
14081 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
14082 NULL, show_interrupt_sequence,
14083 &remote_set_cmdlist,
14084 &remote_show_cmdlist);
14086 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
14087 &interrupt_on_connect, _("\
14088 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
14089 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
14090 If set, interrupt sequence is sent to remote target."),
14092 &remote_set_cmdlist, &remote_show_cmdlist);
14094 /* Install commands for configuring memory read/write packets. */
14096 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
14097 Set the maximum number of bytes per memory write packet (deprecated)."),
14099 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
14100 Show the maximum number of bytes per memory write packet (deprecated)."),
14102 add_cmd ("memory-write-packet-size", no_class,
14103 set_memory_write_packet_size, _("\
14104 Set the maximum number of bytes per memory-write packet.\n\
14105 Specify the number of bytes in a packet or 0 (zero) for the\n\
14106 default packet size. The actual limit is further reduced\n\
14107 dependent on the target. Specify ``fixed'' to disable the\n\
14108 further restriction and ``limit'' to enable that restriction."),
14109 &remote_set_cmdlist);
14110 add_cmd ("memory-read-packet-size", no_class,
14111 set_memory_read_packet_size, _("\
14112 Set the maximum number of bytes per memory-read packet.\n\
14113 Specify the number of bytes in a packet or 0 (zero) for the\n\
14114 default packet size. The actual limit is further reduced\n\
14115 dependent on the target. Specify ``fixed'' to disable the\n\
14116 further restriction and ``limit'' to enable that restriction."),
14117 &remote_set_cmdlist);
14118 add_cmd ("memory-write-packet-size", no_class,
14119 show_memory_write_packet_size,
14120 _("Show the maximum number of bytes per memory-write packet."),
14121 &remote_show_cmdlist);
14122 add_cmd ("memory-read-packet-size", no_class,
14123 show_memory_read_packet_size,
14124 _("Show the maximum number of bytes per memory-read packet."),
14125 &remote_show_cmdlist);
14127 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
14128 &remote_hw_watchpoint_limit, _("\
14129 Set the maximum number of target hardware watchpoints."), _("\
14130 Show the maximum number of target hardware watchpoints."), _("\
14131 Specify a negative limit for unlimited."),
14132 NULL, NULL, /* FIXME: i18n: The maximum
14133 number of target hardware
14134 watchpoints is %s. */
14135 &remote_set_cmdlist, &remote_show_cmdlist);
14136 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
14137 &remote_hw_watchpoint_length_limit, _("\
14138 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
14139 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
14140 Specify a negative limit for unlimited."),
14141 NULL, NULL, /* FIXME: i18n: The maximum
14142 length (in bytes) of a target
14143 hardware watchpoint is %s. */
14144 &remote_set_cmdlist, &remote_show_cmdlist);
14145 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
14146 &remote_hw_breakpoint_limit, _("\
14147 Set the maximum number of target hardware breakpoints."), _("\
14148 Show the maximum number of target hardware breakpoints."), _("\
14149 Specify a negative limit for unlimited."),
14150 NULL, NULL, /* FIXME: i18n: The maximum
14151 number of target hardware
14152 breakpoints is %s. */
14153 &remote_set_cmdlist, &remote_show_cmdlist);
14155 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
14156 &remote_address_size, _("\
14157 Set the maximum size of the address (in bits) in a memory packet."), _("\
14158 Show the maximum size of the address (in bits) in a memory packet."), NULL,
14160 NULL, /* FIXME: i18n: */
14161 &setlist, &showlist);
14163 init_all_packet_configs ();
14165 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
14166 "X", "binary-download", 1);
14168 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
14169 "vCont", "verbose-resume", 0);
14171 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
14172 "QPassSignals", "pass-signals", 0);
14174 add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
14175 "QCatchSyscalls", "catch-syscalls", 0);
14177 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
14178 "QProgramSignals", "program-signals", 0);
14180 add_packet_config_cmd (&remote_protocol_packets[PACKET_QSetWorkingDir],
14181 "QSetWorkingDir", "set-working-dir", 0);
14183 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartupWithShell],
14184 "QStartupWithShell", "startup-with-shell", 0);
14186 add_packet_config_cmd (&remote_protocol_packets
14187 [PACKET_QEnvironmentHexEncoded],
14188 "QEnvironmentHexEncoded", "environment-hex-encoded",
14191 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentReset],
14192 "QEnvironmentReset", "environment-reset",
14195 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentUnset],
14196 "QEnvironmentUnset", "environment-unset",
14199 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
14200 "qSymbol", "symbol-lookup", 0);
14202 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
14203 "P", "set-register", 1);
14205 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
14206 "p", "fetch-register", 1);
14208 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
14209 "Z0", "software-breakpoint", 0);
14211 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
14212 "Z1", "hardware-breakpoint", 0);
14214 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
14215 "Z2", "write-watchpoint", 0);
14217 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
14218 "Z3", "read-watchpoint", 0);
14220 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
14221 "Z4", "access-watchpoint", 0);
14223 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
14224 "qXfer:auxv:read", "read-aux-vector", 0);
14226 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
14227 "qXfer:exec-file:read", "pid-to-exec-file", 0);
14229 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
14230 "qXfer:features:read", "target-features", 0);
14232 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
14233 "qXfer:libraries:read", "library-info", 0);
14235 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
14236 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
14238 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
14239 "qXfer:memory-map:read", "memory-map", 0);
14241 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
14242 "qXfer:spu:read", "read-spu-object", 0);
14244 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
14245 "qXfer:spu:write", "write-spu-object", 0);
14247 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
14248 "qXfer:osdata:read", "osdata", 0);
14250 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
14251 "qXfer:threads:read", "threads", 0);
14253 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
14254 "qXfer:siginfo:read", "read-siginfo-object", 0);
14256 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
14257 "qXfer:siginfo:write", "write-siginfo-object", 0);
14259 add_packet_config_cmd
14260 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
14261 "qXfer:traceframe-info:read", "traceframe-info", 0);
14263 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
14264 "qXfer:uib:read", "unwind-info-block", 0);
14266 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
14267 "qGetTLSAddr", "get-thread-local-storage-address",
14270 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
14271 "qGetTIBAddr", "get-thread-information-block-address",
14274 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
14275 "bc", "reverse-continue", 0);
14277 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
14278 "bs", "reverse-step", 0);
14280 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
14281 "qSupported", "supported-packets", 0);
14283 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
14284 "qSearch:memory", "search-memory", 0);
14286 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
14287 "qTStatus", "trace-status", 0);
14289 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
14290 "vFile:setfs", "hostio-setfs", 0);
14292 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
14293 "vFile:open", "hostio-open", 0);
14295 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
14296 "vFile:pread", "hostio-pread", 0);
14298 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
14299 "vFile:pwrite", "hostio-pwrite", 0);
14301 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
14302 "vFile:close", "hostio-close", 0);
14304 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
14305 "vFile:unlink", "hostio-unlink", 0);
14307 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
14308 "vFile:readlink", "hostio-readlink", 0);
14310 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
14311 "vFile:fstat", "hostio-fstat", 0);
14313 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
14314 "vAttach", "attach", 0);
14316 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
14319 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
14320 "QStartNoAckMode", "noack", 0);
14322 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
14323 "vKill", "kill", 0);
14325 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
14326 "qAttached", "query-attached", 0);
14328 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
14329 "ConditionalTracepoints",
14330 "conditional-tracepoints", 0);
14332 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
14333 "ConditionalBreakpoints",
14334 "conditional-breakpoints", 0);
14336 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
14337 "BreakpointCommands",
14338 "breakpoint-commands", 0);
14340 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
14341 "FastTracepoints", "fast-tracepoints", 0);
14343 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
14344 "TracepointSource", "TracepointSource", 0);
14346 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
14347 "QAllow", "allow", 0);
14349 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
14350 "StaticTracepoints", "static-tracepoints", 0);
14352 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
14353 "InstallInTrace", "install-in-trace", 0);
14355 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
14356 "qXfer:statictrace:read", "read-sdata-object", 0);
14358 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
14359 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
14361 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
14362 "QDisableRandomization", "disable-randomization", 0);
14364 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
14365 "QAgent", "agent", 0);
14367 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
14368 "QTBuffer:size", "trace-buffer-size", 0);
14370 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
14371 "Qbtrace:off", "disable-btrace", 0);
14373 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
14374 "Qbtrace:bts", "enable-btrace-bts", 0);
14376 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
14377 "Qbtrace:pt", "enable-btrace-pt", 0);
14379 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
14380 "qXfer:btrace", "read-btrace", 0);
14382 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
14383 "qXfer:btrace-conf", "read-btrace-conf", 0);
14385 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
14386 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
14388 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
14389 "multiprocess-feature", "multiprocess-feature", 0);
14391 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
14392 "swbreak-feature", "swbreak-feature", 0);
14394 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
14395 "hwbreak-feature", "hwbreak-feature", 0);
14397 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
14398 "fork-event-feature", "fork-event-feature", 0);
14400 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
14401 "vfork-event-feature", "vfork-event-feature", 0);
14403 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
14404 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
14406 add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
14407 "vContSupported", "verbose-resume-supported", 0);
14409 add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
14410 "exec-event-feature", "exec-event-feature", 0);
14412 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
14413 "vCtrlC", "ctrl-c", 0);
14415 add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
14416 "QThreadEvents", "thread-events", 0);
14418 add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
14419 "N stop reply", "no-resumed-stop-reply", 0);
14421 /* Assert that we've registered "set remote foo-packet" commands
14422 for all packet configs. */
14426 for (i = 0; i < PACKET_MAX; i++)
14428 /* Ideally all configs would have a command associated. Some
14429 still don't though. */
14434 case PACKET_QNonStop:
14435 case PACKET_EnableDisableTracepoints_feature:
14436 case PACKET_tracenz_feature:
14437 case PACKET_DisconnectedTracing_feature:
14438 case PACKET_augmented_libraries_svr4_read_feature:
14440 /* Additions to this list need to be well justified:
14441 pre-existing packets are OK; new packets are not. */
14449 /* This catches both forgetting to add a config command, and
14450 forgetting to remove a packet from the exception list. */
14451 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
14455 /* Keep the old ``set remote Z-packet ...'' working. Each individual
14456 Z sub-packet has its own set and show commands, but users may
14457 have sets to this variable in their .gdbinit files (or in their
14459 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
14460 &remote_Z_packet_detect, _("\
14461 Set use of remote protocol `Z' packets"), _("\
14462 Show use of remote protocol `Z' packets "), _("\
14463 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
14465 set_remote_protocol_Z_packet_cmd,
14466 show_remote_protocol_Z_packet_cmd,
14467 /* FIXME: i18n: Use of remote protocol
14468 `Z' packets is %s. */
14469 &remote_set_cmdlist, &remote_show_cmdlist);
14471 add_prefix_cmd ("remote", class_files, remote_command, _("\
14472 Manipulate files on the remote system\n\
14473 Transfer files to and from the remote target system."),
14474 &remote_cmdlist, "remote ",
14475 0 /* allow-unknown */, &cmdlist);
14477 add_cmd ("put", class_files, remote_put_command,
14478 _("Copy a local file to the remote system."),
14481 add_cmd ("get", class_files, remote_get_command,
14482 _("Copy a remote file to the local system."),
14485 add_cmd ("delete", class_files, remote_delete_command,
14486 _("Delete a remote file."),
14489 add_setshow_string_noescape_cmd ("exec-file", class_files,
14490 &remote_exec_file_var, _("\
14491 Set the remote pathname for \"run\""), _("\
14492 Show the remote pathname for \"run\""), NULL,
14493 set_remote_exec_file,
14494 show_remote_exec_file,
14495 &remote_set_cmdlist,
14496 &remote_show_cmdlist);
14498 add_setshow_boolean_cmd ("range-stepping", class_run,
14499 &use_range_stepping, _("\
14500 Enable or disable range stepping."), _("\
14501 Show whether target-assisted range stepping is enabled."), _("\
14502 If on, and the target supports it, when stepping a source line, GDB\n\
14503 tells the target to step the corresponding range of addresses itself instead\n\
14504 of issuing multiple single-steps. This speeds up source level\n\
14505 stepping. If off, GDB always issues single-steps, even if range\n\
14506 stepping is supported by the target. The default is on."),
14507 set_range_stepping,
14508 show_range_stepping,
14512 /* Eventually initialize fileio. See fileio.c */
14513 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
14515 /* Take advantage of the fact that the TID field is not used, to tag
14516 special ptids with it set to != 0. */
14517 magic_null_ptid = ptid_build (42000, -1, 1);
14518 not_sent_ptid = ptid_build (42000, -2, 1);
14519 any_thread_ptid = ptid_build (42000, 0, 1);