1 /* Remote target communications for serial-line targets in custom GDB protocol
3 Copyright (C) 1988-2025 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. */
24 #include "exceptions.h"
30 #include "process-stratum-target.h"
31 #include "cli/cli-cmds.h"
33 #include "gdbthread.h"
35 #include "remote-notif.h"
38 #include "observable.h"
40 #include "cli/cli-decode.h"
41 #include "cli/cli-setshow.h"
42 #include "cli/cli-style.h"
43 #include "target-descriptions.h"
45 #include "gdbsupport/filestuff.h"
46 #include "gdbsupport/rsp-low.h"
50 #include "gdbsupport/gdb_sys_time.h"
52 #include "gdbsupport/event-loop.h"
53 #include "event-top.h"
61 #include "remote-fileio.h"
62 #include "gdbsupport/fileio.h"
64 #include "xml-support.h"
66 #include "memory-map.h"
68 #include "tracepoint.h"
71 #include "gdbsupport/agent.h"
73 #include "record-btrace.h"
74 #include "gdbsupport/scoped_restore.h"
75 #include "gdbsupport/environ.h"
76 #include "gdbsupport/byte-vector.h"
77 #include "gdbsupport/search.h"
80 #include "async-event.h"
81 #include "gdbsupport/selftest.h"
82 #include "cli/cli-style.h"
83 #include "gdbsupport/remote-args.h"
85 /* The remote target. */
87 static const char remote_doc
[] = N_("\
88 Use a remote computer via a serial line, using a gdb-specific protocol.\n\
89 Specify the serial device it is connected to\n\
90 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).");
94 bool remote_debug
= false;
96 #define OPAQUETHREADBYTES 8
98 /* a 64 bit opaque identifier */
99 typedef unsigned char threadref
[OPAQUETHREADBYTES
];
101 struct gdb_ext_thread_info
;
102 struct threads_listing_context
;
103 typedef int (*rmt_thread_action
) (threadref
*ref
, void *context
);
104 struct protocol_feature
;
108 typedef std::unique_ptr
<stop_reply
> stop_reply_up
;
110 /* Generic configuration support for packets the stub optionally
111 supports. Allows the user to specify the use of the packet as well
112 as allowing GDB to auto-detect support in the remote stub. */
116 PACKET_SUPPORT_UNKNOWN
= 0,
121 /* Convert the packet support auto_boolean to a name used for gdb printing. */
124 get_packet_support_name (auto_boolean support
)
128 case AUTO_BOOLEAN_TRUE
:
130 case AUTO_BOOLEAN_FALSE
:
132 case AUTO_BOOLEAN_AUTO
:
135 gdb_assert_not_reached ("invalid var_auto_boolean");
139 /* Convert the target type (future remote target or currently connected target)
140 to a name used for gdb printing. */
143 get_target_type_name (bool target_connected
)
145 if (target_connected
)
146 return _("on the current remote target");
148 return _("on future remote targets");
151 /* Analyze a packet's return value and update the packet config
161 /* Keeps packet's return value. If packet's return value is PACKET_ERROR,
162 err_msg contains an error message string from E.string or the number
163 stored as a string from E.num. */
167 /* Private ctors for internal use. Clients should use the public
168 factory static methods instead. */
170 /* Construct a PACKET_ERROR packet_result. */
171 packet_result (const char *err_msg
, bool textual_err_msg
)
172 : m_status (PACKET_ERROR
),
174 m_textual_err_msg (textual_err_msg
)
177 /* Construct an PACKET_OK/PACKET_UNKNOWN packet_result. */
178 explicit packet_result (enum packet_status status
)
181 gdb_assert (status
!= PACKET_ERROR
);
185 enum packet_status
status () const
187 return this->m_status
;
190 const char *err_msg () const
192 gdb_assert (this->m_status
== PACKET_ERROR
);
193 return this->m_err_msg
.c_str ();
196 bool textual_err_msg () const
198 gdb_assert (this->m_status
== PACKET_ERROR
);
199 return this->m_textual_err_msg
;
202 static packet_result
make_numeric_error (const char *err_msg
)
204 return packet_result (err_msg
, false);
207 static packet_result
make_textual_error (const char *err_msg
)
209 return packet_result (err_msg
, true);
212 static packet_result
make_ok ()
214 return packet_result (PACKET_OK
);
217 static packet_result
make_unknown ()
219 return packet_result (PACKET_UNKNOWN
);
223 enum packet_status m_status
;
224 std::string m_err_msg
;
226 /* True if we have a textual error message, from an "E.MESSAGE"
228 bool m_textual_err_msg
= false;
231 /* Enumeration of packets for a remote target. */
251 PACKET_vFile_readlink
,
256 PACKET_qXfer_features
,
257 PACKET_qXfer_exec_file
,
258 PACKET_qXfer_libraries
,
259 PACKET_qXfer_libraries_svr4
,
260 PACKET_qXfer_memory_map
,
262 PACKET_qXfer_threads
,
263 PACKET_qXfer_statictrace_read
,
264 PACKET_qXfer_traceframe_info
,
271 PACKET_QCatchSyscalls
,
272 PACKET_QProgramSignals
,
273 PACKET_QSetWorkingDir
,
274 PACKET_QStartupWithShell
,
275 PACKET_QEnvironmentHexEncoded
,
276 PACKET_QEnvironmentReset
,
277 PACKET_QEnvironmentUnset
,
279 PACKET_qSearch_memory
,
282 PACKET_QStartNoAckMode
,
284 PACKET_qXfer_siginfo_read
,
285 PACKET_qXfer_siginfo_write
,
288 /* Support for conditional tracepoints. */
289 PACKET_ConditionalTracepoints
,
291 /* Support for target-side breakpoint conditions. */
292 PACKET_ConditionalBreakpoints
,
294 /* Support for target-side breakpoint commands. */
295 PACKET_BreakpointCommands
,
297 /* Support for fast tracepoints. */
298 PACKET_FastTracepoints
,
300 /* Support for static tracepoints. */
301 PACKET_StaticTracepoints
,
303 /* Support for installing tracepoints while a trace experiment is
305 PACKET_InstallInTrace
,
309 PACKET_TracepointSource
,
312 PACKET_QDisableRandomization
,
314 PACKET_QTBuffer_size
,
320 /* Support for the QNonStop packet. */
323 /* Support for the QThreadEvents packet. */
324 PACKET_QThreadEvents
,
326 /* Support for the QThreadOptions packet. */
327 PACKET_QThreadOptions
,
329 /* Support for multi-process extensions. */
330 PACKET_multiprocess_feature
,
332 /* Support for enabling and disabling tracepoints while a trace
333 experiment is running. */
334 PACKET_EnableDisableTracepoints_feature
,
336 /* Support for collecting strings using the tracenz bytecode. */
337 PACKET_tracenz_feature
,
339 /* Support for continuing to run a trace experiment while GDB is
341 PACKET_DisconnectedTracing_feature
,
343 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
344 PACKET_augmented_libraries_svr4_read_feature
,
346 /* Support for the qXfer:btrace-conf:read packet. */
347 PACKET_qXfer_btrace_conf
,
349 /* Support for the Qbtrace-conf:bts:size packet. */
350 PACKET_Qbtrace_conf_bts_size
,
352 /* Support for swbreak+ feature. */
353 PACKET_swbreak_feature
,
355 /* Support for hwbreak+ feature. */
356 PACKET_hwbreak_feature
,
358 /* Support for fork events. */
359 PACKET_fork_event_feature
,
361 /* Support for vfork events. */
362 PACKET_vfork_event_feature
,
364 /* Support for the Qbtrace-conf:pt:size packet. */
365 PACKET_Qbtrace_conf_pt_size
,
367 /* Support for the Qbtrace-conf:pt:ptwrite packet. */
368 PACKET_Qbtrace_conf_pt_ptwrite
,
370 /* Support for the Qbtrace-conf:pt:event-tracing packet. */
371 PACKET_Qbtrace_conf_pt_event_tracing
,
373 /* Support for exec events. */
374 PACKET_exec_event_feature
,
376 /* Support for query supported vCont actions. */
377 PACKET_vContSupported
,
379 /* Support remote CTRL-C. */
382 /* Support TARGET_WAITKIND_NO_RESUMED. */
385 /* Support for memory tagging, allocation tag fetch/store
386 packets and the tag violation stop replies. */
387 PACKET_memory_tagging_feature
,
389 /* Support for the qIsAddressTagged packet. */
390 PACKET_qIsAddressTagged
,
392 /* Support for accepting error message in a E.errtext format.
393 This allows every remote packet to return E.errtext.
395 This feature only exists to fix a backwards compatibility issue
396 with the qRcmd and m packets. Historically, these two packets didn't
397 support E.errtext style errors, but when this feature is on
398 these two packets can receive E.errtext style errors.
400 All new packets should be written to always accept E.errtext style
401 errors, and so they should not need to check for this feature. */
402 PACKET_accept_error_message
,
407 struct threads_listing_context
;
409 /* Stub vCont actions support.
411 Each field is a boolean flag indicating whether the stub reports
412 support for the corresponding action. */
414 struct vCont_action_support
429 /* About this many threadids fit in a packet. */
431 #define MAXTHREADLISTRESULTS 32
433 /* Data for the vFile:pread readahead cache. */
435 struct readahead_cache
437 /* Invalidate the readahead cache. */
440 /* Invalidate the readahead cache if it is holding data for FD. */
441 void invalidate_fd (int fd
);
443 /* Serve pread from the readahead cache. Returns number of bytes
444 read, or 0 if the request can't be served from the cache. */
445 int pread (int fd
, gdb_byte
*read_buf
, size_t len
, ULONGEST offset
);
447 /* The file descriptor for the file that is being cached. -1 if the
451 /* The offset into the file that the cache buffer corresponds
455 /* The buffer holding the cache contents. */
456 gdb::byte_vector buf
;
458 /* Cache hit and miss counters. */
459 ULONGEST hit_count
= 0;
460 ULONGEST miss_count
= 0;
463 /* Description of the remote protocol for a given architecture. */
467 long offset
; /* Offset into G packet. */
468 long regnum
; /* GDB's internal register number. */
469 LONGEST pnum
; /* Remote protocol register number. */
470 bool in_g_packet
; /* Always part of G packet. */
471 /* long size in bytes; == register_size (arch, regnum);
473 /* char *name; == gdbarch_register_name (arch, regnum);
477 struct remote_arch_state
479 explicit remote_arch_state (struct gdbarch
*gdbarch
);
481 /* Description of the remote protocol registers. */
482 long sizeof_g_packet
;
484 /* Description of the remote protocol registers indexed by REGNUM
485 (making an array gdbarch_num_regs in size). */
486 std::unique_ptr
<packet_reg
[]> regs
;
488 /* This is the size (in chars) of the first response to the ``g''
489 packet. It is used as a heuristic when determining the maximum
490 size of memory-read and memory-write packets. A target will
491 typically only reserve a buffer large enough to hold the ``g''
492 packet. The size does not include packet overhead (headers and
494 long actual_register_packet_size
;
496 /* This is the maximum size (in chars) of a non read/write packet.
497 It is also used as a cap on the size of read/write packets. */
498 long remote_packet_size
;
501 /* Description of the remote protocol state for the currently
502 connected target. This is per-target state, and independent of the
503 selected architecture. */
512 /* Get the remote arch state for GDBARCH. */
513 struct remote_arch_state
*get_remote_arch_state (struct gdbarch
*gdbarch
);
515 void create_async_event_handler ()
517 gdb_assert (m_async_event_handler_token
== nullptr);
518 m_async_event_handler_token
519 = ::create_async_event_handler ([] (gdb_client_data data
)
521 inferior_event_handler (INF_REG_EVENT
);
526 void mark_async_event_handler ()
528 gdb_assert (this->is_async_p ());
529 ::mark_async_event_handler (m_async_event_handler_token
);
532 void clear_async_event_handler ()
533 { ::clear_async_event_handler (m_async_event_handler_token
); }
535 bool async_event_handler_marked () const
536 { return ::async_event_handler_marked (m_async_event_handler_token
); }
538 void delete_async_event_handler ()
540 if (m_async_event_handler_token
!= nullptr)
541 ::delete_async_event_handler (&m_async_event_handler_token
);
544 bool is_async_p () const
546 /* We're async whenever the serial device is. */
547 gdb_assert (this->remote_desc
!= nullptr);
548 return serial_is_async_p (this->remote_desc
);
551 bool can_async_p () const
553 /* We can async whenever the serial device can. */
554 gdb_assert (this->remote_desc
!= nullptr);
555 return serial_can_async_p (this->remote_desc
);
560 /* A buffer to use for incoming packets, and its current size. The
561 buffer is grown dynamically for larger incoming packets.
562 Outgoing packets may also be constructed in this buffer.
563 The size of the buffer is always at least REMOTE_PACKET_SIZE;
564 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
566 gdb::char_vector buf
;
568 /* True if we're going through initial connection setup (finding out
569 about the remote side's threads, relocating symbols, etc.). */
570 bool starting_up
= false;
572 /* If we negotiated packet size explicitly (and thus can bypass
573 heuristics for the largest packet size that will not overflow
574 a buffer in the stub), this will be set to that packet size.
575 Otherwise zero, meaning to use the guessed size. */
576 long explicit_packet_size
= 0;
578 /* True, if in no ack mode. That is, neither GDB nor the stub will
579 expect acks from each other. The connection is assumed to be
581 bool noack_mode
= false;
583 /* True if we're connected in extended remote mode. */
584 bool extended
= false;
586 /* True if we resumed the target and we're waiting for the target to
587 stop. In the mean time, we can't start another command/query.
588 The remote server wouldn't be ready to process it, so we'd
589 timeout waiting for a reply that would never come and eventually
590 we'd close the connection. This can happen in asynchronous mode
591 because we allow GDB commands while the target is running. */
592 bool waiting_for_stop_reply
= false;
594 /* The status of the stub support for the various vCont actions. */
595 vCont_action_support supports_vCont
;
597 /* True if the user has pressed Ctrl-C, but the target hasn't
598 responded to that. */
599 bool ctrlc_pending_p
= false;
601 /* True if we saw a Ctrl-C while reading or writing from/to the
602 remote descriptor. At that point it is not safe to send a remote
603 interrupt packet, so we instead remember we saw the Ctrl-C and
604 process it once we're done with sending/receiving the current
605 packet, which should be shortly. If however that takes too long,
606 and the user presses Ctrl-C again, we offer to disconnect. */
607 bool got_ctrlc_during_io
= false;
609 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
610 remote_open knows that we don't have a file open when the program
612 struct serial
*remote_desc
= nullptr;
614 /* These are the threads which we last sent to the remote system. The
615 TID member will be -1 for all or -2 for not sent yet. */
616 ptid_t general_thread
= null_ptid
;
617 ptid_t continue_thread
= null_ptid
;
619 /* This is the traceframe which we last selected on the remote system.
620 It will be -1 if no traceframe is selected. */
621 int remote_traceframe_number
= -1;
623 char *last_pass_packet
= nullptr;
625 /* The last QProgramSignals packet sent to the target. We bypass
626 sending a new program signals list down to the target if the new
627 packet is exactly the same as the last we sent. IOW, we only let
628 the target know about program signals list changes. */
629 char *last_program_signals_packet
= nullptr;
631 /* Similarly, the last QThreadEvents state we sent to the
633 bool last_thread_events
= false;
635 gdb_signal last_sent_signal
= GDB_SIGNAL_0
;
637 bool last_sent_step
= false;
639 /* The execution direction of the last resume we got. */
640 exec_direction_kind last_resume_exec_dir
= EXEC_FORWARD
;
642 char *finished_object
= nullptr;
643 char *finished_annex
= nullptr;
644 ULONGEST finished_offset
= 0;
646 /* Should we try the 'ThreadInfo' query packet?
648 This variable (NOT available to the user: auto-detect only!)
649 determines whether GDB will use the new, simpler "ThreadInfo"
650 query or the older, more complex syntax for thread queries.
651 This is an auto-detect variable (set to true at each connect,
652 and set to false when the target fails to recognize it). */
653 bool use_threadinfo_query
= false;
654 bool use_threadextra_query
= false;
656 threadref echo_nextthread
{};
657 threadref nextthread
{};
658 threadref resultthreadlist
[MAXTHREADLISTRESULTS
] {};
660 /* The state of remote notification. */
661 struct remote_notif_state
*notif_state
= nullptr;
663 /* The branch trace configuration. */
664 struct btrace_config btrace_config
{};
666 /* The argument to the last "vFile:setfs:" packet we sent, used
667 to avoid sending repeated unnecessary "vFile:setfs:" packets.
668 Initialized to -1 to indicate that no "vFile:setfs:" packet
669 has yet been sent. */
672 /* A readahead cache for vFile:pread. Often, reading a binary
673 involves a sequence of small reads. E.g., when parsing an ELF
674 file. A readahead cache helps mostly the case of remote
675 debugging on a connection with higher latency, due to the
676 request/reply nature of the RSP. We only cache data for a single
677 file descriptor at a time. */
678 struct readahead_cache readahead_cache
;
680 /* The list of already fetched and acknowledged stop events. This
681 queue is used for notification Stop, and other notifications
682 don't need queue for their events, because the notification
683 events of Stop can't be consumed immediately, so that events
684 should be queued first, and be consumed by remote_wait_{ns,as}
685 one per time. Other notifications can consume their events
686 immediately, so queue is not needed for them. */
687 std::vector
<stop_reply_up
> stop_reply_queue
;
689 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
690 ``forever'' still use the normal timeout mechanism. This is
691 currently used by the ASYNC code to guarantee that target reads
692 during the initial connect always time-out. Once getpkt has been
693 modified to return a timeout indication and, in turn
694 remote_wait()/wait_for_inferior() have gained a timeout parameter
696 bool wait_forever_enabled_p
= true;
698 /* The set of thread options the target reported it supports, via
700 gdb_thread_options supported_thread_options
= 0;
702 /* Contains the regnums of the expedited registers in the last stop
704 gdb::unordered_set
<int> last_seen_expedited_registers
;
707 /* Asynchronous signal handle registered as event loop source for
708 when we have pending events ready to be passed to the core. */
709 async_event_handler
*m_async_event_handler_token
= nullptr;
711 /* Mapping of remote protocol data for each gdbarch. Usually there
712 is only one entry here, though we may see more with stubs that
713 support multi-process. */
714 gdb::unordered_map
<struct gdbarch
*, remote_arch_state
>
718 static const target_info remote_target_info
= {
720 N_("Remote target using gdb-specific protocol"),
724 /* Description of a remote packet. */
726 struct packet_description
728 /* Name of the packet used for gdb output. */
731 /* Title of the packet, used by the set/show remote name-packet
732 commands to identify the individual packages and gdb output. */
736 /* Configuration of a remote packet. */
740 /* If auto, GDB auto-detects support for this packet or feature,
741 either through qSupported, or by trying the packet and looking
742 at the response. If true, GDB assumes the target supports this
743 packet. If false, the packet is disabled. Configs that don't
744 have an associated command always have this set to auto. */
745 enum auto_boolean detect
;
747 /* Does the target support this packet? */
748 enum packet_support support
;
751 /* User configurable variables for the number of characters in a
752 memory read/write packet. MIN (rsa->remote_packet_size,
753 rsa->sizeof_g_packet) is the default. Some targets need smaller
754 values (fifo overruns, et.al.) and some users need larger values
755 (speed up transfers). The variables ``preferred_*'' (the user
756 request), ``current_*'' (what was actually set) and ``forced_*''
757 (Positive - a soft limit, negative - a hard limit). */
759 struct memory_packet_config
766 /* These global variables contain the default configuration for every new
767 remote_feature object. */
768 static memory_packet_config memory_read_packet_config
=
770 "memory-read-packet-size",
772 static memory_packet_config memory_write_packet_config
=
774 "memory-write-packet-size",
777 /* This global array contains packet descriptions (name and title). */
778 static packet_description packets_descriptions
[PACKET_MAX
];
779 /* This global array contains the default configuration for every new
780 per-remote target array. */
781 static packet_config remote_protocol_packets
[PACKET_MAX
];
783 /* Description of a remote target's features. It stores the configuration
784 and provides functions to determine supported features of the target. */
786 struct remote_features
790 m_memory_read_packet_config
= memory_read_packet_config
;
791 m_memory_write_packet_config
= memory_write_packet_config
;
793 std::copy (std::begin (remote_protocol_packets
),
794 std::end (remote_protocol_packets
),
795 std::begin (m_protocol_packets
));
797 ~remote_features () = default;
799 DISABLE_COPY_AND_ASSIGN (remote_features
);
801 /* Returns whether a given packet defined by its enum value is supported. */
802 enum packet_support
packet_support (int) const;
804 /* Returns the packet's corresponding "set remote foo-packet" command
805 state. See struct packet_config for more details. */
806 enum auto_boolean
packet_set_cmd_state (int packet
) const
807 { return m_protocol_packets
[packet
].detect
; }
809 /* Returns true if the multi-process extensions are in effect. */
810 int remote_multi_process_p () const
811 { return packet_support (PACKET_multiprocess_feature
) == PACKET_ENABLE
; }
813 /* Returns true if fork events are supported. */
814 int remote_fork_event_p () const
815 { return packet_support (PACKET_fork_event_feature
) == PACKET_ENABLE
; }
817 /* Returns true if vfork events are supported. */
818 int remote_vfork_event_p () const
819 { return packet_support (PACKET_vfork_event_feature
) == PACKET_ENABLE
; }
821 /* Returns true if exec events are supported. */
822 int remote_exec_event_p () const
823 { return packet_support (PACKET_exec_event_feature
) == PACKET_ENABLE
; }
825 /* Returns true if memory tagging is supported, false otherwise. */
826 bool remote_memory_tagging_p () const
827 { return packet_support (PACKET_memory_tagging_feature
) == PACKET_ENABLE
; }
829 /* Reset all packets back to "unknown support". Called when opening a
830 new connection to a remote target. */
831 void reset_all_packet_configs_support ();
833 /* Check result value in BUF for packet WHICH_PACKET and update the packet's
834 support configuration accordingly. */
835 packet_result
packet_ok (const char *buf
, const int which_packet
);
836 packet_result
packet_ok (const gdb::char_vector
&buf
, const int which_packet
);
838 /* Configuration of a remote target's memory read packet. */
839 memory_packet_config m_memory_read_packet_config
;
840 /* Configuration of a remote target's memory write packet. */
841 memory_packet_config m_memory_write_packet_config
;
843 /* The per-remote target array which stores a remote's packet
845 packet_config m_protocol_packets
[PACKET_MAX
];
848 class remote_target
: public process_stratum_target
851 remote_target () = default;
852 ~remote_target () override
;
854 const target_info
&info () const override
855 { return remote_target_info
; }
857 const char *connection_string () override
;
859 thread_control_capabilities
get_thread_control_capabilities () override
860 { return tc_schedlock
; }
862 /* Open a remote connection. */
863 static void open (const char *, int);
865 void close () override
;
867 void detach (inferior
*, int) override
;
868 void disconnect (const char *, int) override
;
870 void commit_requested_thread_options ();
872 void commit_resumed () override
;
873 void resume (ptid_t
, int, enum gdb_signal
) override
;
874 ptid_t
wait (ptid_t
, struct target_waitstatus
*, target_wait_flags
) override
;
875 bool has_pending_events () override
;
877 void fetch_registers (struct regcache
*, int) override
;
878 void store_registers (struct regcache
*, int) override
;
879 void prepare_to_store (struct regcache
*) override
;
881 int insert_breakpoint (struct gdbarch
*, struct bp_target_info
*) override
;
883 int remove_breakpoint (struct gdbarch
*, struct bp_target_info
*,
884 enum remove_bp_reason
) override
;
887 bool stopped_by_sw_breakpoint () override
;
888 bool supports_stopped_by_sw_breakpoint () override
;
890 bool stopped_by_hw_breakpoint () override
;
892 bool supports_stopped_by_hw_breakpoint () override
;
894 bool stopped_by_watchpoint () override
;
896 bool stopped_data_address (CORE_ADDR
*) override
;
898 bool watchpoint_addr_within_range (CORE_ADDR
, CORE_ADDR
, int) override
;
900 int can_use_hw_breakpoint (enum bptype
, int, int) override
;
902 int insert_hw_breakpoint (struct gdbarch
*, struct bp_target_info
*) override
;
904 int remove_hw_breakpoint (struct gdbarch
*, struct bp_target_info
*) override
;
906 int region_ok_for_hw_watchpoint (CORE_ADDR
, int) override
;
908 int insert_watchpoint (CORE_ADDR
, int, enum target_hw_bp_type
,
909 struct expression
*) override
;
911 int remove_watchpoint (CORE_ADDR
, int, enum target_hw_bp_type
,
912 struct expression
*) override
;
914 void kill () override
;
916 void load (const char *, int) override
;
918 void mourn_inferior () override
;
920 void pass_signals (gdb::array_view
<const unsigned char>) override
;
922 int set_syscall_catchpoint (int, bool, int,
923 gdb::array_view
<const int>) override
;
925 void program_signals (gdb::array_view
<const unsigned char>) override
;
927 bool thread_alive (ptid_t ptid
) override
;
929 const char *thread_name (struct thread_info
*) override
;
931 void update_thread_list () override
;
933 std::string
pid_to_str (ptid_t
) override
;
935 const char *extra_thread_info (struct thread_info
*) override
;
937 ptid_t
get_ada_task_ptid (long lwp
, ULONGEST thread
) override
;
939 thread_info
*thread_handle_to_thread_info (const gdb_byte
*thread_handle
,
941 inferior
*inf
) override
;
943 gdb::array_view
<const gdb_byte
> thread_info_to_thread_handle (struct thread_info
*tp
)
946 void stop (ptid_t
) override
;
948 void interrupt () override
;
950 void pass_ctrlc () override
;
952 enum target_xfer_status
xfer_partial (enum target_object object
,
955 const gdb_byte
*writebuf
,
956 ULONGEST offset
, ULONGEST len
,
957 ULONGEST
*xfered_len
) override
;
959 ULONGEST
get_memory_xfer_limit () override
;
961 void rcmd (const char *command
, struct ui_file
*output
) override
;
963 const char *pid_to_exec_file (int pid
) override
;
965 void log_command (const char *cmd
) override
967 serial_log_command (this, cmd
);
970 CORE_ADDR
get_thread_local_address (ptid_t ptid
,
971 CORE_ADDR load_module_addr
,
972 CORE_ADDR offset
) override
;
974 bool can_execute_reverse () override
;
976 std::vector
<mem_region
> memory_map () override
;
978 void flash_erase (ULONGEST address
, LONGEST length
) override
;
980 void flash_done () override
;
982 const struct target_desc
*read_description () override
;
984 int search_memory (CORE_ADDR start_addr
, ULONGEST search_space_len
,
985 const gdb_byte
*pattern
, ULONGEST pattern_len
,
986 CORE_ADDR
*found_addrp
) override
;
988 bool can_async_p () override
;
990 bool is_async_p () override
;
992 void async (bool) override
;
994 int async_wait_fd () override
;
996 void thread_events (bool) override
;
998 bool supports_set_thread_options (gdb_thread_options
) override
;
1000 int can_do_single_step () override
;
1002 void terminal_inferior () override
;
1004 void terminal_ours () override
;
1006 bool supports_non_stop () override
;
1008 bool supports_multi_process () override
;
1010 bool supports_disable_randomization () override
;
1012 bool filesystem_is_local () override
;
1015 int fileio_open (struct inferior
*inf
, const char *filename
,
1016 int flags
, int mode
, int warn_if_slow
,
1017 fileio_error
*target_errno
) override
;
1019 int fileio_pwrite (int fd
, const gdb_byte
*write_buf
, int len
,
1020 ULONGEST offset
, fileio_error
*target_errno
) override
;
1022 int fileio_pread (int fd
, gdb_byte
*read_buf
, int len
,
1023 ULONGEST offset
, fileio_error
*target_errno
) override
;
1025 int fileio_fstat (int fd
, struct stat
*sb
, fileio_error
*target_errno
) override
;
1027 int fileio_lstat (struct inferior
*inf
, const char *filename
,
1028 struct stat
*sb
, fileio_error
*target_errno
) override
;
1030 int fileio_close (int fd
, fileio_error
*target_errno
) override
;
1032 int fileio_unlink (struct inferior
*inf
,
1033 const char *filename
,
1034 fileio_error
*target_errno
) override
;
1036 std::optional
<std::string
>
1037 fileio_readlink (struct inferior
*inf
,
1038 const char *filename
,
1039 fileio_error
*target_errno
) override
;
1041 bool supports_enable_disable_tracepoint () override
;
1043 bool supports_string_tracing () override
;
1045 int remote_supports_cond_tracepoints ();
1047 bool supports_evaluation_of_breakpoint_conditions () override
;
1049 int remote_supports_fast_tracepoints ();
1051 int remote_supports_static_tracepoints ();
1053 int remote_supports_install_in_trace ();
1055 bool can_run_breakpoint_commands () override
;
1057 void trace_init () override
;
1059 void download_tracepoint (struct bp_location
*location
) override
;
1061 bool can_download_tracepoint () override
;
1063 void download_trace_state_variable (const trace_state_variable
&tsv
) override
;
1065 void enable_tracepoint (struct bp_location
*location
) override
;
1067 void disable_tracepoint (struct bp_location
*location
) override
;
1069 void trace_set_readonly_regions () override
;
1071 void trace_start () override
;
1073 int get_trace_status (struct trace_status
*ts
) override
;
1075 void get_tracepoint_status (tracepoint
*tp
, struct uploaded_tp
*utp
)
1078 void trace_stop () override
;
1080 int trace_find (enum trace_find_type type
, int num
,
1081 CORE_ADDR addr1
, CORE_ADDR addr2
, int *tpp
) override
;
1083 bool get_trace_state_variable_value (int tsv
, LONGEST
*val
) override
;
1085 int save_trace_data (const char *filename
) override
;
1087 int upload_tracepoints (struct uploaded_tp
**utpp
) override
;
1089 int upload_trace_state_variables (struct uploaded_tsv
**utsvp
) override
;
1091 LONGEST
get_raw_trace_data (gdb_byte
*buf
, ULONGEST offset
, LONGEST len
) override
;
1093 int get_min_fast_tracepoint_insn_len () override
;
1095 void set_disconnected_tracing (int val
) override
;
1097 void set_circular_trace_buffer (int val
) override
;
1099 void set_trace_buffer_size (LONGEST val
) override
;
1101 bool set_trace_notes (const char *user
, const char *notes
,
1102 const char *stopnotes
) override
;
1104 int core_of_thread (ptid_t ptid
) override
;
1106 int verify_memory (const gdb_byte
*data
,
1107 CORE_ADDR memaddr
, ULONGEST size
) override
;
1110 bool get_tib_address (ptid_t ptid
, CORE_ADDR
*addr
) override
;
1112 void set_permissions () override
;
1114 bool static_tracepoint_marker_at (CORE_ADDR
,
1115 struct static_tracepoint_marker
*marker
)
1118 std::vector
<static_tracepoint_marker
>
1119 static_tracepoint_markers_by_strid (const char *id
) override
;
1121 traceframe_info_up
traceframe_info () override
;
1123 bool use_agent (bool use
) override
;
1124 bool can_use_agent () override
;
1126 struct btrace_target_info
*
1127 enable_btrace (thread_info
*tp
, const struct btrace_config
*conf
) override
;
1129 void disable_btrace (struct btrace_target_info
*tinfo
) override
;
1131 void teardown_btrace (struct btrace_target_info
*tinfo
) override
;
1133 enum btrace_error
read_btrace (struct btrace_data
*data
,
1134 struct btrace_target_info
*btinfo
,
1135 enum btrace_read_type type
) override
;
1137 const struct btrace_config
*btrace_conf (const struct btrace_target_info
*) override
;
1138 bool augmented_libraries_svr4_read () override
;
1139 void follow_fork (inferior
*, ptid_t
, target_waitkind
, bool, bool) override
;
1140 void follow_clone (ptid_t child_ptid
) override
;
1141 void follow_exec (inferior
*, ptid_t
, const char *) override
;
1142 int insert_fork_catchpoint (int) override
;
1143 int remove_fork_catchpoint (int) override
;
1144 int insert_vfork_catchpoint (int) override
;
1145 int remove_vfork_catchpoint (int) override
;
1146 int insert_exec_catchpoint (int) override
;
1147 int remove_exec_catchpoint (int) override
;
1148 enum exec_direction_kind
execution_direction () override
;
1150 bool supports_memory_tagging () override
;
1152 bool fetch_memtags (CORE_ADDR address
, size_t len
,
1153 gdb::byte_vector
&tags
, int type
) override
;
1155 bool store_memtags (CORE_ADDR address
, size_t len
,
1156 const gdb::byte_vector
&tags
, int type
) override
;
1158 bool is_address_tagged (gdbarch
*gdbarch
, CORE_ADDR address
) override
;
1160 public: /* Remote specific methods. */
1162 void remote_download_command_source (int num
, ULONGEST addr
,
1163 struct command_line
*cmds
);
1165 void remote_file_put (const char *local_file
, const char *remote_file
,
1167 void remote_file_get (const char *remote_file
, const char *local_file
,
1169 void remote_file_delete (const char *remote_file
, int from_tty
);
1171 int remote_hostio_pread (int fd
, gdb_byte
*read_buf
, int len
,
1172 ULONGEST offset
, fileio_error
*remote_errno
);
1173 int remote_hostio_pwrite (int fd
, const gdb_byte
*write_buf
, int len
,
1174 ULONGEST offset
, fileio_error
*remote_errno
);
1175 int remote_hostio_pread_vFile (int fd
, gdb_byte
*read_buf
, int len
,
1176 ULONGEST offset
, fileio_error
*remote_errno
);
1178 int remote_hostio_send_command (int command_bytes
, int which_packet
,
1179 fileio_error
*remote_errno
, const char **attachment
,
1180 int *attachment_len
);
1181 int remote_hostio_set_filesystem (struct inferior
*inf
,
1182 fileio_error
*remote_errno
);
1183 /* We should get rid of this and use fileio_open directly. */
1184 int remote_hostio_open (struct inferior
*inf
, const char *filename
,
1185 int flags
, int mode
, int warn_if_slow
,
1186 fileio_error
*remote_errno
);
1187 int remote_hostio_close (int fd
, fileio_error
*remote_errno
);
1189 int remote_hostio_unlink (inferior
*inf
, const char *filename
,
1190 fileio_error
*remote_errno
);
1192 struct remote_state
*get_remote_state ();
1194 long get_remote_packet_size (void);
1195 long get_memory_packet_size (struct memory_packet_config
*config
);
1197 long get_memory_write_packet_size ();
1198 long get_memory_read_packet_size ();
1200 char *append_pending_thread_resumptions (char *p
, char *endp
,
1202 static void open_1 (const char *name
, int from_tty
, int extended_p
);
1203 void start_remote (int from_tty
, int extended_p
);
1204 void remote_detach_1 (struct inferior
*inf
, int from_tty
);
1206 char *append_resumption (char *p
, char *endp
,
1207 ptid_t ptid
, int step
, gdb_signal siggnal
);
1208 int remote_resume_with_vcont (ptid_t scope_ptid
, int step
,
1209 gdb_signal siggnal
);
1211 thread_info
*add_current_inferior_and_thread (const char *wait_status
);
1213 ptid_t
wait_ns (ptid_t ptid
, struct target_waitstatus
*status
,
1214 target_wait_flags options
);
1215 ptid_t
wait_as (ptid_t ptid
, target_waitstatus
*status
,
1216 target_wait_flags options
);
1218 ptid_t
process_stop_reply (stop_reply_up stop_reply
,
1219 target_waitstatus
*status
);
1221 ptid_t select_thread_for_ambiguous_stop_reply
1222 (const struct target_waitstatus
&status
);
1224 void remote_notice_new_inferior (ptid_t currthread
, bool executing
);
1226 void print_one_stopped_thread (thread_info
*thread
);
1227 void process_initial_stop_replies (int from_tty
);
1229 thread_info
*remote_add_thread (ptid_t ptid
, bool running
, bool executing
,
1232 void btrace_sync_conf (const btrace_config
*conf
);
1234 void remote_btrace_maybe_reopen ();
1236 void remove_new_children (threads_listing_context
*context
);
1237 void kill_new_fork_children (inferior
*inf
);
1238 void discard_pending_stop_replies (struct inferior
*inf
);
1239 int stop_reply_queue_length ();
1241 void check_pending_events_prevent_wildcard_vcont
1242 (bool *may_global_wildcard_vcont
);
1244 void discard_pending_stop_replies_in_queue ();
1245 stop_reply_up
remote_notif_remove_queued_reply (ptid_t ptid
);
1246 stop_reply_up
queued_stop_reply (ptid_t ptid
);
1247 int peek_stop_reply (ptid_t ptid
);
1248 void remote_parse_stop_reply (const char *buf
, stop_reply
*event
);
1250 void remote_stop_ns (ptid_t ptid
);
1251 void remote_interrupt_as ();
1252 void remote_interrupt_ns ();
1254 char *remote_get_noisy_reply ();
1255 int remote_query_attached (int pid
);
1256 inferior
*remote_add_inferior (bool fake_pid_p
, int pid
, int attached
,
1259 ptid_t
remote_current_thread (ptid_t oldpid
);
1260 ptid_t
get_current_thread (const char *wait_status
);
1262 void set_thread (ptid_t ptid
, int gen
);
1263 void set_general_thread (ptid_t ptid
);
1264 void set_continue_thread (ptid_t ptid
);
1265 void set_general_process ();
1267 char *write_ptid (char *buf
, const char *endbuf
, ptid_t ptid
);
1269 int remote_unpack_thread_info_response (const char *pkt
, threadref
*expectedref
,
1270 gdb_ext_thread_info
*info
);
1271 int remote_get_threadinfo (threadref
*threadid
, int fieldset
,
1272 gdb_ext_thread_info
*info
);
1274 int parse_threadlist_response (const char *pkt
, int result_limit
,
1275 threadref
*original_echo
,
1276 threadref
*resultlist
,
1278 int remote_get_threadlist (int startflag
, threadref
*nextthread
,
1279 int result_limit
, int *done
, int *result_count
,
1280 threadref
*threadlist
);
1282 int remote_threadlist_iterator (rmt_thread_action stepfunction
,
1283 void *context
, int looplimit
);
1285 int remote_get_threads_with_ql (threads_listing_context
*context
);
1286 int remote_get_threads_with_qxfer (threads_listing_context
*context
);
1287 int remote_get_threads_with_qthreadinfo (threads_listing_context
*context
);
1289 void extended_remote_restart ();
1291 void get_offsets ();
1293 void remote_check_symbols ();
1295 void remote_supported_packet (const struct protocol_feature
*feature
,
1296 enum packet_support support
,
1297 const char *argument
);
1299 void remote_query_supported ();
1301 void remote_packet_size (const protocol_feature
*feature
,
1302 packet_support support
, const char *value
);
1303 void remote_supported_thread_options (const protocol_feature
*feature
,
1304 enum packet_support support
,
1307 void remote_serial_quit_handler ();
1309 void remote_detach_pid (int pid
);
1311 void remote_vcont_probe ();
1313 void remote_resume_with_hc (ptid_t ptid
, int step
,
1314 gdb_signal siggnal
);
1316 void send_interrupt_sequence ();
1317 void interrupt_query ();
1319 void remote_notif_get_pending_events (const notif_client
*nc
);
1321 int fetch_register_using_p (struct regcache
*regcache
,
1323 int send_g_packet ();
1324 void process_g_packet (struct regcache
*regcache
);
1325 void fetch_registers_using_g (struct regcache
*regcache
);
1326 int store_register_using_P (const struct regcache
*regcache
,
1328 void store_registers_using_G (const struct regcache
*regcache
);
1330 void set_remote_traceframe ();
1332 void check_binary_download (CORE_ADDR addr
);
1334 target_xfer_status
remote_write_bytes_aux (const char *header
,
1336 const gdb_byte
*myaddr
,
1339 ULONGEST
*xfered_len_units
,
1343 target_xfer_status
remote_write_bytes (CORE_ADDR memaddr
,
1344 const gdb_byte
*myaddr
, ULONGEST len
,
1345 int unit_size
, ULONGEST
*xfered_len
);
1347 target_xfer_status
remote_read_bytes_1 (CORE_ADDR memaddr
, gdb_byte
*myaddr
,
1349 int unit_size
, ULONGEST
*xfered_len_units
);
1351 target_xfer_status
remote_xfer_live_readonly_partial (gdb_byte
*readbuf
,
1355 ULONGEST
*xfered_len
);
1357 target_xfer_status
remote_read_bytes (CORE_ADDR memaddr
,
1358 gdb_byte
*myaddr
, ULONGEST len
,
1360 ULONGEST
*xfered_len
);
1362 packet_status
remote_send_printf (const char *format
, ...)
1363 ATTRIBUTE_PRINTF (2, 3);
1365 target_xfer_status
remote_flash_write (ULONGEST address
,
1366 ULONGEST length
, ULONGEST
*xfered_len
,
1367 const gdb_byte
*data
);
1369 int readchar (int timeout
);
1371 void remote_serial_write (const char *str
, int len
);
1372 void remote_serial_send_break ();
1374 int putpkt (const char *buf
);
1375 int putpkt_binary (const char *buf
, int cnt
);
1377 int putpkt (const gdb::char_vector
&buf
)
1379 return putpkt (buf
.data ());
1383 long read_frame (gdb::char_vector
*buf_p
);
1384 int getpkt (gdb::char_vector
*buf
, bool forever
= false,
1385 bool *is_notif
= nullptr);
1386 int remote_vkill (int pid
);
1387 void remote_kill_k ();
1389 void extended_remote_disable_randomization (int val
);
1390 int extended_remote_run (const std::string
&args
);
1392 void send_environment_packet (const char *action
,
1396 void extended_remote_environment_support ();
1397 void extended_remote_set_inferior_cwd ();
1399 target_xfer_status
remote_write_qxfer (const char *object_name
,
1401 const gdb_byte
*writebuf
,
1402 ULONGEST offset
, LONGEST len
,
1403 ULONGEST
*xfered_len
,
1404 const unsigned int which_packet
);
1406 target_xfer_status
remote_read_qxfer (const char *object_name
,
1408 gdb_byte
*readbuf
, ULONGEST offset
,
1410 ULONGEST
*xfered_len
,
1411 const unsigned int which_packet
);
1413 void push_stop_reply (stop_reply_up new_event
);
1415 bool vcont_r_supported ();
1417 remote_features m_features
;
1421 bool start_remote_1 (int from_tty
, int extended_p
);
1423 /* The remote state. Don't reference this directly. Use the
1424 get_remote_state method instead. */
1425 remote_state m_remote_state
;
1428 static const target_info extended_remote_target_info
= {
1430 N_("Extended remote target using gdb-specific protocol"),
1434 /* Set up the extended remote target by extending the standard remote
1435 target and adding to it. */
1437 class extended_remote_target final
: public remote_target
1440 const target_info
&info () const override
1441 { return extended_remote_target_info
; }
1443 /* Open an extended-remote connection. */
1444 static void open (const char *, int);
1446 bool can_create_inferior () override
{ return true; }
1447 void create_inferior (const char *, const std::string
&,
1448 char **, int) override
;
1450 void detach (inferior
*, int) override
;
1452 bool can_attach () override
{ return true; }
1453 void attach (const char *, int) override
;
1455 void post_attach (int) override
;
1456 bool supports_disable_randomization () override
;
1459 struct stop_reply
: public notif_event
1461 /* The identifier of the thread about this event */
1464 /* The remote state this event is associated with. When the remote
1465 connection, represented by a remote_state object, is closed,
1466 all the associated stop_reply events should be released. */
1467 struct remote_state
*rs
;
1469 struct target_waitstatus ws
;
1471 /* The architecture associated with the expedited registers. */
1474 /* Expedited registers. This makes remote debugging a bit more
1475 efficient for those targets that provide critical registers as
1476 part of their normal status mechanism (as another roundtrip to
1477 fetch them is avoided). */
1478 std::vector
<cached_reg_t
> regcache
;
1480 enum target_stop_reason stop_reason
;
1482 CORE_ADDR watch_data_address
;
1487 /* Return TARGET as a remote_target if it is one, else nullptr. */
1489 static remote_target
*
1490 as_remote_target (process_stratum_target
*target
)
1492 return dynamic_cast<remote_target
*> (target
);
1498 is_remote_target (process_stratum_target
*target
)
1500 return as_remote_target (target
) != nullptr;
1506 remote_register_is_expedited (int regnum
)
1508 remote_target
*rt
= as_remote_target (current_inferior ()->process_target ());
1513 remote_state
*rs
= rt
->get_remote_state ();
1514 return rs
->last_seen_expedited_registers
.count (regnum
) > 0;
1517 /* Per-program-space data key. */
1518 static const registry
<program_space
>::key
<char, gdb::xfree_deleter
<char>>
1521 /* The variable registered as the control variable used by the
1522 remote exec-file commands. While the remote exec-file setting is
1523 per-program-space, the set/show machinery uses this as the
1524 location of the remote exec-file value. */
1525 static std::string remote_exec_file_var
;
1527 /* The size to align memory write packets, when practical. The protocol
1528 does not guarantee any alignment, and gdb will generate short
1529 writes and unaligned writes, but even as a best-effort attempt this
1530 can improve bulk transfers. For instance, if a write is misaligned
1531 relative to the target's data bus, the stub may need to make an extra
1532 round trip fetching data from the target. This doesn't make a
1533 huge difference, but it's easy to do, so we try to be helpful.
1535 The alignment chosen is arbitrary; usually data bus width is
1536 important here, not the possibly larger cache line size. */
1537 enum { REMOTE_ALIGN_WRITES
= 16 };
1539 /* Prototypes for local functions. */
1541 static int hexnumlen (ULONGEST num
);
1543 static int stubhex (int ch
);
1545 static int hexnumstr (char *, ULONGEST
);
1547 static int hexnumnstr (char *, ULONGEST
, int);
1549 static CORE_ADDR
remote_address_masked (CORE_ADDR
);
1551 static int stub_unpack_int (const char *buff
, int fieldlength
);
1553 static void set_remote_protocol_packet_cmd (const char *args
, int from_tty
,
1554 cmd_list_element
*c
);
1556 static void show_packet_config_cmd (ui_file
*file
,
1557 const unsigned int which_packet
,
1558 remote_target
*remote
);
1560 static void show_remote_protocol_packet_cmd (struct ui_file
*file
,
1562 struct cmd_list_element
*c
,
1565 static ptid_t
read_ptid (const char *buf
, const char **obuf
);
1567 static bool remote_read_description_p (struct target_ops
*target
);
1569 static void remote_console_output (const char *msg
, ui_file
*stream
);
1571 static void remote_btrace_reset (remote_state
*rs
);
1573 [[noreturn
]] static void remote_unpush_and_throw (remote_target
*target
);
1577 static struct cmd_list_element
*remote_cmdlist
;
1579 /* For "set remote" and "show remote". */
1581 static struct cmd_list_element
*remote_set_cmdlist
;
1582 static struct cmd_list_element
*remote_show_cmdlist
;
1584 /* Controls whether GDB is willing to use range stepping. */
1586 static bool use_range_stepping
= true;
1588 /* From the remote target's point of view, each thread is in one of these three
1590 enum class resume_state
1592 /* Not resumed - we haven't been asked to resume this thread. */
1595 /* We have been asked to resume this thread, but haven't sent a vCont action
1596 for it yet. We'll need to consider it next time commit_resume is
1598 RESUMED_PENDING_VCONT
,
1600 /* We have been asked to resume this thread, and we have sent a vCont action
1605 /* Information about a thread's pending vCont-resume. Used when a thread is in
1606 the remote_resume_state::RESUMED_PENDING_VCONT state. remote_target::resume
1607 stores this information which is then picked up by
1608 remote_target::commit_resume to know which is the proper action for this
1609 thread to include in the vCont packet. */
1610 struct resumed_pending_vcont_info
1612 /* True if the last resume call for this thread was a step request, false
1613 if a continue request. */
1616 /* The signal specified in the last resume call for this thread. */
1620 /* Private data that we'll store in (struct thread_info)->priv. */
1621 struct remote_thread_info
: public private_thread_info
1627 /* The string representation for the thread's id.
1629 The target specifies this if they want to display the thread id
1630 in a specific way. If empty, the default approach is used. */
1633 /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
1634 sequence of bytes. */
1635 gdb::byte_vector thread_handle
;
1637 /* Whether the target stopped for a breakpoint/watchpoint. */
1638 enum target_stop_reason stop_reason
= TARGET_STOPPED_BY_NO_REASON
;
1640 /* This is set to the data address of the access causing the target
1641 to stop for a watchpoint. */
1642 CORE_ADDR watch_data_address
= 0;
1644 /* Get the thread's resume state. */
1645 enum resume_state
get_resume_state () const
1647 return m_resume_state
;
1650 /* Put the thread in the NOT_RESUMED state. */
1651 void set_not_resumed ()
1653 m_resume_state
= resume_state::NOT_RESUMED
;
1656 /* Put the thread in the RESUMED_PENDING_VCONT state. */
1657 void set_resumed_pending_vcont (bool step
, gdb_signal sig
)
1659 m_resume_state
= resume_state::RESUMED_PENDING_VCONT
;
1660 m_resumed_pending_vcont_info
.step
= step
;
1661 m_resumed_pending_vcont_info
.sig
= sig
;
1664 /* Get the information this thread's pending vCont-resumption.
1666 Must only be called if the thread is in the RESUMED_PENDING_VCONT resume
1668 const struct resumed_pending_vcont_info
&resumed_pending_vcont_info () const
1670 gdb_assert (m_resume_state
== resume_state::RESUMED_PENDING_VCONT
);
1672 return m_resumed_pending_vcont_info
;
1675 /* Put the thread in the VCONT_RESUMED state. */
1678 m_resume_state
= resume_state::RESUMED
;
1682 /* Resume state for this thread. This is used to implement vCont action
1683 coalescing (only when the target operates in non-stop mode).
1685 remote_target::resume moves the thread to the RESUMED_PENDING_VCONT state,
1686 which notes that this thread must be considered in the next commit_resume
1689 remote_target::commit_resume sends a vCont packet with actions for the
1690 threads in the RESUMED_PENDING_VCONT state and moves them to the
1691 VCONT_RESUMED state.
1693 When reporting a stop to the core for a thread, that thread is moved back
1694 to the NOT_RESUMED state. */
1695 enum resume_state m_resume_state
= resume_state::NOT_RESUMED
;
1697 /* Extra info used if the thread is in the RESUMED_PENDING_VCONT state. */
1698 struct resumed_pending_vcont_info m_resumed_pending_vcont_info
;
1701 remote_state::remote_state ()
1706 remote_state::~remote_state ()
1708 xfree (this->last_pass_packet
);
1709 xfree (this->last_program_signals_packet
);
1710 xfree (this->finished_object
);
1711 xfree (this->finished_annex
);
1714 /* Utility: generate error from an incoming stub packet. */
1716 trace_error (char *buf
)
1719 return; /* not an error msg */
1722 case '1': /* malformed packet error */
1723 if (*++buf
== '0') /* general case: */
1724 error (_("remote.c: error in outgoing packet."));
1726 error (_("remote.c: error in outgoing packet at field #%ld."),
1727 strtol (buf
, NULL
, 16));
1729 error (_("Target returns error code '%s'."), buf
);
1733 /* Utility: wait for reply from stub, while accepting "O" packets. */
1736 remote_target::remote_get_noisy_reply ()
1738 struct remote_state
*rs
= get_remote_state ();
1740 do /* Loop on reply from remote stub. */
1744 QUIT
; /* Allow user to bail out with ^C. */
1746 buf
= rs
->buf
.data ();
1749 else if (startswith (buf
, "qRelocInsn:"))
1752 CORE_ADDR from
, to
, org_to
;
1754 int adjusted_size
= 0;
1757 p
= buf
+ strlen ("qRelocInsn:");
1758 pp
= unpack_varlen_hex (p
, &ul
);
1760 error (_("invalid qRelocInsn packet: %s"), buf
);
1764 unpack_varlen_hex (p
, &ul
);
1771 gdbarch_relocate_instruction (current_inferior ()->arch (),
1775 catch (const gdb_exception
&ex
)
1777 if (ex
.error
== MEMORY_ERROR
)
1779 /* Propagate memory errors silently back to the
1780 target. The stub may have limited the range of
1781 addresses we can write to, for example. */
1785 /* Something unexpectedly bad happened. Be verbose
1786 so we can tell what, and propagate the error back
1787 to the stub, so it doesn't get stuck waiting for
1789 exception_fprintf (gdb_stderr
, ex
,
1790 _("warning: relocating instruction: "));
1797 adjusted_size
= to
- org_to
;
1799 xsnprintf (buf
, rs
->buf
.size (), "qRelocInsn:%x", adjusted_size
);
1803 else if (buf
[0] == 'O' && buf
[1] != 'K')
1805 /* 'O' message from stub */
1806 remote_console_output (buf
+ 1, gdb_stdtarg
);
1809 return buf
; /* Here's the actual reply. */
1814 struct remote_arch_state
*
1815 remote_state::get_remote_arch_state (struct gdbarch
*gdbarch
)
1817 remote_arch_state
*rsa
;
1819 auto it
= this->m_arch_states
.find (gdbarch
);
1820 if (it
== this->m_arch_states
.end ())
1822 auto p
= this->m_arch_states
.emplace (std::piecewise_construct
,
1823 std::forward_as_tuple (gdbarch
),
1824 std::forward_as_tuple (gdbarch
));
1825 rsa
= &p
.first
->second
;
1827 /* Make sure that the packet buffer is plenty big enough for
1828 this architecture. */
1829 if (this->buf
.size () < rsa
->remote_packet_size
)
1830 this->buf
.resize (2 * rsa
->remote_packet_size
);
1838 /* Fetch the global remote target state. */
1841 remote_target::get_remote_state ()
1843 /* Make sure that the remote architecture state has been
1844 initialized, because doing so might reallocate rs->buf. Any
1845 function which calls getpkt also needs to be mindful of changes
1846 to rs->buf, but this call limits the number of places which run
1848 m_remote_state
.get_remote_arch_state (current_inferior ()->arch ());
1850 return &m_remote_state
;
1853 /* Fetch the remote exec-file from the current program space. */
1856 get_remote_exec_file (void)
1858 char *remote_exec_file
;
1860 remote_exec_file
= remote_pspace_data
.get (current_program_space
);
1861 if (remote_exec_file
== NULL
)
1864 return remote_exec_file
;
1867 /* Set the remote exec file for PSPACE. */
1870 set_pspace_remote_exec_file (struct program_space
*pspace
,
1871 const char *remote_exec_file
)
1873 char *old_file
= remote_pspace_data
.get (pspace
);
1876 remote_pspace_data
.set (pspace
, xstrdup (remote_exec_file
));
1879 /* The "set/show remote exec-file" set command hook. */
1882 set_remote_exec_file (const char *ignored
, int from_tty
,
1883 struct cmd_list_element
*c
)
1885 set_pspace_remote_exec_file (current_program_space
,
1886 remote_exec_file_var
.c_str ());
1889 /* The "set/show remote exec-file" show command hook. */
1892 show_remote_exec_file (struct ui_file
*file
, int from_tty
,
1893 struct cmd_list_element
*cmd
, const char *value
)
1895 gdb_printf (file
, "%s\n", get_remote_exec_file ());
1899 map_regcache_remote_table (struct gdbarch
*gdbarch
, struct packet_reg
*regs
)
1901 int regnum
, num_remote_regs
, offset
;
1902 struct packet_reg
**remote_regs
;
1904 for (regnum
= 0; regnum
< gdbarch_num_regs (gdbarch
); regnum
++)
1906 struct packet_reg
*r
= ®s
[regnum
];
1908 if (register_size (gdbarch
, regnum
) == 0)
1909 /* Do not try to fetch zero-sized (placeholder) registers. */
1912 r
->pnum
= gdbarch_remote_register_number (gdbarch
, regnum
);
1917 /* Define the g/G packet format as the contents of each register
1918 with a remote protocol number, in order of ascending protocol
1921 remote_regs
= XALLOCAVEC (struct packet_reg
*, gdbarch_num_regs (gdbarch
));
1922 for (num_remote_regs
= 0, regnum
= 0;
1923 regnum
< gdbarch_num_regs (gdbarch
);
1925 if (regs
[regnum
].pnum
!= -1)
1926 remote_regs
[num_remote_regs
++] = ®s
[regnum
];
1928 std::sort (remote_regs
, remote_regs
+ num_remote_regs
,
1929 [] (const packet_reg
*a
, const packet_reg
*b
)
1930 { return a
->pnum
< b
->pnum
; });
1932 for (regnum
= 0, offset
= 0; regnum
< num_remote_regs
; regnum
++)
1934 remote_regs
[regnum
]->in_g_packet
= true;
1935 remote_regs
[regnum
]->offset
= offset
;
1936 offset
+= register_size (gdbarch
, remote_regs
[regnum
]->regnum
);
1942 /* Given the architecture described by GDBARCH, return the remote
1943 protocol register's number and the register's offset in the g/G
1944 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
1945 If the target does not have a mapping for REGNUM, return false,
1946 otherwise, return true. */
1949 remote_register_number_and_offset (struct gdbarch
*gdbarch
, int regnum
,
1950 int *pnum
, int *poffset
)
1952 gdb_assert (regnum
< gdbarch_num_regs (gdbarch
));
1954 std::vector
<packet_reg
> regs (gdbarch_num_regs (gdbarch
));
1956 map_regcache_remote_table (gdbarch
, regs
.data ());
1958 *pnum
= regs
[regnum
].pnum
;
1959 *poffset
= regs
[regnum
].offset
;
1964 remote_arch_state::remote_arch_state (struct gdbarch
*gdbarch
)
1966 /* Use the architecture to build a regnum<->pnum table, which will be
1967 1:1 unless a feature set specifies otherwise. */
1968 this->regs
.reset (new packet_reg
[gdbarch_num_regs (gdbarch
)] ());
1970 /* Record the maximum possible size of the g packet - it may turn out
1972 this->sizeof_g_packet
1973 = map_regcache_remote_table (gdbarch
, this->regs
.get ());
1975 /* Default maximum number of characters in a packet body. Many
1976 remote stubs have a hardwired buffer size of 400 bytes
1977 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
1978 as the maximum packet-size to ensure that the packet and an extra
1979 NUL character can always fit in the buffer. This stops GDB
1980 trashing stubs that try to squeeze an extra NUL into what is
1981 already a full buffer (As of 1999-12-04 that was most stubs). */
1982 this->remote_packet_size
= 400 - 1;
1984 /* This one is filled in when a ``g'' packet is received. */
1985 this->actual_register_packet_size
= 0;
1987 /* Should rsa->sizeof_g_packet needs more space than the
1988 default, adjust the size accordingly. Remember that each byte is
1989 encoded as two characters. 32 is the overhead for the packet
1990 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
1991 (``$NN:G...#NN'') is a better guess, the below has been padded a
1993 if (this->sizeof_g_packet
> ((this->remote_packet_size
- 32) / 2))
1994 this->remote_packet_size
= (this->sizeof_g_packet
* 2 + 32);
1997 /* Get a pointer to the current remote target. If not connected to a
1998 remote target, return NULL. */
2000 static remote_target
*
2001 get_current_remote_target ()
2003 target_ops
*proc_target
= current_inferior ()->process_target ();
2004 return dynamic_cast<remote_target
*> (proc_target
);
2007 /* Return the current allowed size of a remote packet. This is
2008 inferred from the current architecture, and should be used to
2009 limit the length of outgoing packets. */
2011 remote_target::get_remote_packet_size ()
2013 struct remote_state
*rs
= get_remote_state ();
2014 remote_arch_state
*rsa
2015 = rs
->get_remote_arch_state (current_inferior ()->arch ());
2017 if (rs
->explicit_packet_size
)
2018 return rs
->explicit_packet_size
;
2020 return rsa
->remote_packet_size
;
2023 static struct packet_reg
*
2024 packet_reg_from_regnum (struct gdbarch
*gdbarch
, struct remote_arch_state
*rsa
,
2027 if (regnum
< 0 && regnum
>= gdbarch_num_regs (gdbarch
))
2031 struct packet_reg
*r
= &rsa
->regs
[regnum
];
2033 gdb_assert (r
->regnum
== regnum
);
2038 static struct packet_reg
*
2039 packet_reg_from_pnum (struct gdbarch
*gdbarch
, struct remote_arch_state
*rsa
,
2044 for (i
= 0; i
< gdbarch_num_regs (gdbarch
); i
++)
2046 struct packet_reg
*r
= &rsa
->regs
[i
];
2048 if (r
->pnum
== pnum
)
2054 /* Allow the user to specify what sequence to send to the remote
2055 when he requests a program interruption: Although ^C is usually
2056 what remote systems expect (this is the default, here), it is
2057 sometimes preferable to send a break. On other systems such
2058 as the Linux kernel, a break followed by g, which is Magic SysRq g
2059 is required in order to interrupt the execution. */
2060 const char interrupt_sequence_control_c
[] = "Ctrl-C";
2061 const char interrupt_sequence_break
[] = "BREAK";
2062 const char interrupt_sequence_break_g
[] = "BREAK-g";
2063 static const char *const interrupt_sequence_modes
[] =
2065 interrupt_sequence_control_c
,
2066 interrupt_sequence_break
,
2067 interrupt_sequence_break_g
,
2070 static const char *interrupt_sequence_mode
= interrupt_sequence_control_c
;
2073 show_interrupt_sequence (struct ui_file
*file
, int from_tty
,
2074 struct cmd_list_element
*c
,
2077 if (interrupt_sequence_mode
== interrupt_sequence_control_c
)
2079 _("Send the ASCII ETX character (Ctrl-c) "
2080 "to the remote target to interrupt the "
2081 "execution of the program.\n"));
2082 else if (interrupt_sequence_mode
== interrupt_sequence_break
)
2084 _("send a break signal to the remote target "
2085 "to interrupt the execution of the program.\n"));
2086 else if (interrupt_sequence_mode
== interrupt_sequence_break_g
)
2088 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
2089 "the remote target to interrupt the execution "
2090 "of Linux kernel.\n"));
2092 internal_error (_("Invalid value for interrupt_sequence_mode: %s."),
2093 interrupt_sequence_mode
);
2096 /* This boolean variable specifies whether interrupt_sequence is sent
2097 to the remote target when gdb connects to it.
2098 This is mostly needed when you debug the Linux kernel: The Linux kernel
2099 expects BREAK g which is Magic SysRq g for connecting gdb. */
2100 static bool interrupt_on_connect
= false;
2102 /* This variable is used to implement the "set/show remotebreak" commands.
2103 Since these commands are now deprecated in favor of "set/show remote
2104 interrupt-sequence", it no longer has any effect on the code. */
2105 static bool remote_break
;
2108 set_remotebreak (const char *args
, int from_tty
, struct cmd_list_element
*c
)
2111 interrupt_sequence_mode
= interrupt_sequence_break
;
2113 interrupt_sequence_mode
= interrupt_sequence_control_c
;
2117 show_remotebreak (struct ui_file
*file
, int from_tty
,
2118 struct cmd_list_element
*c
,
2123 /* This variable sets the number of bits in an address that are to be
2124 sent in a memory ("M" or "m") packet. Normally, after stripping
2125 leading zeros, the entire address would be sent. This variable
2126 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
2127 initial implementation of remote.c restricted the address sent in
2128 memory packets to ``host::sizeof long'' bytes - (typically 32
2129 bits). Consequently, for 64 bit targets, the upper 32 bits of an
2130 address was never sent. Since fixing this bug may cause a break in
2131 some remote targets this variable is principally provided to
2132 facilitate backward compatibility. */
2134 static unsigned int remote_address_size
;
2137 /* The default max memory-write-packet-size, when the setting is
2138 "fixed". The 16k is historical. (It came from older GDB's using
2139 alloca for buffers and the knowledge (folklore?) that some hosts
2140 don't cope very well with large alloca calls.) */
2141 #define DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED 16384
2143 /* The minimum remote packet size for memory transfers. Ensures we
2144 can write at least one byte. */
2145 #define MIN_MEMORY_PACKET_SIZE 20
2147 /* Get the memory packet size, assuming it is fixed. */
2150 get_fixed_memory_packet_size (struct memory_packet_config
*config
)
2152 gdb_assert (config
->fixed_p
);
2154 if (config
->size
<= 0)
2155 return DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED
;
2157 return config
->size
;
2160 /* Compute the current size of a read/write packet. Since this makes
2161 use of ``actual_register_packet_size'' the computation is dynamic. */
2164 remote_target::get_memory_packet_size (struct memory_packet_config
*config
)
2166 struct remote_state
*rs
= get_remote_state ();
2167 remote_arch_state
*rsa
2168 = rs
->get_remote_arch_state (current_inferior ()->arch ());
2171 if (config
->fixed_p
)
2172 what_they_get
= get_fixed_memory_packet_size (config
);
2175 what_they_get
= get_remote_packet_size ();
2176 /* Limit the packet to the size specified by the user. */
2177 if (config
->size
> 0
2178 && what_they_get
> config
->size
)
2179 what_they_get
= config
->size
;
2181 /* Limit it to the size of the targets ``g'' response unless we have
2182 permission from the stub to use a larger packet size. */
2183 if (rs
->explicit_packet_size
== 0
2184 && rsa
->actual_register_packet_size
> 0
2185 && what_they_get
> rsa
->actual_register_packet_size
)
2186 what_they_get
= rsa
->actual_register_packet_size
;
2188 if (what_they_get
< MIN_MEMORY_PACKET_SIZE
)
2189 what_they_get
= MIN_MEMORY_PACKET_SIZE
;
2191 /* Make sure there is room in the global buffer for this packet
2192 (including its trailing NUL byte). */
2193 if (rs
->buf
.size () < what_they_get
+ 1)
2194 rs
->buf
.resize (2 * what_they_get
);
2196 return what_they_get
;
2199 /* Update the size of a read/write packet. If they user wants
2200 something really big then do a sanity check. */
2203 set_memory_packet_size (const char *args
, struct memory_packet_config
*config
,
2204 bool target_connected
)
2206 int fixed_p
= config
->fixed_p
;
2207 long size
= config
->size
;
2210 error (_("Argument required (integer, \"fixed\" or \"limit\")."));
2211 else if (strcmp (args
, "hard") == 0
2212 || strcmp (args
, "fixed") == 0)
2214 else if (strcmp (args
, "soft") == 0
2215 || strcmp (args
, "limit") == 0)
2221 size
= strtoul (args
, &end
, 0);
2223 error (_("Invalid %s (bad syntax)."), config
->name
);
2225 /* Instead of explicitly capping the size of a packet to or
2226 disallowing it, the user is allowed to set the size to
2227 something arbitrarily large. */
2231 if (fixed_p
&& !config
->fixed_p
)
2233 /* So that the query shows the correct value. */
2234 long query_size
= (size
<= 0
2235 ? DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED
2238 if (target_connected
2239 && !query (_("The target may not be able to correctly handle a %s\n"
2240 "of %ld bytes. Change the packet size? "),
2241 config
->name
, query_size
))
2242 error (_("Packet size not changed."));
2243 else if (!target_connected
2244 && !query (_("Future remote targets may not be able to "
2245 "correctly handle a %s\nof %ld bytes. Change the "
2246 "packet size for future remote targets? "),
2247 config
->name
, query_size
))
2248 error (_("Packet size not changed."));
2250 /* Update the config. */
2251 config
->fixed_p
= fixed_p
;
2252 config
->size
= size
;
2254 const char *target_type
= get_target_type_name (target_connected
);
2255 gdb_printf (_("The %s %s is set to \"%s\".\n"), config
->name
, target_type
,
2260 /* Show the memory-read or write-packet size configuration CONFIG of the
2261 target REMOTE. If REMOTE is nullptr, the default configuration for future
2262 remote targets should be passed in CONFIG. */
2265 show_memory_packet_size (memory_packet_config
*config
, remote_target
*remote
)
2267 const char *target_type
= get_target_type_name (remote
!= nullptr);
2269 if (config
->size
== 0)
2270 gdb_printf (_("The %s %s is 0 (default). "), config
->name
, target_type
);
2272 gdb_printf (_("The %s %s is %ld. "), config
->name
, target_type
,
2275 if (config
->fixed_p
)
2276 gdb_printf (_("Packets are fixed at %ld bytes.\n"),
2277 get_fixed_memory_packet_size (config
));
2280 if (remote
!= nullptr)
2281 gdb_printf (_("Packets are limited to %ld bytes.\n"),
2282 remote
->get_memory_packet_size (config
));
2284 gdb_puts ("The actual limit will be further reduced "
2285 "dependent on the target.\n");
2289 /* Configure the memory-write-packet size of the currently selected target. If
2290 no target is available, the default configuration for future remote targets
2294 set_memory_write_packet_size (const char *args
, int from_tty
)
2296 remote_target
*remote
= get_current_remote_target ();
2297 if (remote
!= nullptr)
2299 set_memory_packet_size
2300 (args
, &remote
->m_features
.m_memory_write_packet_config
, true);
2304 memory_packet_config
* config
= &memory_write_packet_config
;
2305 set_memory_packet_size (args
, config
, false);
2309 /* Display the memory-write-packet size of the currently selected target. If
2310 no target is available, the default configuration for future remote targets
2314 show_memory_write_packet_size (const char *args
, int from_tty
)
2316 remote_target
*remote
= get_current_remote_target ();
2317 if (remote
!= nullptr)
2318 show_memory_packet_size (&remote
->m_features
.m_memory_write_packet_config
,
2321 show_memory_packet_size (&memory_write_packet_config
, nullptr);
2324 /* Show the number of hardware watchpoints that can be used. */
2327 show_hardware_watchpoint_limit (struct ui_file
*file
, int from_tty
,
2328 struct cmd_list_element
*c
,
2331 gdb_printf (file
, _("The maximum number of target hardware "
2332 "watchpoints is %s.\n"), value
);
2335 /* Show the length limit (in bytes) for hardware watchpoints. */
2338 show_hardware_watchpoint_length_limit (struct ui_file
*file
, int from_tty
,
2339 struct cmd_list_element
*c
,
2342 gdb_printf (file
, _("The maximum length (in bytes) of a target "
2343 "hardware watchpoint is %s.\n"), value
);
2346 /* Show the number of hardware breakpoints that can be used. */
2349 show_hardware_breakpoint_limit (struct ui_file
*file
, int from_tty
,
2350 struct cmd_list_element
*c
,
2353 gdb_printf (file
, _("The maximum number of target hardware "
2354 "breakpoints is %s.\n"), value
);
2357 /* Controls the maximum number of characters to display in the debug output
2358 for each remote packet. The remaining characters are omitted. */
2360 static int remote_packet_max_chars
= 512;
2362 /* Show the maximum number of characters to display for each remote packet
2363 when remote debugging is enabled. */
2366 show_remote_packet_max_chars (struct ui_file
*file
, int from_tty
,
2367 struct cmd_list_element
*c
,
2370 gdb_printf (file
, _("Number of remote packet characters to "
2371 "display is %s.\n"), value
);
2375 remote_target::get_memory_write_packet_size ()
2377 return get_memory_packet_size (&m_features
.m_memory_write_packet_config
);
2380 /* Configure the memory-read-packet size of the currently selected target. If
2381 no target is available, the default configuration for future remote targets
2385 set_memory_read_packet_size (const char *args
, int from_tty
)
2387 remote_target
*remote
= get_current_remote_target ();
2388 if (remote
!= nullptr)
2389 set_memory_packet_size
2390 (args
, &remote
->m_features
.m_memory_read_packet_config
, true);
2393 memory_packet_config
* config
= &memory_read_packet_config
;
2394 set_memory_packet_size (args
, config
, false);
2399 /* Display the memory-read-packet size of the currently selected target. If
2400 no target is available, the default configuration for future remote targets
2404 show_memory_read_packet_size (const char *args
, int from_tty
)
2406 remote_target
*remote
= get_current_remote_target ();
2407 if (remote
!= nullptr)
2408 show_memory_packet_size (&remote
->m_features
.m_memory_read_packet_config
,
2411 show_memory_packet_size (&memory_read_packet_config
, nullptr);
2415 remote_target::get_memory_read_packet_size ()
2417 long size
= get_memory_packet_size (&m_features
.m_memory_read_packet_config
);
2419 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
2420 extra buffer size argument before the memory read size can be
2421 increased beyond this. */
2422 if (size
> get_remote_packet_size ())
2423 size
= get_remote_packet_size ();
2427 static enum packet_support
packet_config_support (const packet_config
*config
);
2431 set_remote_protocol_packet_cmd (const char *args
, int from_tty
,
2432 cmd_list_element
*c
)
2434 remote_target
*remote
= get_current_remote_target ();
2435 gdb_assert (c
->var
.has_value ());
2437 auto *default_config
= static_cast<packet_config
*> (c
->context ());
2438 const int packet_idx
= std::distance (remote_protocol_packets
,
2441 if (packet_idx
>= 0 && packet_idx
< PACKET_MAX
)
2443 const char *name
= packets_descriptions
[packet_idx
].name
;
2444 const auto_boolean value
= c
->var
->get
<auto_boolean
> ();
2445 const char *support
= get_packet_support_name (value
);
2446 const char *target_type
= get_target_type_name (remote
!= nullptr);
2448 if (remote
!= nullptr)
2449 remote
->m_features
.m_protocol_packets
[packet_idx
].detect
= value
;
2451 remote_protocol_packets
[packet_idx
].detect
= value
;
2453 gdb_printf (_("Support for the '%s' packet %s is set to \"%s\".\n"), name
,
2454 target_type
, support
);
2458 internal_error (_("Could not find config for %s"), c
->name
);
2462 show_packet_config_cmd (ui_file
*file
, const unsigned int which_packet
,
2463 remote_target
*remote
)
2465 const char *support
= "internal-error";
2466 const char *target_type
= get_target_type_name (remote
!= nullptr);
2468 packet_config
*config
;
2469 if (remote
!= nullptr)
2470 config
= &remote
->m_features
.m_protocol_packets
[which_packet
];
2472 config
= &remote_protocol_packets
[which_packet
];
2474 switch (packet_config_support (config
))
2477 support
= "enabled";
2479 case PACKET_DISABLE
:
2480 support
= "disabled";
2482 case PACKET_SUPPORT_UNKNOWN
:
2483 support
= "unknown";
2486 switch (config
->detect
)
2488 case AUTO_BOOLEAN_AUTO
:
2490 _("Support for the '%s' packet %s is \"auto\", "
2492 packets_descriptions
[which_packet
].name
, target_type
,
2495 case AUTO_BOOLEAN_TRUE
:
2496 case AUTO_BOOLEAN_FALSE
:
2498 _("Support for the '%s' packet %s is \"%s\".\n"),
2499 packets_descriptions
[which_packet
].name
, target_type
,
2500 get_packet_support_name (config
->detect
));
2506 add_packet_config_cmd (const unsigned int which_packet
, const char *name
,
2507 const char *title
, int legacy
)
2509 packets_descriptions
[which_packet
].name
= name
;
2510 packets_descriptions
[which_packet
].title
= title
;
2512 packet_config
*config
= &remote_protocol_packets
[which_packet
];
2514 gdb::unique_xmalloc_ptr
<char> set_doc
2515 = xstrprintf ("Set use of remote protocol `%s' packet.", name
);
2516 gdb::unique_xmalloc_ptr
<char> show_doc
2517 = xstrprintf ("Show current use of remote protocol `%s' packet.", name
);
2518 /* set/show TITLE-packet {auto,on,off} */
2519 gdb::unique_xmalloc_ptr
<char> cmd_name
= xstrprintf ("%s-packet", title
);
2520 set_show_commands cmds
2521 = add_setshow_auto_boolean_cmd (cmd_name
.release (), class_obscure
,
2522 &config
->detect
, set_doc
.get (),
2523 show_doc
.get (), NULL
, /* help_doc */
2524 set_remote_protocol_packet_cmd
,
2525 show_remote_protocol_packet_cmd
,
2526 &remote_set_cmdlist
, &remote_show_cmdlist
);
2527 cmds
.show
->set_context (config
);
2528 cmds
.set
->set_context (config
);
2530 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
2533 /* It's not clear who should take ownership of the LEGACY_NAME string
2534 created below, so, for now, place the string into a static vector
2535 which ensures the strings is released when GDB exits. */
2536 static std::vector
<gdb::unique_xmalloc_ptr
<char>> legacy_names
;
2537 gdb::unique_xmalloc_ptr
<char> legacy_name
2538 = xstrprintf ("%s-packet", name
);
2539 add_alias_cmd (legacy_name
.get (), cmds
.set
, class_obscure
, 0,
2540 &remote_set_cmdlist
);
2541 add_alias_cmd (legacy_name
.get (), cmds
.show
, class_obscure
, 0,
2542 &remote_show_cmdlist
);
2543 legacy_names
.emplace_back (std::move (legacy_name
));
2547 /* Check GDBserver's reply packet. Return packet_result structure
2548 which contains the packet_status enum and an error message for the
2551 An error packet can always take the form Exx (where xx is a hex
2553 static packet_result
2554 packet_check_result (const char *buf
)
2558 /* The stub recognized the packet request. Check that the
2559 operation succeeded. */
2561 && isxdigit (buf
[1]) && isxdigit (buf
[2])
2563 /* "Enn" - definitely an error. */
2564 return packet_result::make_numeric_error (buf
+ 1);
2566 /* Always treat "E." as an error. This will be used for
2567 more verbose error messages, such as E.memtypes. */
2568 if (buf
[0] == 'E' && buf
[1] == '.')
2571 return packet_result::make_textual_error (buf
+ 2);
2573 return packet_result::make_textual_error ("no error provided");
2576 /* The packet may or may not be OK. Just assume it is. */
2577 return packet_result::make_ok ();
2581 /* The stub does not support the packet. */
2582 return packet_result::make_unknown ();
2586 static packet_result
2587 packet_check_result (const gdb::char_vector
&buf
)
2589 return packet_check_result (buf
.data ());
2593 remote_features::packet_ok (const char *buf
, const int which_packet
)
2595 packet_config
*config
= &m_protocol_packets
[which_packet
];
2596 packet_description
*descr
= &packets_descriptions
[which_packet
];
2598 if (config
->detect
!= AUTO_BOOLEAN_TRUE
2599 && config
->support
== PACKET_DISABLE
)
2600 internal_error (_("packet_ok: attempt to use a disabled packet"));
2602 packet_result result
= packet_check_result (buf
);
2603 switch (result
.status ())
2607 /* The stub recognized the packet request. */
2608 if (config
->support
== PACKET_SUPPORT_UNKNOWN
)
2610 remote_debug_printf ("Packet %s (%s) is supported",
2611 descr
->name
, descr
->title
);
2612 config
->support
= PACKET_ENABLE
;
2615 case PACKET_UNKNOWN
:
2616 /* The stub does not support the packet. */
2617 if (config
->detect
== AUTO_BOOLEAN_AUTO
2618 && config
->support
== PACKET_ENABLE
)
2620 /* If the stub previously indicated that the packet was
2621 supported then there is a protocol error. */
2622 error (_("Protocol error: %s (%s) conflicting enabled responses."),
2623 descr
->name
, descr
->title
);
2625 else if (config
->detect
== AUTO_BOOLEAN_TRUE
)
2627 /* The user set it wrong. */
2628 error (_("Enabled packet %s (%s) not recognized by stub"),
2629 descr
->name
, descr
->title
);
2632 remote_debug_printf ("Packet %s (%s) is NOT supported", descr
->name
,
2634 config
->support
= PACKET_DISABLE
;
2642 remote_features::packet_ok (const gdb::char_vector
&buf
, const int which_packet
)
2644 return packet_ok (buf
.data (), which_packet
);
2647 /* Returns whether a given packet or feature is supported. This takes
2648 into account the state of the corresponding "set remote foo-packet"
2649 command, which may be used to bypass auto-detection. */
2651 static enum packet_support
2652 packet_config_support (const packet_config
*config
)
2654 switch (config
->detect
)
2656 case AUTO_BOOLEAN_TRUE
:
2657 return PACKET_ENABLE
;
2658 case AUTO_BOOLEAN_FALSE
:
2659 return PACKET_DISABLE
;
2660 case AUTO_BOOLEAN_AUTO
:
2661 return config
->support
;
2663 gdb_assert_not_reached ("bad switch");
2668 remote_features::packet_support (int packet
) const
2670 const packet_config
*config
= &m_protocol_packets
[packet
];
2671 return packet_config_support (config
);
2675 show_remote_protocol_packet_cmd (struct ui_file
*file
, int from_tty
,
2676 struct cmd_list_element
*c
,
2679 remote_target
*remote
= get_current_remote_target ();
2680 gdb_assert (c
->var
.has_value ());
2682 auto *default_config
= static_cast<packet_config
*> (c
->context ());
2683 const int packet_idx
= std::distance (remote_protocol_packets
,
2686 if (packet_idx
>= 0 && packet_idx
< PACKET_MAX
)
2688 show_packet_config_cmd (file
, packet_idx
, remote
);
2691 internal_error (_("Could not find config for %s"), c
->name
);
2694 /* Should we try one of the 'Z' requests? */
2698 Z_PACKET_SOFTWARE_BP
,
2699 Z_PACKET_HARDWARE_BP
,
2706 /* For compatibility with older distributions. Provide a ``set remote
2707 Z-packet ...'' command that updates all the Z packet types. */
2709 static enum auto_boolean remote_Z_packet_detect
;
2712 set_remote_protocol_Z_packet_cmd (const char *args
, int from_tty
,
2713 struct cmd_list_element
*c
)
2715 remote_target
*remote
= get_current_remote_target ();
2718 for (i
= 0; i
< NR_Z_PACKET_TYPES
; i
++)
2720 if (remote
!= nullptr)
2721 remote
->m_features
.m_protocol_packets
[PACKET_Z0
+ i
].detect
2722 = remote_Z_packet_detect
;
2724 remote_protocol_packets
[PACKET_Z0
+ i
].detect
= remote_Z_packet_detect
;
2727 const char *support
= get_packet_support_name (remote_Z_packet_detect
);
2728 const char *target_type
= get_target_type_name (remote
!= nullptr);
2729 gdb_printf (_("Use of Z packets %s is set to \"%s\".\n"), target_type
,
2735 show_remote_protocol_Z_packet_cmd (struct ui_file
*file
, int from_tty
,
2736 struct cmd_list_element
*c
,
2739 remote_target
*remote
= get_current_remote_target ();
2742 for (i
= 0; i
< NR_Z_PACKET_TYPES
; i
++)
2743 show_packet_config_cmd (file
, PACKET_Z0
+ i
, remote
);
2746 /* Insert fork catchpoint target routine. If fork events are enabled
2747 then return success, nothing more to do. */
2750 remote_target::insert_fork_catchpoint (int pid
)
2752 return !m_features
.remote_fork_event_p ();
2755 /* Remove fork catchpoint target routine. Nothing to do, just
2759 remote_target::remove_fork_catchpoint (int pid
)
2764 /* Insert vfork catchpoint target routine. If vfork events are enabled
2765 then return success, nothing more to do. */
2768 remote_target::insert_vfork_catchpoint (int pid
)
2770 return !m_features
.remote_vfork_event_p ();
2773 /* Remove vfork catchpoint target routine. Nothing to do, just
2777 remote_target::remove_vfork_catchpoint (int pid
)
2782 /* Insert exec catchpoint target routine. If exec events are
2783 enabled, just return success. */
2786 remote_target::insert_exec_catchpoint (int pid
)
2788 return !m_features
.remote_exec_event_p ();
2791 /* Remove exec catchpoint target routine. Nothing to do, just
2795 remote_target::remove_exec_catchpoint (int pid
)
2802 /* Take advantage of the fact that the TID field is not used, to tag
2803 special ptids with it set to != 0. */
2804 static const ptid_t
magic_null_ptid (42000, -1, 1);
2805 static const ptid_t
not_sent_ptid (42000, -2, 1);
2806 static const ptid_t
any_thread_ptid (42000, 0, 1);
2808 /* Find out if the stub attached to PID (and hence GDB should offer to
2809 detach instead of killing it when bailing out). */
2812 remote_target::remote_query_attached (int pid
)
2814 struct remote_state
*rs
= get_remote_state ();
2815 size_t size
= get_remote_packet_size ();
2817 if (m_features
.packet_support (PACKET_qAttached
) == PACKET_DISABLE
)
2820 if (m_features
.remote_multi_process_p ())
2821 xsnprintf (rs
->buf
.data (), size
, "qAttached:%x", pid
);
2823 xsnprintf (rs
->buf
.data (), size
, "qAttached");
2828 packet_result result
= m_features
.packet_ok (rs
->buf
, PACKET_qAttached
);
2829 switch (result
.status ())
2832 if (strcmp (rs
->buf
.data (), "1") == 0)
2836 warning (_("Remote failure reply: %s"), result
.err_msg ());
2838 case PACKET_UNKNOWN
:
2845 /* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
2846 has been invented by GDB, instead of reported by the target. Since
2847 we can be connected to a remote system before before knowing about
2848 any inferior, mark the target with execution when we find the first
2849 inferior. If ATTACHED is 1, then we had just attached to this
2850 inferior. If it is 0, then we just created this inferior. If it
2851 is -1, then try querying the remote stub to find out if it had
2852 attached to the inferior or not. If TRY_OPEN_EXEC is true then
2853 attempt to open this inferior's executable as the main executable
2854 if no main executable is open already. */
2857 remote_target::remote_add_inferior (bool fake_pid_p
, int pid
, int attached
,
2860 struct inferior
*inf
;
2862 /* Check whether this process we're learning about is to be
2863 considered attached, or if is to be considered to have been
2864 spawned by the stub. */
2866 attached
= remote_query_attached (pid
);
2868 if (gdbarch_has_global_solist (current_inferior ()->arch ()))
2870 /* If the target shares code across all inferiors, then every
2871 attach adds a new inferior. */
2872 inf
= add_inferior (pid
);
2874 /* ... and every inferior is bound to the same program space.
2875 However, each inferior may still have its own address
2877 inf
->aspace
= maybe_new_address_space ();
2878 inf
->pspace
= current_program_space
;
2882 /* In the traditional debugging scenario, there's a 1-1 match
2883 between program/address spaces. We simply bind the inferior
2884 to the program space's address space. */
2885 inf
= current_inferior ();
2887 /* However, if the current inferior is already bound to a
2888 process, find some other empty inferior. */
2892 for (inferior
*it
: all_inferiors ())
2901 /* Since all inferiors were already bound to a process, add
2903 inf
= add_inferior_with_spaces ();
2905 switch_to_inferior_no_thread (inf
);
2906 inf
->push_target (this);
2907 inferior_appeared (inf
, pid
);
2910 inf
->attach_flag
= attached
;
2911 inf
->fake_pid_p
= fake_pid_p
;
2913 /* If no main executable is currently open then attempt to
2914 open the file that was executed to create this inferior. */
2915 if (try_open_exec
&& current_program_space
->exec_filename () == nullptr)
2916 exec_file_locate_attach (pid
, 0, 1);
2918 /* Check for exec file mismatch, and let the user solve it. */
2919 validate_exec_file (1);
2924 static remote_thread_info
*get_remote_thread_info (thread_info
*thread
);
2925 static remote_thread_info
*get_remote_thread_info (remote_target
*target
,
2928 /* Add thread PTID to GDB's thread list. Tag it as executing/running
2929 according to EXECUTING and RUNNING respectively. If SILENT_P (or the
2930 remote_state::starting_up flag) is true then the new thread is added
2931 silently, otherwise the new thread will be announced to the user. */
2934 remote_target::remote_add_thread (ptid_t ptid
, bool running
, bool executing
,
2937 struct remote_state
*rs
= get_remote_state ();
2938 struct thread_info
*thread
;
2940 /* GDB historically didn't pull threads in the initial connection
2941 setup. If the remote target doesn't even have a concept of
2942 threads (e.g., a bare-metal target), even if internally we
2943 consider that a single-threaded target, mentioning a new thread
2944 might be confusing to the user. Be silent then, preserving the
2945 age old behavior. */
2946 if (rs
->starting_up
|| silent_p
)
2947 thread
= add_thread_silent (this, ptid
);
2949 thread
= add_thread (this, ptid
);
2952 get_remote_thread_info (thread
)->set_resumed ();
2953 set_executing (this, ptid
, executing
);
2954 set_running (this, ptid
, running
);
2959 /* Come here when we learn about a thread id from the remote target.
2960 It may be the first time we hear about such thread, so take the
2961 opportunity to add it to GDB's thread list. In case this is the
2962 first time we're noticing its corresponding inferior, add it to
2963 GDB's inferior list as well. EXECUTING indicates whether the
2964 thread is (internally) executing or stopped. */
2967 remote_target::remote_notice_new_inferior (ptid_t currthread
, bool executing
)
2969 /* In non-stop mode, we assume new found threads are (externally)
2970 running until proven otherwise with a stop reply. In all-stop,
2971 we can only get here if all threads are stopped. */
2972 bool running
= target_is_non_stop_p ();
2974 /* If this is a new thread, add it to GDB's thread list.
2975 If we leave it up to WFI to do this, bad things will happen. */
2977 thread_info
*tp
= this->find_thread (currthread
);
2978 if (tp
!= NULL
&& tp
->state
== THREAD_EXITED
)
2980 /* We're seeing an event on a thread id we knew had exited.
2981 This has to be a new thread reusing the old id. Add it. */
2982 remote_add_thread (currthread
, running
, executing
, false);
2986 if (!in_thread_list (this, currthread
))
2988 struct inferior
*inf
= NULL
;
2989 int pid
= currthread
.pid ();
2991 if (inferior_ptid
.is_pid ()
2992 && pid
== inferior_ptid
.pid ())
2994 /* inferior_ptid has no thread member yet. This can happen
2995 with the vAttach -> remote_wait,"TAAthread:" path if the
2996 stub doesn't support qC. This is the first stop reported
2997 after an attach, so this is the main thread. Update the
2998 ptid in the thread list. */
2999 if (in_thread_list (this, ptid_t (pid
)))
3000 thread_change_ptid (this, inferior_ptid
, currthread
);
3004 = remote_add_thread (currthread
, running
, executing
, false);
3005 switch_to_thread (thr
);
3010 if (magic_null_ptid
== inferior_ptid
)
3012 /* inferior_ptid is not set yet. This can happen with the
3013 vRun -> remote_wait,"TAAthread:" path if the stub
3014 doesn't support qC. This is the first stop reported
3015 after an attach, so this is the main thread. Update the
3016 ptid in the thread list. */
3017 thread_change_ptid (this, inferior_ptid
, currthread
);
3021 /* When connecting to a target remote, or to a target
3022 extended-remote which already was debugging an inferior, we
3023 may not know about it yet. Add it before adding its child
3024 thread, so notifications are emitted in a sensible order. */
3025 if (find_inferior_pid (this, currthread
.pid ()) == NULL
)
3027 bool fake_pid_p
= !m_features
.remote_multi_process_p ();
3029 inf
= remote_add_inferior (fake_pid_p
,
3030 currthread
.pid (), -1, 1);
3033 /* This is really a new thread. Add it. */
3034 thread_info
*new_thr
3035 = remote_add_thread (currthread
, running
, executing
, false);
3037 /* If we found a new inferior, let the common code do whatever
3038 it needs to with it (e.g., read shared libraries, insert
3039 breakpoints), unless we're just setting up an all-stop
3043 struct remote_state
*rs
= get_remote_state ();
3045 if (!rs
->starting_up
)
3046 notice_new_inferior (new_thr
, executing
, 0);
3051 /* Return THREAD's private thread data, creating it if necessary. */
3053 static remote_thread_info
*
3054 get_remote_thread_info (thread_info
*thread
)
3056 gdb_assert (thread
!= NULL
);
3058 if (thread
->priv
== NULL
)
3059 thread
->priv
= std::make_unique
<remote_thread_info
> ();
3061 return gdb::checked_static_cast
<remote_thread_info
*> (thread
->priv
.get ());
3064 /* Return PTID's private thread data, creating it if necessary. */
3066 static remote_thread_info
*
3067 get_remote_thread_info (remote_target
*target
, ptid_t ptid
)
3069 thread_info
*thr
= target
->find_thread (ptid
);
3070 return get_remote_thread_info (thr
);
3073 /* Call this function as a result of
3074 1) A halt indication (T packet) containing a thread id
3075 2) A direct query of currthread
3076 3) Successful execution of set thread */
3079 record_currthread (struct remote_state
*rs
, ptid_t currthread
)
3081 rs
->general_thread
= currthread
;
3084 /* If 'QPassSignals' is supported, tell the remote stub what signals
3085 it can simply pass through to the inferior without reporting. */
3088 remote_target::pass_signals (gdb::array_view
<const unsigned char> pass_signals
)
3090 if (m_features
.packet_support (PACKET_QPassSignals
) != PACKET_DISABLE
)
3092 char *pass_packet
, *p
;
3094 struct remote_state
*rs
= get_remote_state ();
3096 gdb_assert (pass_signals
.size () < 256);
3097 for (size_t i
= 0; i
< pass_signals
.size (); i
++)
3099 if (pass_signals
[i
])
3102 pass_packet
= (char *) xmalloc (count
* 3 + strlen ("QPassSignals:") + 1);
3103 strcpy (pass_packet
, "QPassSignals:");
3104 p
= pass_packet
+ strlen (pass_packet
);
3105 for (size_t i
= 0; i
< pass_signals
.size (); i
++)
3107 if (pass_signals
[i
])
3110 *p
++ = tohex (i
>> 4);
3111 *p
++ = tohex (i
& 15);
3120 if (!rs
->last_pass_packet
|| strcmp (rs
->last_pass_packet
, pass_packet
))
3122 putpkt (pass_packet
);
3124 m_features
.packet_ok (rs
->buf
, PACKET_QPassSignals
);
3125 xfree (rs
->last_pass_packet
);
3126 rs
->last_pass_packet
= pass_packet
;
3129 xfree (pass_packet
);
3133 /* If 'QCatchSyscalls' is supported, tell the remote stub
3134 to report syscalls to GDB. */
3137 remote_target::set_syscall_catchpoint (int pid
, bool needed
, int any_count
,
3138 gdb::array_view
<const int> syscall_counts
)
3140 const char *catch_packet
;
3143 if (m_features
.packet_support (PACKET_QCatchSyscalls
) == PACKET_DISABLE
)
3145 /* Not supported. */
3149 if (needed
&& any_count
== 0)
3151 /* Count how many syscalls are to be caught. */
3152 for (size_t i
= 0; i
< syscall_counts
.size (); i
++)
3154 if (syscall_counts
[i
] != 0)
3159 remote_debug_printf ("pid %d needed %d any_count %d n_sysno %d",
3160 pid
, needed
, any_count
, n_sysno
);
3162 std::string built_packet
;
3165 /* Prepare a packet with the sysno list, assuming max 8+1
3166 characters for a sysno. If the resulting packet size is too
3167 big, fallback on the non-selective packet. */
3168 const int maxpktsz
= strlen ("QCatchSyscalls:1") + n_sysno
* 9 + 1;
3169 built_packet
.reserve (maxpktsz
);
3170 built_packet
= "QCatchSyscalls:1";
3173 /* Add in each syscall to be caught. */
3174 for (size_t i
= 0; i
< syscall_counts
.size (); i
++)
3176 if (syscall_counts
[i
] != 0)
3177 string_appendf (built_packet
, ";%zx", i
);
3180 if (built_packet
.size () > get_remote_packet_size ())
3182 /* catch_packet too big. Fallback to less efficient
3183 non selective mode, with GDB doing the filtering. */
3184 catch_packet
= "QCatchSyscalls:1";
3187 catch_packet
= built_packet
.c_str ();
3190 catch_packet
= "QCatchSyscalls:0";
3192 struct remote_state
*rs
= get_remote_state ();
3194 putpkt (catch_packet
);
3196 packet_result result
= m_features
.packet_ok (rs
->buf
, PACKET_QCatchSyscalls
);
3197 if (result
.status () == PACKET_OK
)
3203 /* If 'QProgramSignals' is supported, tell the remote stub what
3204 signals it should pass through to the inferior when detaching. */
3207 remote_target::program_signals (gdb::array_view
<const unsigned char> signals
)
3209 if (m_features
.packet_support (PACKET_QProgramSignals
) != PACKET_DISABLE
)
3213 struct remote_state
*rs
= get_remote_state ();
3215 gdb_assert (signals
.size () < 256);
3216 for (size_t i
= 0; i
< signals
.size (); i
++)
3221 packet
= (char *) xmalloc (count
* 3 + strlen ("QProgramSignals:") + 1);
3222 strcpy (packet
, "QProgramSignals:");
3223 p
= packet
+ strlen (packet
);
3224 for (size_t i
= 0; i
< signals
.size (); i
++)
3226 if (signal_pass_state (i
))
3229 *p
++ = tohex (i
>> 4);
3230 *p
++ = tohex (i
& 15);
3239 if (!rs
->last_program_signals_packet
3240 || strcmp (rs
->last_program_signals_packet
, packet
) != 0)
3244 m_features
.packet_ok (rs
->buf
, PACKET_QProgramSignals
);
3245 xfree (rs
->last_program_signals_packet
);
3246 rs
->last_program_signals_packet
= packet
;
3253 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
3254 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
3255 thread. If GEN is set, set the general thread, if not, then set
3256 the step/continue thread. */
3258 remote_target::set_thread (ptid_t ptid
, int gen
)
3260 struct remote_state
*rs
= get_remote_state ();
3261 ptid_t state
= gen
? rs
->general_thread
: rs
->continue_thread
;
3262 char *buf
= rs
->buf
.data ();
3263 char *endbuf
= buf
+ get_remote_packet_size ();
3269 *buf
++ = gen
? 'g' : 'c';
3270 if (ptid
== magic_null_ptid
)
3271 xsnprintf (buf
, endbuf
- buf
, "0");
3272 else if (ptid
== any_thread_ptid
)
3273 xsnprintf (buf
, endbuf
- buf
, "0");
3274 else if (ptid
== minus_one_ptid
)
3275 xsnprintf (buf
, endbuf
- buf
, "-1");
3277 write_ptid (buf
, endbuf
, ptid
);
3281 rs
->general_thread
= ptid
;
3283 rs
->continue_thread
= ptid
;
3287 remote_target::set_general_thread (ptid_t ptid
)
3289 set_thread (ptid
, 1);
3293 remote_target::set_continue_thread (ptid_t ptid
)
3295 set_thread (ptid
, 0);
3298 /* Change the remote current process. Which thread within the process
3299 ends up selected isn't important, as long as it is the same process
3300 as what INFERIOR_PTID points to.
3302 This comes from that fact that there is no explicit notion of
3303 "selected process" in the protocol. The selected process for
3304 general operations is the process the selected general thread
3308 remote_target::set_general_process ()
3310 /* If the remote can't handle multiple processes, don't bother. */
3311 if (!m_features
.remote_multi_process_p ())
3314 remote_state
*rs
= get_remote_state ();
3316 /* We only need to change the remote current thread if it's pointing
3317 at some other process. */
3318 if (rs
->general_thread
.pid () != inferior_ptid
.pid ())
3319 set_general_thread (inferior_ptid
);
3323 /* Return nonzero if this is the main thread that we made up ourselves
3324 to model non-threaded targets as single-threaded. */
3327 remote_thread_always_alive (ptid_t ptid
)
3329 if (ptid
== magic_null_ptid
)
3330 /* The main thread is always alive. */
3333 if (ptid
.pid () != 0 && ptid
.lwp () == 0)
3334 /* The main thread is always alive. This can happen after a
3335 vAttach, if the remote side doesn't support
3342 /* Return nonzero if the thread PTID is still alive on the remote
3346 remote_target::thread_alive (ptid_t ptid
)
3348 struct remote_state
*rs
= get_remote_state ();
3351 /* Check if this is a thread that we made up ourselves to model
3352 non-threaded targets as single-threaded. */
3353 if (remote_thread_always_alive (ptid
))
3356 p
= rs
->buf
.data ();
3357 endp
= p
+ get_remote_packet_size ();
3360 write_ptid (p
, endp
, ptid
);
3364 return (rs
->buf
[0] == 'O' && rs
->buf
[1] == 'K');
3367 /* Return a pointer to a thread name if we know it and NULL otherwise.
3368 The thread_info object owns the memory for the name. */
3371 remote_target::thread_name (struct thread_info
*info
)
3373 if (info
->priv
!= NULL
)
3375 const std::string
&name
= get_remote_thread_info (info
)->name
;
3376 return !name
.empty () ? name
.c_str () : NULL
;
3382 /* About these extended threadlist and threadinfo packets. They are
3383 variable length packets but, the fields within them are often fixed
3384 length. They are redundant enough to send over UDP as is the
3385 remote protocol in general. There is a matching unit test module
3388 /* WARNING: This threadref data structure comes from the remote O.S.,
3389 libstub protocol encoding, and remote.c. It is not particularly
3392 /* Right now, the internal structure is int. We want it to be bigger.
3393 Plan to fix this. */
3395 typedef int gdb_threadref
; /* Internal GDB thread reference. */
3397 /* gdb_ext_thread_info is an internal GDB data structure which is
3398 equivalent to the reply of the remote threadinfo packet. */
3400 struct gdb_ext_thread_info
3402 threadref threadid
; /* External form of thread reference. */
3403 int active
; /* Has state interesting to GDB?
3405 char display
[256]; /* Brief state display, name,
3406 blocked/suspended. */
3407 char shortname
[32]; /* To be used to name threads. */
3408 char more_display
[256]; /* Long info, statistics, queue depth,
3412 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
3414 static const char *unpack_nibble (const char *buf
, int *val
);
3416 static const char *unpack_byte (const char *buf
, int *value
);
3418 static char *pack_int (char *buf
, int value
);
3420 static const char *unpack_int (const char *buf
, int *value
);
3422 static const char *unpack_string (const char *src
, char *dest
, int length
);
3424 static char *pack_threadid (char *pkt
, threadref
*id
);
3426 static const char *unpack_threadid (const char *inbuf
, threadref
*id
);
3428 void int_to_threadref (threadref
*id
, int value
);
3430 static int threadref_to_int (threadref
*ref
);
3432 static void copy_threadref (threadref
*dest
, threadref
*src
);
3434 static int threadmatch (threadref
*dest
, threadref
*src
);
3436 static char *pack_threadinfo_request (char *pkt
, int mode
,
3439 static char *pack_threadlist_request (char *pkt
, int startflag
,
3441 threadref
*nextthread
);
3443 static int remote_newthread_step (threadref
*ref
, void *context
);
3446 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
3447 buffer we're allowed to write to. Returns
3448 BUF+CHARACTERS_WRITTEN. */
3451 remote_target::write_ptid (char *buf
, const char *endbuf
, ptid_t ptid
)
3455 if (m_features
.remote_multi_process_p ())
3459 buf
+= xsnprintf (buf
, endbuf
- buf
, "p-%x.", -pid
);
3461 buf
+= xsnprintf (buf
, endbuf
- buf
, "p%x.", pid
);
3465 buf
+= xsnprintf (buf
, endbuf
- buf
, "-%x", -tid
);
3467 buf
+= xsnprintf (buf
, endbuf
- buf
, "%x", tid
);
3472 /* Extract a PTID from BUF. If non-null, OBUF is set to one past the
3473 last parsed char. Returns null_ptid if no thread id is found, and
3474 throws an error if the thread id has an invalid format. */
3477 read_ptid (const char *buf
, const char **obuf
)
3479 const char *p
= buf
;
3481 ULONGEST pid
= 0, tid
= 0;
3485 /* Multi-process ptid. */
3486 pp
= unpack_varlen_hex (p
+ 1, &pid
);
3488 error (_("invalid remote ptid: %s"), p
);
3491 pp
= unpack_varlen_hex (p
+ 1, &tid
);
3494 return ptid_t (pid
, tid
);
3497 /* No multi-process. Just a tid. */
3498 pp
= unpack_varlen_hex (p
, &tid
);
3500 /* Return null_ptid when no thread id is found. */
3508 /* Since the stub is not sending a process id, default to what's
3509 current_inferior, unless it doesn't have a PID yet. If so,
3510 then since there's no way to know the pid of the reported
3511 threads, use the magic number. */
3512 inferior
*inf
= current_inferior ();
3514 pid
= magic_null_ptid
.pid ();
3520 return ptid_t (pid
, tid
);
3526 if (ch
>= 'a' && ch
<= 'f')
3527 return ch
- 'a' + 10;
3528 if (ch
>= '0' && ch
<= '9')
3530 if (ch
>= 'A' && ch
<= 'F')
3531 return ch
- 'A' + 10;
3536 stub_unpack_int (const char *buff
, int fieldlength
)
3543 nibble
= stubhex (*buff
++);
3547 retval
= retval
<< 4;
3553 unpack_nibble (const char *buf
, int *val
)
3555 *val
= fromhex (*buf
++);
3560 unpack_byte (const char *buf
, int *value
)
3562 *value
= stub_unpack_int (buf
, 2);
3567 pack_int (char *buf
, int value
)
3569 buf
= pack_hex_byte (buf
, (value
>> 24) & 0xff);
3570 buf
= pack_hex_byte (buf
, (value
>> 16) & 0xff);
3571 buf
= pack_hex_byte (buf
, (value
>> 8) & 0x0ff);
3572 buf
= pack_hex_byte (buf
, (value
& 0xff));
3577 unpack_int (const char *buf
, int *value
)
3579 *value
= stub_unpack_int (buf
, 8);
3583 #if 0 /* Currently unused, uncomment when needed. */
3584 static char *pack_string (char *pkt
, char *string
);
3587 pack_string (char *pkt
, char *string
)
3592 len
= strlen (string
);
3594 len
= 200; /* Bigger than most GDB packets, junk??? */
3595 pkt
= pack_hex_byte (pkt
, len
);
3599 if ((ch
== '\0') || (ch
== '#'))
3600 ch
= '*'; /* Protect encapsulation. */
3605 #endif /* 0 (unused) */
3608 unpack_string (const char *src
, char *dest
, int length
)
3617 pack_threadid (char *pkt
, threadref
*id
)
3620 unsigned char *altid
;
3622 altid
= (unsigned char *) id
;
3623 limit
= pkt
+ BUF_THREAD_ID_SIZE
;
3625 pkt
= pack_hex_byte (pkt
, *altid
++);
3631 unpack_threadid (const char *inbuf
, threadref
*id
)
3634 const char *limit
= inbuf
+ BUF_THREAD_ID_SIZE
;
3637 altref
= (char *) id
;
3639 while (inbuf
< limit
)
3641 x
= stubhex (*inbuf
++);
3642 y
= stubhex (*inbuf
++);
3643 *altref
++ = (x
<< 4) | y
;
3648 /* Externally, threadrefs are 64 bits but internally, they are still
3649 ints. This is due to a mismatch of specifications. We would like
3650 to use 64bit thread references internally. This is an adapter
3654 int_to_threadref (threadref
*id
, int value
)
3656 unsigned char *scan
;
3658 scan
= (unsigned char *) id
;
3664 *scan
++ = (value
>> 24) & 0xff;
3665 *scan
++ = (value
>> 16) & 0xff;
3666 *scan
++ = (value
>> 8) & 0xff;
3667 *scan
++ = (value
& 0xff);
3671 threadref_to_int (threadref
*ref
)
3674 unsigned char *scan
;
3680 value
= (value
<< 8) | ((*scan
++) & 0xff);
3685 copy_threadref (threadref
*dest
, threadref
*src
)
3688 unsigned char *csrc
, *cdest
;
3690 csrc
= (unsigned char *) src
;
3691 cdest
= (unsigned char *) dest
;
3698 threadmatch (threadref
*dest
, threadref
*src
)
3700 /* Things are broken right now, so just assume we got a match. */
3702 unsigned char *srcp
, *destp
;
3704 srcp
= (char *) src
;
3705 destp
= (char *) dest
;
3709 result
&= (*srcp
++ == *destp
++) ? 1 : 0;
3716 threadid:1, # always request threadid
3723 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
3726 pack_threadinfo_request (char *pkt
, int mode
, threadref
*id
)
3728 *pkt
++ = 'q'; /* Info Query */
3729 *pkt
++ = 'P'; /* process or thread info */
3730 pkt
= pack_int (pkt
, mode
); /* mode */
3731 pkt
= pack_threadid (pkt
, id
); /* threadid */
3732 *pkt
= '\0'; /* terminate */
3736 /* These values tag the fields in a thread info response packet. */
3737 /* Tagging the fields allows us to request specific fields and to
3738 add more fields as time goes by. */
3740 #define TAG_THREADID 1 /* Echo the thread identifier. */
3741 #define TAG_EXISTS 2 /* Is this process defined enough to
3742 fetch registers and its stack? */
3743 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
3744 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
3745 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
3749 remote_target::remote_unpack_thread_info_response (const char *pkt
,
3750 threadref
*expectedref
,
3751 gdb_ext_thread_info
*info
)
3753 struct remote_state
*rs
= get_remote_state ();
3757 const char *limit
= pkt
+ rs
->buf
.size (); /* Plausible parsing limit. */
3760 /* info->threadid = 0; FIXME: implement zero_threadref. */
3762 info
->display
[0] = '\0';
3763 info
->shortname
[0] = '\0';
3764 info
->more_display
[0] = '\0';
3766 /* Assume the characters indicating the packet type have been
3768 pkt
= unpack_int (pkt
, &mask
); /* arg mask */
3769 pkt
= unpack_threadid (pkt
, &ref
);
3772 warning (_("Incomplete response to threadinfo request."));
3773 if (!threadmatch (&ref
, expectedref
))
3774 { /* This is an answer to a different request. */
3775 warning (_("ERROR RMT Thread info mismatch."));
3778 copy_threadref (&info
->threadid
, &ref
);
3780 /* Loop on tagged fields , try to bail if something goes wrong. */
3782 /* Packets are terminated with nulls. */
3783 while ((pkt
< limit
) && mask
&& *pkt
)
3785 pkt
= unpack_int (pkt
, &tag
); /* tag */
3786 pkt
= unpack_byte (pkt
, &length
); /* length */
3787 if (!(tag
& mask
)) /* Tags out of synch with mask. */
3789 warning (_("ERROR RMT: threadinfo tag mismatch."));
3793 if (tag
== TAG_THREADID
)
3797 warning (_("ERROR RMT: length of threadid is not 16."));
3801 pkt
= unpack_threadid (pkt
, &ref
);
3802 mask
= mask
& ~TAG_THREADID
;
3805 if (tag
== TAG_EXISTS
)
3807 info
->active
= stub_unpack_int (pkt
, length
);
3809 mask
= mask
& ~(TAG_EXISTS
);
3812 warning (_("ERROR RMT: 'exists' length too long."));
3818 if (tag
== TAG_THREADNAME
)
3820 pkt
= unpack_string (pkt
, &info
->shortname
[0], length
);
3821 mask
= mask
& ~TAG_THREADNAME
;
3824 if (tag
== TAG_DISPLAY
)
3826 pkt
= unpack_string (pkt
, &info
->display
[0], length
);
3827 mask
= mask
& ~TAG_DISPLAY
;
3830 if (tag
== TAG_MOREDISPLAY
)
3832 pkt
= unpack_string (pkt
, &info
->more_display
[0], length
);
3833 mask
= mask
& ~TAG_MOREDISPLAY
;
3836 warning (_("ERROR RMT: unknown thread info tag."));
3837 break; /* Not a tag we know about. */
3843 remote_target::remote_get_threadinfo (threadref
*threadid
,
3845 gdb_ext_thread_info
*info
)
3847 struct remote_state
*rs
= get_remote_state ();
3850 pack_threadinfo_request (rs
->buf
.data (), fieldset
, threadid
);
3854 if (rs
->buf
[0] == '\0')
3857 result
= remote_unpack_thread_info_response (&rs
->buf
[2],
3862 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
3865 pack_threadlist_request (char *pkt
, int startflag
, int threadcount
,
3866 threadref
*nextthread
)
3868 *pkt
++ = 'q'; /* info query packet */
3869 *pkt
++ = 'L'; /* Process LIST or threadLIST request */
3870 pkt
= pack_nibble (pkt
, startflag
); /* initflag 1 bytes */
3871 pkt
= pack_hex_byte (pkt
, threadcount
); /* threadcount 2 bytes */
3872 pkt
= pack_threadid (pkt
, nextthread
); /* 64 bit thread identifier */
3877 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
3880 remote_target::parse_threadlist_response (const char *pkt
, int result_limit
,
3881 threadref
*original_echo
,
3882 threadref
*resultlist
,
3885 struct remote_state
*rs
= get_remote_state ();
3886 int count
, resultcount
, done
;
3889 /* Assume the 'q' and 'M chars have been stripped. */
3890 const char *limit
= pkt
+ (rs
->buf
.size () - BUF_THREAD_ID_SIZE
);
3891 /* done parse past here */
3892 pkt
= unpack_byte (pkt
, &count
); /* count field */
3893 pkt
= unpack_nibble (pkt
, &done
);
3894 /* The first threadid is the argument threadid. */
3895 pkt
= unpack_threadid (pkt
, original_echo
); /* should match query packet */
3896 while ((count
-- > 0) && (pkt
< limit
))
3898 pkt
= unpack_threadid (pkt
, resultlist
++);
3899 if (resultcount
++ >= result_limit
)
3907 /* Fetch the next batch of threads from the remote. Returns -1 if the
3908 qL packet is not supported, 0 on error and 1 on success. */
3911 remote_target::remote_get_threadlist (int startflag
, threadref
*nextthread
,
3912 int result_limit
, int *done
, int *result_count
,
3913 threadref
*threadlist
)
3915 struct remote_state
*rs
= get_remote_state ();
3918 /* Truncate result limit to be smaller than the packet size. */
3919 if ((((result_limit
+ 1) * BUF_THREAD_ID_SIZE
) + 10)
3920 >= get_remote_packet_size ())
3921 result_limit
= (get_remote_packet_size () / BUF_THREAD_ID_SIZE
) - 2;
3923 pack_threadlist_request (rs
->buf
.data (), startflag
, result_limit
,
3927 if (rs
->buf
[0] == '\0')
3929 /* Packet not supported. */
3934 parse_threadlist_response (&rs
->buf
[2], result_limit
,
3935 &rs
->echo_nextthread
, threadlist
, done
);
3937 if (!threadmatch (&rs
->echo_nextthread
, nextthread
))
3939 /* FIXME: This is a good reason to drop the packet. */
3940 /* Possibly, there is a duplicate response. */
3942 retransmit immediately - race conditions
3943 retransmit after timeout - yes
3945 wait for packet, then exit
3947 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
3948 return 0; /* I choose simply exiting. */
3950 if (*result_count
<= 0)
3954 warning (_("RMT ERROR : failed to get remote thread list."));
3957 return result
; /* break; */
3959 if (*result_count
> result_limit
)
3962 warning (_("RMT ERROR: threadlist response longer than requested."));
3968 /* Fetch the list of remote threads, with the qL packet, and call
3969 STEPFUNCTION for each thread found. Stops iterating and returns 1
3970 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
3971 STEPFUNCTION returns false. If the packet is not supported,
3975 remote_target::remote_threadlist_iterator (rmt_thread_action stepfunction
,
3976 void *context
, int looplimit
)
3978 struct remote_state
*rs
= get_remote_state ();
3979 int done
, i
, result_count
;
3987 if (loopcount
++ > looplimit
)
3990 warning (_("Remote fetch threadlist -infinite loop-."));
3993 result
= remote_get_threadlist (startflag
, &rs
->nextthread
,
3994 MAXTHREADLISTRESULTS
,
3995 &done
, &result_count
,
3996 rs
->resultthreadlist
);
3999 /* Clear for later iterations. */
4001 /* Setup to resume next batch of thread references, set nextthread. */
4002 if (result_count
>= 1)
4003 copy_threadref (&rs
->nextthread
,
4004 &rs
->resultthreadlist
[result_count
- 1]);
4006 while (result_count
--)
4008 if (!(*stepfunction
) (&rs
->resultthreadlist
[i
++], context
))
4018 /* A thread found on the remote target. */
4022 explicit thread_item (ptid_t ptid_
)
4026 thread_item (thread_item
&&other
) = default;
4027 thread_item
&operator= (thread_item
&&other
) = default;
4029 DISABLE_COPY_AND_ASSIGN (thread_item
);
4031 /* The thread's PTID. */
4034 /* The thread's extra info. */
4037 /* The thread's name. */
4040 /* The thread's id, translated to a string for displaying. */
4043 /* The core the thread was running on. -1 if not known. */
4046 /* The thread handle associated with the thread. */
4047 gdb::byte_vector thread_handle
;
4050 /* Context passed around to the various methods listing remote
4051 threads. As new threads are found, they're added to the ITEMS
4054 struct threads_listing_context
4056 /* Return true if this object contains an entry for a thread with ptid
4059 bool contains_thread (ptid_t ptid
) const
4061 auto match_ptid
= [&] (const thread_item
&item
)
4063 return item
.ptid
== ptid
;
4066 auto it
= std::find_if (this->items
.begin (),
4070 return it
!= this->items
.end ();
4073 /* Remove the thread with ptid PTID. */
4075 void remove_thread (ptid_t ptid
)
4077 auto match_ptid
= [&] (const thread_item
&item
)
4079 return item
.ptid
== ptid
;
4082 auto it
= std::remove_if (this->items
.begin (),
4086 if (it
!= this->items
.end ())
4087 this->items
.erase (it
);
4090 /* The threads found on the remote target. */
4091 std::vector
<thread_item
> items
;
4095 remote_newthread_step (threadref
*ref
, void *data
)
4097 struct threads_listing_context
*context
4098 = (struct threads_listing_context
*) data
;
4099 int pid
= inferior_ptid
.pid ();
4100 int lwp
= threadref_to_int (ref
);
4101 ptid_t
ptid (pid
, lwp
);
4103 context
->items
.emplace_back (ptid
);
4105 return 1; /* continue iterator */
4108 #define CRAZY_MAX_THREADS 1000
4111 remote_target::remote_current_thread (ptid_t oldpid
)
4113 struct remote_state
*rs
= get_remote_state ();
4117 if (rs
->buf
[0] == 'Q' && rs
->buf
[1] == 'C')
4122 result
= read_ptid (&rs
->buf
[2], &obuf
);
4124 remote_debug_printf ("warning: garbage in qC reply");
4132 /* List remote threads using the deprecated qL packet. */
4135 remote_target::remote_get_threads_with_ql (threads_listing_context
*context
)
4137 if (remote_threadlist_iterator (remote_newthread_step
, context
,
4138 CRAZY_MAX_THREADS
) >= 0)
4144 #if defined(HAVE_LIBEXPAT)
4147 start_thread (struct gdb_xml_parser
*parser
,
4148 const struct gdb_xml_element
*element
,
4150 std::vector
<gdb_xml_value
> &attributes
)
4152 struct threads_listing_context
*data
4153 = (struct threads_listing_context
*) user_data
;
4154 struct gdb_xml_value
*attr
;
4156 char *id
= (char *) xml_find_attribute (attributes
, "id")->value
.get ();
4157 ptid_t ptid
= read_ptid (id
, NULL
);
4159 thread_item
&item
= data
->items
.emplace_back (ptid
);
4161 attr
= xml_find_attribute (attributes
, "core");
4163 item
.core
= *(ULONGEST
*) attr
->value
.get ();
4165 attr
= xml_find_attribute (attributes
, "name");
4167 item
.name
= (const char *) attr
->value
.get ();
4169 attr
= xml_find_attribute (attributes
, "id_str");
4170 if (attr
!= nullptr)
4171 item
.id_str
= (const char *) attr
->value
.get ();
4173 attr
= xml_find_attribute (attributes
, "handle");
4175 item
.thread_handle
= hex2bin ((const char *) attr
->value
.get ());
4179 end_thread (struct gdb_xml_parser
*parser
,
4180 const struct gdb_xml_element
*element
,
4181 void *user_data
, const char *body_text
)
4183 struct threads_listing_context
*data
4184 = (struct threads_listing_context
*) user_data
;
4186 if (body_text
!= NULL
&& *body_text
!= '\0')
4187 data
->items
.back ().extra
= body_text
;
4190 const struct gdb_xml_attribute thread_attributes
[] = {
4191 { "id", GDB_XML_AF_NONE
, NULL
, NULL
},
4192 { "core", GDB_XML_AF_OPTIONAL
, gdb_xml_parse_attr_ulongest
, NULL
},
4193 { "name", GDB_XML_AF_OPTIONAL
, NULL
, NULL
},
4194 { "id_str", GDB_XML_AF_OPTIONAL
, NULL
, NULL
},
4195 { "handle", GDB_XML_AF_OPTIONAL
, NULL
, NULL
},
4196 { NULL
, GDB_XML_AF_NONE
, NULL
, NULL
}
4199 const struct gdb_xml_element thread_children
[] = {
4200 { NULL
, NULL
, NULL
, GDB_XML_EF_NONE
, NULL
, NULL
}
4203 const struct gdb_xml_element threads_children
[] = {
4204 { "thread", thread_attributes
, thread_children
,
4205 GDB_XML_EF_REPEATABLE
| GDB_XML_EF_OPTIONAL
,
4206 start_thread
, end_thread
},
4207 { NULL
, NULL
, NULL
, GDB_XML_EF_NONE
, NULL
, NULL
}
4210 const struct gdb_xml_element threads_elements
[] = {
4211 { "threads", NULL
, threads_children
,
4212 GDB_XML_EF_NONE
, NULL
, NULL
},
4213 { NULL
, NULL
, NULL
, GDB_XML_EF_NONE
, NULL
, NULL
}
4218 /* List remote threads using qXfer:threads:read. */
4221 remote_target::remote_get_threads_with_qxfer (threads_listing_context
*context
)
4223 #if defined(HAVE_LIBEXPAT)
4224 if (m_features
.packet_support (PACKET_qXfer_threads
) == PACKET_ENABLE
)
4226 std::optional
<gdb::char_vector
> xml
4227 = target_read_stralloc (this, TARGET_OBJECT_THREADS
, NULL
);
4229 if (xml
&& (*xml
)[0] != '\0')
4231 gdb_xml_parse_quick (_("threads"), "threads.dtd",
4232 threads_elements
, xml
->data (), context
);
4242 /* List remote threads using qfThreadInfo/qsThreadInfo. */
4245 remote_target::remote_get_threads_with_qthreadinfo (threads_listing_context
*context
)
4247 struct remote_state
*rs
= get_remote_state ();
4249 if (rs
->use_threadinfo_query
)
4253 putpkt ("qfThreadInfo");
4255 bufp
= rs
->buf
.data ();
4256 if (bufp
[0] != '\0') /* q packet recognized */
4258 while (*bufp
++ == 'm') /* reply contains one or more TID */
4262 ptid_t ptid
= read_ptid (bufp
, &bufp
);
4263 context
->items
.emplace_back (ptid
);
4265 while (*bufp
++ == ','); /* comma-separated list */
4266 putpkt ("qsThreadInfo");
4268 bufp
= rs
->buf
.data ();
4274 /* Packet not recognized. */
4275 rs
->use_threadinfo_query
= 0;
4282 /* Return true if INF only has one non-exited thread. */
4285 has_single_non_exited_thread (inferior
*inf
)
4288 for (thread_info
*tp ATTRIBUTE_UNUSED
: inf
->non_exited_threads ())
4294 /* Implement the to_update_thread_list function for the remote
4298 remote_target::update_thread_list ()
4300 struct threads_listing_context context
;
4303 /* We have a few different mechanisms to fetch the thread list. Try
4304 them all, starting with the most preferred one first, falling
4305 back to older methods. */
4306 if (remote_get_threads_with_qxfer (&context
)
4307 || remote_get_threads_with_qthreadinfo (&context
)
4308 || remote_get_threads_with_ql (&context
))
4312 if (context
.items
.empty ()
4313 && remote_thread_always_alive (inferior_ptid
))
4315 /* Some targets don't really support threads, but still
4316 reply an (empty) thread list in response to the thread
4317 listing packets, instead of replying "packet not
4318 supported". Exit early so we don't delete the main
4323 /* CONTEXT now holds the current thread list on the remote
4324 target end. Delete GDB-side threads no longer found on the
4326 for (thread_info
*tp
: all_threads_safe ())
4328 if (tp
->inf
->process_target () != this)
4331 if (!context
.contains_thread (tp
->ptid
))
4333 /* Do not remove the thread if it is the last thread in
4334 the inferior. This situation happens when we have a
4335 pending exit process status to process. Otherwise we
4336 may end up with a seemingly live inferior (i.e. pid
4337 != 0) that has no threads. */
4338 if (has_single_non_exited_thread (tp
->inf
))
4341 /* Do not remove the thread if we've requested to be
4342 notified of its exit. For example, the thread may be
4343 displaced stepping, infrun will need to handle the
4344 exit event, and displaced stepping info is recorded
4345 in the thread object. If we deleted the thread now,
4346 we'd lose that info. */
4347 if ((tp
->thread_options () & GDB_THREAD_OPTION_EXIT
) != 0)
4355 /* Remove any unreported fork/vfork/clone child threads from
4356 CONTEXT so that we don't interfere with follow
4357 fork/vfork/clone, which is where creation of such threads is
4359 remove_new_children (&context
);
4361 /* And now add threads we don't know about yet to our list. */
4362 for (thread_item
&item
: context
.items
)
4364 if (item
.ptid
!= null_ptid
)
4366 /* In non-stop mode, we assume new found threads are
4367 executing until proven otherwise with a stop reply.
4368 In all-stop, we can only get here if all threads are
4370 bool executing
= target_is_non_stop_p ();
4372 remote_notice_new_inferior (item
.ptid
, executing
);
4374 thread_info
*tp
= this->find_thread (item
.ptid
);
4375 remote_thread_info
*info
= get_remote_thread_info (tp
);
4376 info
->core
= item
.core
;
4377 info
->extra
= std::move (item
.extra
);
4378 info
->name
= std::move (item
.name
);
4379 info
->id_str
= std::move (item
.id_str
);
4380 info
->thread_handle
= std::move (item
.thread_handle
);
4387 /* If no thread listing method is supported, then query whether
4388 each known thread is alive, one by one, with the T packet.
4389 If the target doesn't support threads at all, then this is a
4390 no-op. See remote_thread_alive. */
4396 * Collect a descriptive string about the given thread.
4397 * The target may say anything it wants to about the thread
4398 * (typically info about its blocked / runnable state, name, etc.).
4399 * This string will appear in the info threads display.
4401 * Optional: targets are not required to implement this function.
4405 remote_target::extra_thread_info (thread_info
*tp
)
4407 struct remote_state
*rs
= get_remote_state ();
4410 struct gdb_ext_thread_info threadinfo
;
4412 if (rs
->remote_desc
== 0) /* paranoia */
4413 internal_error (_("remote_threads_extra_info"));
4415 if (tp
->ptid
== magic_null_ptid
4416 || (tp
->ptid
.pid () != 0 && tp
->ptid
.lwp () == 0))
4417 /* This is the main thread which was added by GDB. The remote
4418 server doesn't know about it. */
4421 std::string
&extra
= get_remote_thread_info (tp
)->extra
;
4423 /* If already have cached info, use it. */
4424 if (!extra
.empty ())
4425 return extra
.c_str ();
4427 if (m_features
.packet_support (PACKET_qXfer_threads
) == PACKET_ENABLE
)
4429 /* If we're using qXfer:threads:read, then the extra info is
4430 included in the XML. So if we didn't have anything cached,
4431 it's because there's really no extra info. */
4435 if (rs
->use_threadextra_query
)
4437 char *b
= rs
->buf
.data ();
4438 char *endb
= b
+ get_remote_packet_size ();
4440 xsnprintf (b
, endb
- b
, "qThreadExtraInfo,");
4442 write_ptid (b
, endb
, tp
->ptid
);
4446 if (rs
->buf
[0] != 0)
4448 extra
.resize (strlen (rs
->buf
.data ()) / 2);
4449 hex2bin (rs
->buf
.data (), (gdb_byte
*) &extra
[0], extra
.size ());
4450 return extra
.c_str ();
4454 /* If the above query fails, fall back to the old method. */
4455 rs
->use_threadextra_query
= 0;
4456 set
= TAG_THREADID
| TAG_EXISTS
| TAG_THREADNAME
4457 | TAG_MOREDISPLAY
| TAG_DISPLAY
;
4458 int_to_threadref (&id
, tp
->ptid
.lwp ());
4459 if (remote_get_threadinfo (&id
, set
, &threadinfo
))
4460 if (threadinfo
.active
)
4462 if (*threadinfo
.shortname
)
4463 string_appendf (extra
, " Name: %s", threadinfo
.shortname
);
4464 if (*threadinfo
.display
)
4466 if (!extra
.empty ())
4468 string_appendf (extra
, " State: %s", threadinfo
.display
);
4470 if (*threadinfo
.more_display
)
4472 if (!extra
.empty ())
4474 string_appendf (extra
, " Priority: %s", threadinfo
.more_display
);
4476 return extra
.c_str ();
4483 remote_target::static_tracepoint_marker_at (CORE_ADDR addr
,
4484 struct static_tracepoint_marker
*marker
)
4486 struct remote_state
*rs
= get_remote_state ();
4487 char *p
= rs
->buf
.data ();
4489 xsnprintf (p
, get_remote_packet_size (), "qTSTMat:");
4491 p
+= hexnumstr (p
, addr
);
4494 p
= rs
->buf
.data ();
4497 error (_("Remote failure reply: %s"), p
);
4501 parse_static_tracepoint_marker_definition (p
, NULL
, marker
);
4508 std::vector
<static_tracepoint_marker
>
4509 remote_target::static_tracepoint_markers_by_strid (const char *strid
)
4511 struct remote_state
*rs
= get_remote_state ();
4512 std::vector
<static_tracepoint_marker
> markers
;
4514 static_tracepoint_marker marker
;
4516 /* Ask for a first packet of static tracepoint marker
4520 p
= rs
->buf
.data ();
4522 error (_("Remote failure reply: %s"), p
);
4528 parse_static_tracepoint_marker_definition (p
, &p
, &marker
);
4530 if (strid
== NULL
|| marker
.str_id
== strid
)
4531 markers
.push_back (std::move (marker
));
4533 while (*p
++ == ','); /* comma-separated list */
4534 /* Ask for another packet of static tracepoint definition. */
4537 p
= rs
->buf
.data ();
4544 /* Implement the to_get_ada_task_ptid function for the remote targets. */
4547 remote_target::get_ada_task_ptid (long lwp
, ULONGEST thread
)
4549 return ptid_t (inferior_ptid
.pid (), lwp
);
4553 /* Restart the remote side; this is an extended protocol operation. */
4556 remote_target::extended_remote_restart ()
4558 struct remote_state
*rs
= get_remote_state ();
4560 /* Send the restart command; for reasons I don't understand the
4561 remote side really expects a number after the "R". */
4562 xsnprintf (rs
->buf
.data (), get_remote_packet_size (), "R%x", 0);
4565 remote_fileio_reset ();
4568 /* Clean up connection to a remote debugger. */
4571 remote_target::close ()
4573 /* Make sure we leave stdin registered in the event loop. */
4576 trace_reset_local_state ();
4581 remote_target::~remote_target ()
4583 struct remote_state
*rs
= get_remote_state ();
4585 /* Check for NULL because we may get here with a partially
4586 constructed target/connection. */
4587 if (rs
->remote_desc
== nullptr)
4590 serial_close (rs
->remote_desc
);
4592 /* We are destroying the remote target, so we should discard
4593 everything of this target. */
4594 discard_pending_stop_replies_in_queue ();
4596 rs
->delete_async_event_handler ();
4598 delete rs
->notif_state
;
4601 /* Query the remote side for the text, data and bss offsets. */
4604 remote_target::get_offsets ()
4606 struct remote_state
*rs
= get_remote_state ();
4609 int lose
, num_segments
= 0, do_sections
, do_segments
;
4610 CORE_ADDR text_addr
, data_addr
, bss_addr
, segments
[2];
4612 if (current_program_space
->symfile_object_file
== NULL
)
4615 putpkt ("qOffsets");
4617 buf
= rs
->buf
.data ();
4619 if (buf
[0] == '\000')
4620 return; /* Return silently. Stub doesn't support
4624 warning (_("Remote failure reply: %s"), buf
);
4628 /* Pick up each field in turn. This used to be done with scanf, but
4629 scanf will make trouble if CORE_ADDR size doesn't match
4630 conversion directives correctly. The following code will work
4631 with any size of CORE_ADDR. */
4632 text_addr
= data_addr
= bss_addr
= 0;
4636 if (startswith (ptr
, "Text="))
4639 /* Don't use strtol, could lose on big values. */
4640 while (*ptr
&& *ptr
!= ';')
4641 text_addr
= (text_addr
<< 4) + fromhex (*ptr
++);
4643 if (startswith (ptr
, ";Data="))
4646 while (*ptr
&& *ptr
!= ';')
4647 data_addr
= (data_addr
<< 4) + fromhex (*ptr
++);
4652 if (!lose
&& startswith (ptr
, ";Bss="))
4655 while (*ptr
&& *ptr
!= ';')
4656 bss_addr
= (bss_addr
<< 4) + fromhex (*ptr
++);
4658 if (bss_addr
!= data_addr
)
4659 warning (_("Target reported unsupported offsets: %s"), buf
);
4664 else if (startswith (ptr
, "TextSeg="))
4667 /* Don't use strtol, could lose on big values. */
4668 while (*ptr
&& *ptr
!= ';')
4669 text_addr
= (text_addr
<< 4) + fromhex (*ptr
++);
4672 if (startswith (ptr
, ";DataSeg="))
4675 while (*ptr
&& *ptr
!= ';')
4676 data_addr
= (data_addr
<< 4) + fromhex (*ptr
++);
4684 error (_("Malformed response to offset query, %s"), buf
);
4685 else if (*ptr
!= '\0')
4686 warning (_("Target reported unsupported offsets: %s"), buf
);
4688 objfile
*objf
= current_program_space
->symfile_object_file
;
4689 section_offsets offs
= objf
->section_offsets
;
4691 symfile_segment_data_up data
= get_symfile_segment_data (objf
->obfd
.get ());
4692 do_segments
= (data
!= NULL
);
4693 do_sections
= num_segments
== 0;
4695 if (num_segments
> 0)
4697 segments
[0] = text_addr
;
4698 segments
[1] = data_addr
;
4700 /* If we have two segments, we can still try to relocate everything
4701 by assuming that the .text and .data offsets apply to the whole
4702 text and data segments. Convert the offsets given in the packet
4703 to base addresses for symfile_map_offsets_to_segments. */
4704 else if (data
!= nullptr && data
->segments
.size () == 2)
4706 segments
[0] = data
->segments
[0].base
+ text_addr
;
4707 segments
[1] = data
->segments
[1].base
+ data_addr
;
4710 /* If the object file has only one segment, assume that it is text
4711 rather than data; main programs with no writable data are rare,
4712 but programs with no code are useless. Of course the code might
4713 have ended up in the data segment... to detect that we would need
4714 the permissions here. */
4715 else if (data
&& data
->segments
.size () == 1)
4717 segments
[0] = data
->segments
[0].base
+ text_addr
;
4720 /* There's no way to relocate by segment. */
4726 int ret
= symfile_map_offsets_to_segments (objf
->obfd
.get (),
4728 num_segments
, segments
);
4730 if (ret
== 0 && !do_sections
)
4731 error (_("Can not handle qOffsets TextSeg "
4732 "response with this symbol file"));
4740 offs
[SECT_OFF_TEXT (objf
)] = text_addr
;
4742 /* This is a temporary kludge to force data and bss to use the
4743 same offsets because that's what nlmconv does now. The real
4744 solution requires changes to the stub and remote.c that I
4745 don't have time to do right now. */
4747 offs
[SECT_OFF_DATA (objf
)] = data_addr
;
4748 offs
[SECT_OFF_BSS (objf
)] = data_addr
;
4751 objfile_relocate (objf
, offs
);
4754 /* Send interrupt_sequence to remote target. */
4757 remote_target::send_interrupt_sequence ()
4759 if (interrupt_sequence_mode
== interrupt_sequence_control_c
)
4760 remote_serial_write ("\x03", 1);
4761 else if (interrupt_sequence_mode
== interrupt_sequence_break
)
4762 remote_serial_send_break ();
4763 else if (interrupt_sequence_mode
== interrupt_sequence_break_g
)
4765 remote_serial_send_break ();
4766 remote_serial_write ("g", 1);
4769 internal_error (_("Invalid value for interrupt_sequence_mode: %s."),
4770 interrupt_sequence_mode
);
4773 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
4774 and extract the PTID. Returns NULL_PTID if not found. */
4777 stop_reply_extract_thread (const char *stop_reply
)
4779 if (stop_reply
[0] == 'T' && strlen (stop_reply
) > 3)
4783 /* Txx r:val ; r:val (...) */
4786 /* Look for "register" named "thread". */
4791 p1
= strchr (p
, ':');
4795 if (strncmp (p
, "thread", p1
- p
) == 0)
4796 return read_ptid (++p1
, &p
);
4798 p1
= strchr (p
, ';');
4810 /* Determine the remote side's current thread. If we have a stop
4811 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
4812 "thread" register we can extract the current thread from. If not,
4813 ask the remote which is the current thread with qC. The former
4814 method avoids a roundtrip. */
4817 remote_target::get_current_thread (const char *wait_status
)
4819 ptid_t ptid
= null_ptid
;
4821 /* Note we don't use remote_parse_stop_reply as that makes use of
4822 the target architecture, which we haven't yet fully determined at
4824 if (wait_status
!= NULL
)
4825 ptid
= stop_reply_extract_thread (wait_status
);
4826 if (ptid
== null_ptid
)
4827 ptid
= remote_current_thread (inferior_ptid
);
4832 /* Query the remote target for which is the current thread/process,
4833 add it to our tables, and update INFERIOR_PTID. The caller is
4834 responsible for setting the state such that the remote end is ready
4835 to return the current thread.
4837 This function is called after handling the '?' or 'vRun' packets,
4838 whose response is a stop reply from which we can also try
4839 extracting the thread. If the target doesn't support the explicit
4840 qC query, we infer the current thread from that stop reply, passed
4841 in in WAIT_STATUS, which may be NULL.
4843 The function returns pointer to the main thread of the inferior. */
4846 remote_target::add_current_inferior_and_thread (const char *wait_status
)
4848 bool fake_pid_p
= false;
4850 switch_to_no_thread ();
4852 /* Now, if we have thread information, update the current thread's
4854 ptid_t curr_ptid
= get_current_thread (wait_status
);
4856 if (curr_ptid
!= null_ptid
)
4858 if (!m_features
.remote_multi_process_p ())
4863 /* Without this, some commands which require an active target
4864 (such as kill) won't work. This variable serves (at least)
4865 double duty as both the pid of the target process (if it has
4866 such), and as a flag indicating that a target is active. */
4867 curr_ptid
= magic_null_ptid
;
4871 remote_add_inferior (fake_pid_p
, curr_ptid
.pid (), -1, 1);
4873 /* Add the main thread and switch to it. Don't try reading
4874 registers yet, since we haven't fetched the target description
4876 thread_info
*tp
= add_thread_silent (this, curr_ptid
);
4877 switch_to_thread_no_regs (tp
);
4882 /* Print info about a thread that was found already stopped on
4886 remote_target::print_one_stopped_thread (thread_info
*thread
)
4888 target_waitstatus ws
;
4890 /* If there is a pending waitstatus, use it. If there isn't it's because
4891 the thread's stop was reported with TARGET_WAITKIND_STOPPED / GDB_SIGNAL_0
4892 and process_initial_stop_replies decided it wasn't interesting to save
4893 and report to the core. */
4894 if (thread
->has_pending_waitstatus ())
4896 ws
= thread
->pending_waitstatus ();
4897 thread
->clear_pending_waitstatus ();
4901 ws
.set_stopped (GDB_SIGNAL_0
);
4904 switch_to_thread (thread
);
4905 thread
->set_stop_pc (get_frame_pc (get_current_frame ()));
4906 set_current_sal_from_frame (get_current_frame ());
4908 /* For "info program". */
4909 set_last_target_status (this, thread
->ptid
, ws
);
4911 if (ws
.kind () == TARGET_WAITKIND_STOPPED
)
4913 enum gdb_signal sig
= ws
.sig ();
4915 if (signal_print_state (sig
))
4916 notify_signal_received (sig
);
4919 notify_normal_stop (nullptr, 1);
4922 /* Process all initial stop replies the remote side sent in response
4923 to the ? packet. These indicate threads that were already stopped
4924 on initial connection. We mark these threads as stopped and print
4925 their current frame before giving the user the prompt. */
4928 remote_target::process_initial_stop_replies (int from_tty
)
4930 int pending_stop_replies
= stop_reply_queue_length ();
4931 struct thread_info
*selected
= NULL
;
4932 struct thread_info
*lowest_stopped
= NULL
;
4933 struct thread_info
*first
= NULL
;
4935 /* This is only used when the target is non-stop. */
4936 gdb_assert (target_is_non_stop_p ());
4938 /* Consume the initial pending events. */
4939 while (pending_stop_replies
-- > 0)
4941 ptid_t waiton_ptid
= minus_one_ptid
;
4943 struct target_waitstatus ws
;
4944 int ignore_event
= 0;
4946 event_ptid
= target_wait (waiton_ptid
, &ws
, TARGET_WNOHANG
);
4948 print_target_wait_results (waiton_ptid
, event_ptid
, ws
, this);
4952 case TARGET_WAITKIND_IGNORE
:
4953 case TARGET_WAITKIND_NO_RESUMED
:
4954 case TARGET_WAITKIND_SIGNALLED
:
4955 case TARGET_WAITKIND_EXITED
:
4956 /* We shouldn't see these, but if we do, just ignore. */
4957 remote_debug_printf ("event ignored");
4968 thread_info
*evthread
= this->find_thread (event_ptid
);
4970 if (ws
.kind () == TARGET_WAITKIND_STOPPED
)
4972 enum gdb_signal sig
= ws
.sig ();
4974 /* Stubs traditionally report SIGTRAP as initial signal,
4975 instead of signal 0. Suppress it. */
4976 if (sig
== GDB_SIGNAL_TRAP
)
4978 evthread
->set_stop_signal (sig
);
4979 ws
.set_stopped (sig
);
4982 if (ws
.kind () != TARGET_WAITKIND_STOPPED
4983 || ws
.sig () != GDB_SIGNAL_0
)
4984 evthread
->set_pending_waitstatus (ws
);
4986 set_executing (this, event_ptid
, false);
4987 set_running (this, event_ptid
, false);
4988 get_remote_thread_info (evthread
)->set_not_resumed ();
4991 /* "Notice" the new inferiors before anything related to
4992 registers/memory. */
4993 for (inferior
*inf
: all_non_exited_inferiors (this))
4995 inf
->needs_setup
= true;
4999 thread_info
*thread
= any_live_thread_of_inferior (inf
);
5000 notice_new_inferior (thread
, thread
->state
== THREAD_RUNNING
,
5005 /* If all-stop on top of non-stop, pause all threads. Note this
5006 records the threads' stop pc, so must be done after "noticing"
5011 /* At this point, the remote target is not async. It needs to be for
5012 the poll in stop_all_threads to consider events from it, so enable
5014 gdb_assert (!this->is_async_p ());
5015 SCOPE_EXIT
{ target_async (false); };
5016 target_async (true);
5017 stop_all_threads ("remote connect in all-stop");
5020 /* If all threads of an inferior were already stopped, we
5021 haven't setup the inferior yet. */
5022 for (inferior
*inf
: all_non_exited_inferiors (this))
5024 if (inf
->needs_setup
)
5026 thread_info
*thread
= any_live_thread_of_inferior (inf
);
5027 switch_to_thread_no_regs (thread
);
5033 /* Now go over all threads that are stopped, and print their current
5034 frame. If all-stop, then if there's a signalled thread, pick
5036 for (thread_info
*thread
: all_non_exited_threads (this))
5042 thread
->set_running (false);
5043 else if (thread
->state
!= THREAD_STOPPED
)
5046 if (selected
== nullptr && thread
->has_pending_waitstatus ())
5049 if (lowest_stopped
== NULL
5050 || thread
->inf
->num
< lowest_stopped
->inf
->num
5051 || thread
->per_inf_num
< lowest_stopped
->per_inf_num
)
5052 lowest_stopped
= thread
;
5055 print_one_stopped_thread (thread
);
5058 /* In all-stop, we only print the status of one thread, and leave
5059 others with their status pending. */
5062 thread_info
*thread
= selected
;
5064 thread
= lowest_stopped
;
5068 print_one_stopped_thread (thread
);
5072 /* Mark a remote_target as starting (by setting the starting_up flag within
5073 its remote_state) for the lifetime of this object. The reference count
5074 on the remote target is temporarily incremented, to prevent the target
5075 being deleted under our feet. */
5077 struct scoped_mark_target_starting
5079 /* Constructor, TARGET is the target to be marked as starting, its
5080 reference count will be incremented. */
5081 scoped_mark_target_starting (remote_target
*target
)
5082 : m_remote_target (remote_target_ref::new_reference (target
)),
5083 m_restore_starting_up (set_starting_up_flag (target
))
5088 /* Helper function, set the starting_up flag on TARGET and return an
5089 object which, when it goes out of scope, will restore the previous
5090 value of the starting_up flag. */
5091 static scoped_restore_tmpl
<bool>
5092 set_starting_up_flag (remote_target
*target
)
5094 remote_state
*rs
= target
->get_remote_state ();
5095 gdb_assert (!rs
->starting_up
);
5096 return make_scoped_restore (&rs
->starting_up
, true);
5099 /* A gdb::ref_ptr pointer to a remote_target. */
5100 using remote_target_ref
= gdb::ref_ptr
<remote_target
, target_ops_ref_policy
>;
5102 /* A reference to the target on which we are operating. */
5103 remote_target_ref m_remote_target
;
5105 /* An object which restores the previous value of the starting_up flag
5106 when it goes out of scope. */
5107 scoped_restore_tmpl
<bool> m_restore_starting_up
;
5110 /* Transfer ownership of the stop_reply owned by EVENT to a
5111 stop_reply_up object. */
5113 static stop_reply_up
5114 as_stop_reply_up (notif_event_up event
)
5116 auto *stop_reply
= static_cast<struct stop_reply
*> (event
.release ());
5117 return stop_reply_up (stop_reply
);
5120 /* Helper for remote_target::start_remote, start the remote connection and
5121 sync state. Return true if everything goes OK, otherwise, return false.
5122 This function exists so that the scoped_restore created within it will
5123 expire before we return to remote_target::start_remote. */
5126 remote_target::start_remote_1 (int from_tty
, int extended_p
)
5128 REMOTE_SCOPED_DEBUG_ENTER_EXIT
;
5130 struct remote_state
*rs
= get_remote_state ();
5132 /* Signal other parts that we're going through the initial setup,
5133 and so things may not be stable yet. E.g., we don't try to
5134 install tracepoints until we've relocated symbols. Also, a
5135 Ctrl-C before we're connected and synced up can't interrupt the
5136 target. Instead, it offers to drop the (potentially wedged)
5138 scoped_mark_target_starting
target_is_starting (this);
5142 if (interrupt_on_connect
)
5143 send_interrupt_sequence ();
5145 /* Ack any packet which the remote side has already sent. */
5146 remote_serial_write ("+", 1);
5148 /* The first packet we send to the target is the optional "supported
5149 packets" request. If the target can answer this, it will tell us
5150 which later probes to skip. */
5151 remote_query_supported ();
5153 /* Check vCont support and set the remote state's vCont_action_support
5155 remote_vcont_probe ();
5157 /* If the stub wants to get a QAllow, compose one and send it. */
5158 if (m_features
.packet_support (PACKET_QAllow
) != PACKET_DISABLE
)
5161 /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
5162 unknown 'v' packet with string "OK". "OK" gets interpreted by GDB
5163 as a reply to known packet. For packet "vFile:setfs:" it is an
5164 invalid reply and GDB would return error in
5165 remote_hostio_set_filesystem, making remote files access impossible.
5166 Disable "vFile:setfs:" in such case. Do not disable other 'v' packets as
5167 other "vFile" packets get correctly detected even on gdbserver < 7.7. */
5169 const char v_mustreplyempty
[] = "vMustReplyEmpty";
5171 putpkt (v_mustreplyempty
);
5173 if (strcmp (rs
->buf
.data (), "OK") == 0)
5175 m_features
.m_protocol_packets
[PACKET_vFile_setfs
].support
5178 else if (strcmp (rs
->buf
.data (), "") != 0)
5179 error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty
,
5183 /* Next, we possibly activate noack mode.
5185 If the QStartNoAckMode packet configuration is set to AUTO,
5186 enable noack mode if the stub reported a wish for it with
5189 If set to TRUE, then enable noack mode even if the stub didn't
5190 report it in qSupported. If the stub doesn't reply OK, the
5191 session ends with an error.
5193 If FALSE, then don't activate noack mode, regardless of what the
5194 stub claimed should be the default with qSupported. */
5196 if (m_features
.packet_support (PACKET_QStartNoAckMode
) != PACKET_DISABLE
)
5198 putpkt ("QStartNoAckMode");
5200 if ((m_features
.packet_ok (rs
->buf
, PACKET_QStartNoAckMode
)).status ()
5207 /* Tell the remote that we are using the extended protocol. */
5212 /* Let the target know which signals it is allowed to pass down to
5214 update_signals_program_target ();
5216 /* Next, if the target can specify a description, read it. We do
5217 this before anything involving memory or registers. */
5218 target_find_description ();
5220 /* Next, now that we know something about the target, update the
5221 address spaces in the program spaces. */
5222 update_address_spaces ();
5224 /* On OSs where the list of libraries is global to all
5225 processes, we fetch them early. */
5226 if (gdbarch_has_global_solist (current_inferior ()->arch ()))
5227 solib_add (NULL
, from_tty
, auto_solib_add
);
5229 if (target_is_non_stop_p ())
5231 if (m_features
.packet_support (PACKET_QNonStop
) != PACKET_ENABLE
)
5232 error (_("Non-stop mode requested, but remote "
5233 "does not support non-stop"));
5235 putpkt ("QNonStop:1");
5238 if (strcmp (rs
->buf
.data (), "OK") != 0)
5239 error (_("Remote refused setting non-stop mode with: %s"),
5242 /* Find about threads and processes the stub is already
5243 controlling. We default to adding them in the running state.
5244 The '?' query below will then tell us about which threads are
5246 this->update_thread_list ();
5248 else if (m_features
.packet_support (PACKET_QNonStop
) == PACKET_ENABLE
)
5250 /* Don't assume that the stub can operate in all-stop mode.
5251 Request it explicitly. */
5252 putpkt ("QNonStop:0");
5255 if (strcmp (rs
->buf
.data (), "OK") != 0)
5256 error (_("Remote refused setting all-stop mode with: %s"),
5260 /* Upload TSVs regardless of whether the target is running or not. The
5261 remote stub, such as GDBserver, may have some predefined or builtin
5262 TSVs, even if the target is not running. */
5263 if (get_trace_status (current_trace_status ()) != -1)
5265 struct uploaded_tsv
*uploaded_tsvs
= NULL
;
5267 upload_trace_state_variables (&uploaded_tsvs
);
5268 merge_uploaded_trace_state_variables (&uploaded_tsvs
);
5271 /* Check whether the target is running now. */
5275 if (!target_is_non_stop_p ())
5277 char *wait_status
= NULL
;
5279 if (rs
->buf
[0] == 'W' || rs
->buf
[0] == 'X')
5282 error (_("The target is not running (try extended-remote?)"));
5287 /* Save the reply for later. */
5288 wait_status
= (char *) alloca (strlen (rs
->buf
.data ()) + 1);
5289 strcpy (wait_status
, rs
->buf
.data ());
5292 /* Fetch thread list. */
5293 target_update_thread_list ();
5295 /* Let the stub know that we want it to return the thread. */
5296 set_continue_thread (minus_one_ptid
);
5298 if (thread_count (this) == 0)
5300 /* Target has no concept of threads at all. GDB treats
5301 non-threaded target as single-threaded; add a main
5303 thread_info
*tp
= add_current_inferior_and_thread (wait_status
);
5304 get_remote_thread_info (tp
)->set_resumed ();
5308 /* We have thread information; select the thread the target
5309 says should be current. If we're reconnecting to a
5310 multi-threaded program, this will ideally be the thread
5311 that last reported an event before GDB disconnected. */
5312 ptid_t curr_thread
= get_current_thread (wait_status
);
5313 if (curr_thread
== null_ptid
)
5315 /* Odd... The target was able to list threads, but not
5316 tell us which thread was current (no "thread"
5317 register in T stop reply?). Just pick the first
5318 thread in the thread list then. */
5320 remote_debug_printf ("warning: couldn't determine remote "
5321 "current thread; picking first in list.");
5323 for (thread_info
*tp
: all_non_exited_threads (this,
5326 switch_to_thread (tp
);
5331 switch_to_thread (this->find_thread (curr_thread
));
5333 get_remote_thread_info (inferior_thread ())->set_resumed ();
5336 /* init_wait_for_inferior should be called before get_offsets in order
5337 to manage `inserted' flag in bp loc in a correct state.
5338 breakpoint_init_inferior, called from init_wait_for_inferior, set
5339 `inserted' flag to 0, while before breakpoint_re_set, called from
5340 start_remote, set `inserted' flag to 1. In the initialization of
5341 inferior, breakpoint_init_inferior should be called first, and then
5342 breakpoint_re_set can be called. If this order is broken, state of
5343 `inserted' flag is wrong, and cause some problems on breakpoint
5345 init_wait_for_inferior ();
5347 get_offsets (); /* Get text, data & bss offsets. */
5349 /* If we could not find a description using qXfer, and we know
5350 how to do it some other way, try again. This is not
5351 supported for non-stop; it could be, but it is tricky if
5352 there are no stopped threads when we connect. */
5353 if (remote_read_description_p (this)
5354 && gdbarch_target_desc (current_inferior ()->arch ()) == NULL
)
5356 target_clear_description ();
5357 target_find_description ();
5360 /* Use the previously fetched status. */
5361 gdb_assert (wait_status
!= NULL
);
5362 notif_event_up reply
5363 = remote_notif_parse (this, ¬if_client_stop
, wait_status
);
5364 push_stop_reply (as_stop_reply_up (std::move (reply
)));
5366 ::start_remote (from_tty
); /* Initialize gdb process mechanisms. */
5370 /* Clear WFI global state. Do this before finding about new
5371 threads and inferiors, and setting the current inferior.
5372 Otherwise we would clear the proceed status of the current
5373 inferior when we want its stop_soon state to be preserved
5374 (see notice_new_inferior). */
5375 init_wait_for_inferior ();
5377 /* In non-stop, we will either get an "OK", meaning that there
5378 are no stopped threads at this time; or, a regular stop
5379 reply. In the latter case, there may be more than one thread
5380 stopped --- we pull them all out using the vStopped
5382 if (strcmp (rs
->buf
.data (), "OK") != 0)
5384 const notif_client
*notif
= ¬if_client_stop
;
5386 /* remote_notif_get_pending_replies acks this one, and gets
5388 rs
->notif_state
->pending_event
[notif_client_stop
.id
]
5389 = remote_notif_parse (this, notif
, rs
->buf
.data ());
5390 remote_notif_get_pending_events (notif
);
5393 if (thread_count (this) == 0)
5396 error (_("The target is not running (try extended-remote?)"));
5400 /* Report all signals during attach/startup. */
5403 /* If there are already stopped threads, mark them stopped and
5404 report their stops before giving the prompt to the user. */
5405 process_initial_stop_replies (from_tty
);
5407 if (target_can_async_p ())
5408 target_async (true);
5411 /* Give the target a chance to look up symbols. */
5412 for (inferior
*inf
: all_inferiors (this))
5414 /* The inferiors that exist at this point were created from what
5415 was found already running on the remote side, so we know they
5417 gdb_assert (this->has_execution (inf
));
5419 /* No use without a symbol-file. */
5420 if (inf
->pspace
->symfile_object_file
== nullptr)
5423 /* Need to switch to a specific thread, because remote_check_symbols
5424 uses INFERIOR_PTID to set the general thread. */
5425 scoped_restore_current_thread restore_thread
;
5426 thread_info
*thread
= any_thread_of_inferior (inf
);
5427 switch_to_thread (thread
);
5428 this->remote_check_symbols ();
5431 /* Possibly the target has been engaged in a trace run started
5432 previously; find out where things are at. */
5433 if (get_trace_status (current_trace_status ()) != -1)
5435 struct uploaded_tp
*uploaded_tps
= NULL
;
5437 if (current_trace_status ()->running
)
5438 gdb_printf (_("Trace is already running on the target.\n"));
5440 upload_tracepoints (&uploaded_tps
);
5442 merge_uploaded_tracepoints (&uploaded_tps
);
5445 /* Possibly the target has been engaged in a btrace record started
5446 previously; find out where things are at. */
5447 remote_btrace_maybe_reopen ();
5452 /* Start the remote connection and sync state. */
5455 remote_target::start_remote (int from_tty
, int extended_p
)
5457 if (start_remote_1 (from_tty
, extended_p
)
5458 && breakpoints_should_be_inserted_now ())
5459 insert_breakpoints ();
5463 remote_target::connection_string ()
5465 remote_state
*rs
= get_remote_state ();
5467 if (rs
->remote_desc
->name
!= NULL
)
5468 return rs
->remote_desc
->name
;
5473 /* Open a connection to a remote debugger.
5474 NAME is the filename used for communication. */
5477 remote_target::open (const char *name
, int from_tty
)
5479 open_1 (name
, from_tty
, 0);
5482 /* Open a connection to a remote debugger using the extended
5483 remote gdb protocol. NAME is the filename used for communication. */
5486 extended_remote_target::open (const char *name
, int from_tty
)
5488 open_1 (name
, from_tty
, 1 /*extended_p */);
5492 remote_features::reset_all_packet_configs_support ()
5496 for (i
= 0; i
< PACKET_MAX
; i
++)
5497 m_protocol_packets
[i
].support
= PACKET_SUPPORT_UNKNOWN
;
5500 /* Initialize all packet configs. */
5503 init_all_packet_configs (void)
5507 for (i
= 0; i
< PACKET_MAX
; i
++)
5509 remote_protocol_packets
[i
].detect
= AUTO_BOOLEAN_AUTO
;
5510 remote_protocol_packets
[i
].support
= PACKET_SUPPORT_UNKNOWN
;
5514 /* Symbol look-up. */
5517 remote_target::remote_check_symbols ()
5522 /* It doesn't make sense to send a qSymbol packet for an inferior that
5523 doesn't have execution, because the remote side doesn't know about
5524 inferiors without execution. */
5525 gdb_assert (target_has_execution ());
5527 if (m_features
.packet_support (PACKET_qSymbol
) == PACKET_DISABLE
)
5530 /* Make sure the remote is pointing at the right process. Note
5531 there's no way to select "no process". */
5532 set_general_process ();
5534 /* Allocate a message buffer. We can't reuse the input buffer in RS,
5535 because we need both at the same time. */
5536 gdb::char_vector
msg (get_remote_packet_size ());
5537 gdb::char_vector
reply (get_remote_packet_size ());
5539 /* Invite target to request symbol lookups. */
5541 putpkt ("qSymbol::");
5543 m_features
.packet_ok (reply
, PACKET_qSymbol
);
5545 while (startswith (reply
.data (), "qSymbol:"))
5548 end
= hex2bin (tmp
, reinterpret_cast <gdb_byte
*> (msg
.data ()),
5551 bound_minimal_symbol sym
5552 = lookup_minimal_symbol (current_program_space
, msg
.data ());
5553 if (sym
.minsym
== NULL
)
5554 xsnprintf (msg
.data (), get_remote_packet_size (), "qSymbol::%s",
5558 int addr_size
= gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
5559 CORE_ADDR sym_addr
= sym
.value_address ();
5561 /* If this is a function address, return the start of code
5562 instead of any data function descriptor. */
5563 sym_addr
= gdbarch_convert_from_func_ptr_addr
5564 (current_inferior ()->arch (), sym_addr
,
5565 current_inferior ()->top_target ());
5567 xsnprintf (msg
.data (), get_remote_packet_size (), "qSymbol:%s:%s",
5568 phex_nz (sym_addr
, addr_size
), &reply
[8]);
5571 putpkt (msg
.data ());
5576 static struct serial
*
5577 remote_serial_open (const char *name
)
5579 static int udp_warning
= 0;
5581 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
5582 of in ser-tcp.c, because it is the remote protocol assuming that the
5583 serial connection is reliable and not the serial connection promising
5585 if (!udp_warning
&& startswith (name
, "udp:"))
5587 warning (_("The remote protocol may be unreliable over UDP.\n"
5588 "Some events may be lost, rendering further debugging "
5593 return serial_open (name
);
5596 /* Inform the target of our permission settings. The permission flags
5597 work without this, but if the target knows the settings, it can do
5598 a couple things. First, it can add its own check, to catch cases
5599 that somehow manage to get by the permissions checks in target
5600 methods. Second, if the target is wired to disallow particular
5601 settings (for instance, a system in the field that is not set up to
5602 be able to stop at a breakpoint), it can object to any unavailable
5606 remote_target::set_permissions ()
5608 struct remote_state
*rs
= get_remote_state ();
5610 xsnprintf (rs
->buf
.data (), get_remote_packet_size (), "QAllow:"
5611 "WriteReg:%x;WriteMem:%x;"
5612 "InsertBreak:%x;InsertTrace:%x;"
5613 "InsertFastTrace:%x;Stop:%x",
5614 may_write_registers
, may_write_memory
,
5615 may_insert_breakpoints
, may_insert_tracepoints
,
5616 may_insert_fast_tracepoints
, may_stop
);
5620 /* If the target didn't like the packet, warn the user. Do not try
5621 to undo the user's settings, that would just be maddening. */
5622 if (strcmp (rs
->buf
.data (), "OK") != 0)
5623 warning (_("Remote refused setting permissions with: %s"),
5627 /* This type describes each known response to the qSupported
5629 struct protocol_feature
5631 /* The name of this protocol feature. */
5634 /* The default for this protocol feature. */
5635 enum packet_support default_support
;
5637 /* The function to call when this feature is reported, or after
5638 qSupported processing if the feature is not supported.
5639 The first argument points to this structure. The second
5640 argument indicates whether the packet requested support be
5641 enabled, disabled, or probed (or the default, if this function
5642 is being called at the end of processing and this feature was
5643 not reported). The third argument may be NULL; if not NULL, it
5644 is a NUL-terminated string taken from the packet following
5645 this feature's name and an equals sign. */
5646 void (*func
) (remote_target
*remote
, const struct protocol_feature
*,
5647 enum packet_support
, const char *);
5649 /* The corresponding packet for this feature. Only used if
5650 FUNC is remote_supported_packet. */
5655 remote_supported_packet (remote_target
*remote
,
5656 const struct protocol_feature
*feature
,
5657 enum packet_support support
,
5658 const char *argument
)
5662 warning (_("Remote qSupported response supplied an unexpected value for"
5663 " \"%s\"."), feature
->name
);
5667 remote
->m_features
.m_protocol_packets
[feature
->packet
].support
= support
;
5671 remote_target::remote_packet_size (const protocol_feature
*feature
,
5672 enum packet_support support
,
5675 struct remote_state
*rs
= get_remote_state ();
5680 if (support
!= PACKET_ENABLE
)
5683 if (value
== NULL
|| *value
== '\0')
5685 warning (_("Remote target reported \"%s\" without a size."),
5691 packet_size
= strtol (value
, &value_end
, 16);
5692 if (errno
!= 0 || *value_end
!= '\0' || packet_size
< 0)
5694 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
5695 feature
->name
, value
);
5699 /* Record the new maximum packet size. */
5700 rs
->explicit_packet_size
= packet_size
;
5704 remote_packet_size (remote_target
*remote
, const protocol_feature
*feature
,
5705 enum packet_support support
, const char *value
)
5707 remote
->remote_packet_size (feature
, support
, value
);
5711 remote_target::remote_supported_thread_options (const protocol_feature
*feature
,
5712 enum packet_support support
,
5715 struct remote_state
*rs
= get_remote_state ();
5717 m_features
.m_protocol_packets
[feature
->packet
].support
= support
;
5719 if (support
!= PACKET_ENABLE
)
5722 if (value
== nullptr || *value
== '\0')
5724 warning (_("Remote target reported \"%s\" without supported options."),
5729 ULONGEST options
= 0;
5730 const char *p
= unpack_varlen_hex (value
, &options
);
5734 warning (_("Remote target reported \"%s\" with "
5735 "bad thread options: \"%s\"."),
5736 feature
->name
, value
);
5740 /* Record the set of supported options. */
5741 rs
->supported_thread_options
= (gdb_thread_option
) options
;
5745 remote_supported_thread_options (remote_target
*remote
,
5746 const protocol_feature
*feature
,
5747 enum packet_support support
,
5750 remote
->remote_supported_thread_options (feature
, support
, value
);
5753 static const struct protocol_feature remote_protocol_features
[] = {
5754 { "PacketSize", PACKET_DISABLE
, remote_packet_size
, -1 },
5755 { "qXfer:auxv:read", PACKET_DISABLE
, remote_supported_packet
,
5756 PACKET_qXfer_auxv
},
5757 { "qXfer:exec-file:read", PACKET_DISABLE
, remote_supported_packet
,
5758 PACKET_qXfer_exec_file
},
5759 { "qXfer:features:read", PACKET_DISABLE
, remote_supported_packet
,
5760 PACKET_qXfer_features
},
5761 { "qXfer:libraries:read", PACKET_DISABLE
, remote_supported_packet
,
5762 PACKET_qXfer_libraries
},
5763 { "qXfer:libraries-svr4:read", PACKET_DISABLE
, remote_supported_packet
,
5764 PACKET_qXfer_libraries_svr4
},
5765 { "augmented-libraries-svr4-read", PACKET_DISABLE
,
5766 remote_supported_packet
, PACKET_augmented_libraries_svr4_read_feature
},
5767 { "qXfer:memory-map:read", PACKET_DISABLE
, remote_supported_packet
,
5768 PACKET_qXfer_memory_map
},
5769 { "qXfer:osdata:read", PACKET_DISABLE
, remote_supported_packet
,
5770 PACKET_qXfer_osdata
},
5771 { "qXfer:threads:read", PACKET_DISABLE
, remote_supported_packet
,
5772 PACKET_qXfer_threads
},
5773 { "qXfer:traceframe-info:read", PACKET_DISABLE
, remote_supported_packet
,
5774 PACKET_qXfer_traceframe_info
},
5775 { "QPassSignals", PACKET_DISABLE
, remote_supported_packet
,
5776 PACKET_QPassSignals
},
5777 { "QCatchSyscalls", PACKET_DISABLE
, remote_supported_packet
,
5778 PACKET_QCatchSyscalls
},
5779 { "QProgramSignals", PACKET_DISABLE
, remote_supported_packet
,
5780 PACKET_QProgramSignals
},
5781 { "QSetWorkingDir", PACKET_DISABLE
, remote_supported_packet
,
5782 PACKET_QSetWorkingDir
},
5783 { "QStartupWithShell", PACKET_DISABLE
, remote_supported_packet
,
5784 PACKET_QStartupWithShell
},
5785 { "QEnvironmentHexEncoded", PACKET_DISABLE
, remote_supported_packet
,
5786 PACKET_QEnvironmentHexEncoded
},
5787 { "QEnvironmentReset", PACKET_DISABLE
, remote_supported_packet
,
5788 PACKET_QEnvironmentReset
},
5789 { "QEnvironmentUnset", PACKET_DISABLE
, remote_supported_packet
,
5790 PACKET_QEnvironmentUnset
},
5791 { "QStartNoAckMode", PACKET_DISABLE
, remote_supported_packet
,
5792 PACKET_QStartNoAckMode
},
5793 { "multiprocess", PACKET_DISABLE
, remote_supported_packet
,
5794 PACKET_multiprocess_feature
},
5795 { "QNonStop", PACKET_DISABLE
, remote_supported_packet
, PACKET_QNonStop
},
5796 { "qXfer:siginfo:read", PACKET_DISABLE
, remote_supported_packet
,
5797 PACKET_qXfer_siginfo_read
},
5798 { "qXfer:siginfo:write", PACKET_DISABLE
, remote_supported_packet
,
5799 PACKET_qXfer_siginfo_write
},
5800 { "ConditionalTracepoints", PACKET_DISABLE
, remote_supported_packet
,
5801 PACKET_ConditionalTracepoints
},
5802 { "ConditionalBreakpoints", PACKET_DISABLE
, remote_supported_packet
,
5803 PACKET_ConditionalBreakpoints
},
5804 { "BreakpointCommands", PACKET_DISABLE
, remote_supported_packet
,
5805 PACKET_BreakpointCommands
},
5806 { "FastTracepoints", PACKET_DISABLE
, remote_supported_packet
,
5807 PACKET_FastTracepoints
},
5808 { "StaticTracepoints", PACKET_DISABLE
, remote_supported_packet
,
5809 PACKET_StaticTracepoints
},
5810 {"InstallInTrace", PACKET_DISABLE
, remote_supported_packet
,
5811 PACKET_InstallInTrace
},
5812 { "DisconnectedTracing", PACKET_DISABLE
, remote_supported_packet
,
5813 PACKET_DisconnectedTracing_feature
},
5814 { "ReverseContinue", PACKET_DISABLE
, remote_supported_packet
,
5816 { "ReverseStep", PACKET_DISABLE
, remote_supported_packet
,
5818 { "TracepointSource", PACKET_DISABLE
, remote_supported_packet
,
5819 PACKET_TracepointSource
},
5820 { "QAllow", PACKET_DISABLE
, remote_supported_packet
,
5822 { "EnableDisableTracepoints", PACKET_DISABLE
, remote_supported_packet
,
5823 PACKET_EnableDisableTracepoints_feature
},
5824 { "qXfer:fdpic:read", PACKET_DISABLE
, remote_supported_packet
,
5825 PACKET_qXfer_fdpic
},
5826 { "qXfer:uib:read", PACKET_DISABLE
, remote_supported_packet
,
5828 { "QDisableRandomization", PACKET_DISABLE
, remote_supported_packet
,
5829 PACKET_QDisableRandomization
},
5830 { "QAgent", PACKET_DISABLE
, remote_supported_packet
, PACKET_QAgent
},
5831 { "QTBuffer:size", PACKET_DISABLE
,
5832 remote_supported_packet
, PACKET_QTBuffer_size
},
5833 { "tracenz", PACKET_DISABLE
, remote_supported_packet
, PACKET_tracenz_feature
},
5834 { "Qbtrace:off", PACKET_DISABLE
, remote_supported_packet
, PACKET_Qbtrace_off
},
5835 { "Qbtrace:bts", PACKET_DISABLE
, remote_supported_packet
, PACKET_Qbtrace_bts
},
5836 { "Qbtrace:pt", PACKET_DISABLE
, remote_supported_packet
, PACKET_Qbtrace_pt
},
5837 { "qXfer:btrace:read", PACKET_DISABLE
, remote_supported_packet
,
5838 PACKET_qXfer_btrace
},
5839 { "qXfer:btrace-conf:read", PACKET_DISABLE
, remote_supported_packet
,
5840 PACKET_qXfer_btrace_conf
},
5841 { "Qbtrace-conf:bts:size", PACKET_DISABLE
, remote_supported_packet
,
5842 PACKET_Qbtrace_conf_bts_size
},
5843 { "swbreak", PACKET_DISABLE
, remote_supported_packet
, PACKET_swbreak_feature
},
5844 { "hwbreak", PACKET_DISABLE
, remote_supported_packet
, PACKET_hwbreak_feature
},
5845 { "fork-events", PACKET_DISABLE
, remote_supported_packet
,
5846 PACKET_fork_event_feature
},
5847 { "vfork-events", PACKET_DISABLE
, remote_supported_packet
,
5848 PACKET_vfork_event_feature
},
5849 { "exec-events", PACKET_DISABLE
, remote_supported_packet
,
5850 PACKET_exec_event_feature
},
5851 { "Qbtrace-conf:pt:size", PACKET_DISABLE
, remote_supported_packet
,
5852 PACKET_Qbtrace_conf_pt_size
},
5853 { "Qbtrace-conf:pt:ptwrite", PACKET_DISABLE
, remote_supported_packet
,
5854 PACKET_Qbtrace_conf_pt_ptwrite
},
5855 { "Qbtrace-conf:pt:event-tracing", PACKET_DISABLE
, remote_supported_packet
,
5856 PACKET_Qbtrace_conf_pt_event_tracing
},
5857 { "vContSupported", PACKET_DISABLE
, remote_supported_packet
, PACKET_vContSupported
},
5858 { "QThreadEvents", PACKET_DISABLE
, remote_supported_packet
, PACKET_QThreadEvents
},
5859 { "QThreadOptions", PACKET_DISABLE
, remote_supported_thread_options
,
5860 PACKET_QThreadOptions
},
5861 { "no-resumed", PACKET_DISABLE
, remote_supported_packet
, PACKET_no_resumed
},
5862 { "memory-tagging", PACKET_DISABLE
, remote_supported_packet
,
5863 PACKET_memory_tagging_feature
},
5864 { "error-message", PACKET_ENABLE
, remote_supported_packet
,
5865 PACKET_accept_error_message
},
5866 { "binary-upload", PACKET_DISABLE
, remote_supported_packet
, PACKET_x
},
5869 static char *remote_support_xml
;
5871 /* Register string appended to "xmlRegisters=" in qSupported query. */
5874 register_remote_support_xml (const char *xml
)
5876 #if defined(HAVE_LIBEXPAT)
5877 if (remote_support_xml
== NULL
)
5878 remote_support_xml
= concat ("xmlRegisters=", xml
, (char *) NULL
);
5881 char *copy
= xstrdup (remote_support_xml
+ 13);
5883 char *p
= strtok_r (copy
, ",", &saveptr
);
5887 if (strcmp (p
, xml
) == 0)
5894 while ((p
= strtok_r (NULL
, ",", &saveptr
)) != NULL
);
5897 remote_support_xml
= reconcat (remote_support_xml
,
5898 remote_support_xml
, ",", xml
,
5905 remote_query_supported_append (std::string
*msg
, const char *append
)
5909 msg
->append (append
);
5913 remote_target::remote_query_supported ()
5915 struct remote_state
*rs
= get_remote_state ();
5918 unsigned char seen
[ARRAY_SIZE (remote_protocol_features
)];
5920 /* The packet support flags are handled differently for this packet
5921 than for most others. We treat an error, a disabled packet, and
5922 an empty response identically: any features which must be reported
5923 to be used will be automatically disabled. An empty buffer
5924 accomplishes this, since that is also the representation for a list
5925 containing no features. */
5928 if (m_features
.packet_support (PACKET_qSupported
) != PACKET_DISABLE
)
5932 if (m_features
.packet_set_cmd_state (PACKET_multiprocess_feature
)
5933 != AUTO_BOOLEAN_FALSE
)
5934 remote_query_supported_append (&q
, "multiprocess+");
5936 if (m_features
.packet_set_cmd_state (PACKET_swbreak_feature
)
5937 != AUTO_BOOLEAN_FALSE
)
5938 remote_query_supported_append (&q
, "swbreak+");
5940 if (m_features
.packet_set_cmd_state (PACKET_hwbreak_feature
)
5941 != AUTO_BOOLEAN_FALSE
)
5942 remote_query_supported_append (&q
, "hwbreak+");
5944 remote_query_supported_append (&q
, "qRelocInsn+");
5946 if (m_features
.packet_set_cmd_state (PACKET_fork_event_feature
)
5947 != AUTO_BOOLEAN_FALSE
)
5948 remote_query_supported_append (&q
, "fork-events+");
5950 if (m_features
.packet_set_cmd_state (PACKET_vfork_event_feature
)
5951 != AUTO_BOOLEAN_FALSE
)
5952 remote_query_supported_append (&q
, "vfork-events+");
5954 if (m_features
.packet_set_cmd_state (PACKET_exec_event_feature
)
5955 != AUTO_BOOLEAN_FALSE
)
5956 remote_query_supported_append (&q
, "exec-events+");
5958 if (m_features
.packet_set_cmd_state (PACKET_vContSupported
)
5959 != AUTO_BOOLEAN_FALSE
)
5960 remote_query_supported_append (&q
, "vContSupported+");
5962 if (m_features
.packet_set_cmd_state (PACKET_QThreadEvents
)
5963 != AUTO_BOOLEAN_FALSE
)
5964 remote_query_supported_append (&q
, "QThreadEvents+");
5966 if (m_features
.packet_set_cmd_state (PACKET_QThreadOptions
)
5967 != AUTO_BOOLEAN_FALSE
)
5968 remote_query_supported_append (&q
, "QThreadOptions+");
5970 if (m_features
.packet_set_cmd_state (PACKET_no_resumed
)
5971 != AUTO_BOOLEAN_FALSE
)
5972 remote_query_supported_append (&q
, "no-resumed+");
5974 if (m_features
.packet_set_cmd_state (PACKET_memory_tagging_feature
)
5975 != AUTO_BOOLEAN_FALSE
)
5976 remote_query_supported_append (&q
, "memory-tagging+");
5978 /* Keep this one last to work around a gdbserver <= 7.10 bug in
5979 the qSupported:xmlRegisters=i386 handling. */
5980 if (remote_support_xml
!= NULL
5981 && (m_features
.packet_support (PACKET_qXfer_features
)
5983 remote_query_supported_append (&q
, remote_support_xml
);
5985 if (m_features
.packet_set_cmd_state (PACKET_accept_error_message
)
5986 != AUTO_BOOLEAN_FALSE
)
5987 remote_query_supported_append (&q
, "error-message+");
5989 q
= "qSupported:" + q
;
5990 putpkt (q
.c_str ());
5994 /* If an error occurred, warn, but do not return - just reset the
5995 buffer to empty and go on to disable features. */
5996 packet_result result
= m_features
.packet_ok (rs
->buf
, PACKET_qSupported
);
5997 if (result
.status () == PACKET_ERROR
)
5999 warning (_("Remote failure reply: %s"), result
.err_msg ());
6004 memset (seen
, 0, sizeof (seen
));
6006 next
= rs
->buf
.data ();
6009 enum packet_support is_supported
;
6010 char *p
, *end
, *name_end
, *value
;
6012 /* First separate out this item from the rest of the packet. If
6013 there's another item after this, we overwrite the separator
6014 (terminated strings are much easier to work with). */
6016 end
= strchr (p
, ';');
6019 end
= p
+ strlen (p
);
6029 warning (_("empty item in \"qSupported\" response"));
6034 name_end
= strchr (p
, '=');
6037 /* This is a name=value entry. */
6038 is_supported
= PACKET_ENABLE
;
6039 value
= name_end
+ 1;
6048 is_supported
= PACKET_ENABLE
;
6052 is_supported
= PACKET_DISABLE
;
6056 is_supported
= PACKET_SUPPORT_UNKNOWN
;
6060 warning (_("unrecognized item \"%s\" "
6061 "in \"qSupported\" response"), p
);
6067 for (i
= 0; i
< ARRAY_SIZE (remote_protocol_features
); i
++)
6068 if (strcmp (remote_protocol_features
[i
].name
, p
) == 0)
6070 const struct protocol_feature
*feature
;
6073 feature
= &remote_protocol_features
[i
];
6074 feature
->func (this, feature
, is_supported
, value
);
6079 /* If we increased the packet size, make sure to increase the global
6080 buffer size also. We delay this until after parsing the entire
6081 qSupported packet, because this is the same buffer we were
6083 if (rs
->buf
.size () < rs
->explicit_packet_size
)
6084 rs
->buf
.resize (rs
->explicit_packet_size
);
6086 /* Handle the defaults for unmentioned features. */
6087 for (i
= 0; i
< ARRAY_SIZE (remote_protocol_features
); i
++)
6090 const struct protocol_feature
*feature
;
6092 feature
= &remote_protocol_features
[i
];
6093 feature
->func (this, feature
, feature
->default_support
, NULL
);
6097 /* Serial QUIT handler for the remote serial descriptor.
6099 Defers handling a Ctrl-C until we're done with the current
6100 command/response packet sequence, unless:
6102 - We're setting up the connection. Don't send a remote interrupt
6103 request, as we're not fully synced yet. Quit immediately
6106 - The target has been resumed in the foreground
6107 (target_terminal::is_ours is false) with a synchronous resume
6108 packet, and we're blocked waiting for the stop reply, thus a
6109 Ctrl-C should be immediately sent to the target.
6111 - We get a second Ctrl-C while still within the same serial read or
6112 write. In that case the serial is seemingly wedged --- offer to
6115 - We see a second Ctrl-C without target response, after having
6116 previously interrupted the target. In that case the target/stub
6117 is probably wedged --- offer to quit/disconnect.
6121 remote_target::remote_serial_quit_handler ()
6123 struct remote_state
*rs
= get_remote_state ();
6125 if (check_quit_flag ())
6127 /* If we're starting up, we're not fully synced yet. Quit
6129 if (rs
->starting_up
)
6131 else if (rs
->got_ctrlc_during_io
)
6133 if (query (_("The target is not responding to GDB commands.\n"
6134 "Stop debugging it? ")))
6135 remote_unpush_and_throw (this);
6137 /* If ^C has already been sent once, offer to disconnect. */
6138 else if (!target_terminal::is_ours () && rs
->ctrlc_pending_p
)
6140 /* All-stop protocol, and blocked waiting for stop reply. Send
6141 an interrupt request. */
6142 else if (!target_terminal::is_ours () && rs
->waiting_for_stop_reply
)
6143 target_interrupt ();
6145 rs
->got_ctrlc_during_io
= 1;
6149 /* The remote_target that is current while the quit handler is
6150 overridden with remote_serial_quit_handler. */
6151 static remote_target
*curr_quit_handler_target
;
6154 remote_serial_quit_handler ()
6156 curr_quit_handler_target
->remote_serial_quit_handler ();
6159 /* Remove the remote target from the target stack of each inferior
6160 that is using it. Upper targets depend on it so remove them
6164 remote_unpush_target (remote_target
*target
)
6166 /* We have to unpush the target from all inferiors, even those that
6168 scoped_restore_current_inferior restore_current_inferior
;
6170 for (inferior
*inf
: all_inferiors (target
))
6172 switch_to_inferior_no_thread (inf
);
6173 inf
->pop_all_targets_at_and_above (process_stratum
);
6174 generic_mourn_inferior ();
6177 /* Don't rely on target_close doing this when the target is popped
6178 from the last remote inferior above, because something may be
6179 holding a reference to the target higher up on the stack, meaning
6180 target_close won't be called yet. We lost the connection to the
6181 target, so clear these now, otherwise we may later throw
6182 TARGET_CLOSE_ERROR while trying to tell the remote target to
6184 fileio_handles_invalidate_target (target
);
6187 [[noreturn
]] static void
6188 remote_unpush_and_throw (remote_target
*target
)
6190 remote_unpush_target (target
);
6191 throw_error (TARGET_CLOSE_ERROR
, _("Disconnected from target."));
6195 remote_target::open_1 (const char *name
, int from_tty
, int extended_p
)
6197 remote_target
*curr_remote
= get_current_remote_target ();
6200 error (_("To open a remote debug connection, you need to specify what\n"
6201 "serial device is attached to the remote system\n"
6202 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
6204 /* If we're connected to a running target, target_preopen will kill it.
6205 Ask this question first, before target_preopen has a chance to kill
6207 if (curr_remote
!= NULL
&& !target_has_execution ())
6210 && !query (_("Already connected to a remote target. Disconnect? ")))
6211 error (_("Still connected."));
6214 /* Here the possibly existing remote target gets unpushed. */
6215 target_preopen (from_tty
);
6217 remote_fileio_reset ();
6218 reopen_exec_file ();
6219 reread_symbols (from_tty
);
6221 remote_target
*remote
6222 = (extended_p
? new extended_remote_target () : new remote_target ());
6223 target_ops_up
target_holder (remote
);
6225 remote_state
*rs
= remote
->get_remote_state ();
6227 /* See FIXME above. */
6228 if (!target_async_permitted
)
6229 rs
->wait_forever_enabled_p
= true;
6231 rs
->remote_desc
= remote_serial_open (name
);
6233 if (baud_rate
!= -1)
6237 serial_setbaudrate (rs
->remote_desc
, baud_rate
);
6239 catch (const gdb_exception_error
&)
6241 /* The requested speed could not be set. Error out to
6242 top level after closing remote_desc. Take care to
6243 set remote_desc to NULL to avoid closing remote_desc
6245 serial_close (rs
->remote_desc
);
6246 rs
->remote_desc
= NULL
;
6251 serial_setparity (rs
->remote_desc
, serial_parity
);
6252 serial_raw (rs
->remote_desc
);
6254 /* If there is something sitting in the buffer we might take it as a
6255 response to a command, which would be bad. */
6256 serial_flush_input (rs
->remote_desc
);
6260 gdb_puts ("Remote debugging using ");
6265 /* Switch to using the remote target now. */
6266 current_inferior ()->push_target (std::move (target_holder
));
6268 /* Register extra event sources in the event loop. */
6269 rs
->create_async_event_handler ();
6271 rs
->notif_state
= remote_notif_state_allocate (remote
);
6273 /* Reset the target state; these things will be queried either by
6274 remote_query_supported or as they are needed. */
6275 remote
->m_features
.reset_all_packet_configs_support ();
6276 rs
->explicit_packet_size
= 0;
6278 rs
->extended
= extended_p
;
6279 rs
->waiting_for_stop_reply
= 0;
6280 rs
->ctrlc_pending_p
= 0;
6281 rs
->got_ctrlc_during_io
= 0;
6283 rs
->general_thread
= not_sent_ptid
;
6284 rs
->continue_thread
= not_sent_ptid
;
6285 rs
->remote_traceframe_number
= -1;
6287 rs
->last_resume_exec_dir
= EXEC_FORWARD
;
6289 /* Probe for ability to use "ThreadInfo" query, as required. */
6290 rs
->use_threadinfo_query
= 1;
6291 rs
->use_threadextra_query
= 1;
6293 rs
->readahead_cache
.invalidate ();
6295 if (target_async_permitted
)
6297 /* FIXME: cagney/1999-09-23: During the initial connection it is
6298 assumed that the target is already ready and able to respond to
6299 requests. Unfortunately remote_start_remote() eventually calls
6300 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
6301 around this. Eventually a mechanism that allows
6302 wait_for_inferior() to expect/get timeouts will be
6304 rs
->wait_forever_enabled_p
= false;
6307 /* First delete any symbols previously loaded from shared libraries. */
6308 no_shared_libraries (current_program_space
);
6310 /* Start the remote connection. If error() or QUIT, discard this
6311 target (we'd otherwise be in an inconsistent state) and then
6312 propagate the error on up the exception chain. This ensures that
6313 the caller doesn't stumble along blindly assuming that the
6314 function succeeded. The CLI doesn't have this problem but other
6315 UI's, such as MI do.
6317 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
6318 this function should return an error indication letting the
6319 caller restore the previous state. Unfortunately the command
6320 ``target remote'' is directly wired to this function making that
6321 impossible. On a positive note, the CLI side of this problem has
6322 been fixed - the function set_cmd_context() makes it possible for
6323 all the ``target ....'' commands to share a common callback
6324 function. See cli-dump.c. */
6329 remote
->start_remote (from_tty
, extended_p
);
6331 catch (const gdb_exception
&ex
)
6333 /* Pop the partially set up target - unless something else did
6334 already before throwing the exception. */
6335 if (ex
.error
!= TARGET_CLOSE_ERROR
)
6336 remote_unpush_target (remote
);
6341 remote_btrace_reset (rs
);
6343 if (target_async_permitted
)
6344 rs
->wait_forever_enabled_p
= true;
6347 /* Determine if WS represents a fork status. */
6350 is_fork_status (target_waitkind kind
)
6352 return (kind
== TARGET_WAITKIND_FORKED
6353 || kind
== TARGET_WAITKIND_VFORKED
);
6356 /* Return a reference to the field where a pending child status, if
6357 there's one, is recorded. If there's no child event pending, the
6358 returned waitstatus has TARGET_WAITKIND_IGNORE kind. */
6360 static const target_waitstatus
&
6361 thread_pending_status (struct thread_info
*thread
)
6363 return (thread
->has_pending_waitstatus ()
6364 ? thread
->pending_waitstatus ()
6365 : thread
->pending_follow
);
6368 /* Return THREAD's pending status if it is a pending fork/vfork (but
6369 not clone) parent, else return nullptr. */
6371 static const target_waitstatus
*
6372 thread_pending_fork_status (struct thread_info
*thread
)
6374 const target_waitstatus
&ws
= thread_pending_status (thread
);
6376 if (!is_fork_status (ws
.kind ()))
6382 /* Return THREAD's pending status if is is a pending fork/vfork/clone
6383 event, else return nullptr. */
6385 static const target_waitstatus
*
6386 thread_pending_child_status (thread_info
*thread
)
6388 const target_waitstatus
&ws
= thread_pending_status (thread
);
6390 if (!is_new_child_status (ws
.kind ()))
6396 /* Detach the specified process. */
6399 remote_target::remote_detach_pid (int pid
)
6401 struct remote_state
*rs
= get_remote_state ();
6403 /* This should not be necessary, but the handling for D;PID in
6404 GDBserver versions prior to 8.2 incorrectly assumes that the
6405 selected process points to the same process we're detaching,
6406 leading to misbehavior (and possibly GDBserver crashing) when it
6407 does not. Since it's easy and cheap, work around it by forcing
6408 GDBserver to select GDB's current process. */
6409 set_general_process ();
6411 if (m_features
.remote_multi_process_p ())
6412 xsnprintf (rs
->buf
.data (), get_remote_packet_size (), "D;%x", pid
);
6414 strcpy (rs
->buf
.data (), "D");
6419 if (rs
->buf
[0] == 'O' && rs
->buf
[1] == 'K')
6421 else if (rs
->buf
[0] == '\0')
6422 error (_("Remote doesn't know how to detach"));
6425 /* It is possible that we have an unprocessed exit event for this
6426 pid. If this is the case then we can ignore the failure to detach
6427 and just pretend that the detach worked, as far as the user is
6428 concerned, the process exited immediately after the detach. */
6429 bool process_has_already_exited
= false;
6430 remote_notif_get_pending_events (¬if_client_stop
);
6431 for (stop_reply_up
&reply
: rs
->stop_reply_queue
)
6433 if (reply
->ptid
.pid () != pid
)
6436 enum target_waitkind kind
= reply
->ws
.kind ();
6437 if (kind
== TARGET_WAITKIND_EXITED
6438 || kind
== TARGET_WAITKIND_SIGNALLED
)
6440 process_has_already_exited
= true;
6442 ("detach failed, but process already exited");
6447 if (!process_has_already_exited
)
6448 error (_("can't detach process: %s"), (char *) rs
->buf
.data ());
6452 /* This detaches a program to which we previously attached, using
6453 inferior_ptid to identify the process. After this is done, GDB
6454 can be used to debug some other program. We better not have left
6455 any breakpoints in the target program or it'll die when it hits
6459 remote_target::remote_detach_1 (inferior
*inf
, int from_tty
)
6461 int pid
= inferior_ptid
.pid ();
6462 struct remote_state
*rs
= get_remote_state ();
6465 if (!target_has_execution ())
6466 error (_("No process to detach from."));
6468 target_announce_detach (from_tty
);
6470 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
6472 /* If we're in breakpoints-always-inserted mode, or the inferior
6473 is running, we have to remove breakpoints before detaching.
6474 We don't do this in common code instead because not all
6475 targets support removing breakpoints while the target is
6476 running. The remote target / gdbserver does, though. */
6477 remove_breakpoints_inf (current_inferior ());
6480 /* Tell the remote target to detach. */
6481 remote_detach_pid (pid
);
6483 /* Exit only if this is the only active inferior. */
6484 if (from_tty
&& !rs
->extended
&& number_of_live_inferiors (this) == 1)
6485 gdb_puts (_("Ending remote debugging.\n"));
6487 /* See if any thread of the inferior we are detaching has a pending fork
6488 status. In that case, we must detach from the child resulting from
6490 for (thread_info
*thread
: inf
->non_exited_threads ())
6492 const target_waitstatus
*ws
= thread_pending_fork_status (thread
);
6497 remote_detach_pid (ws
->child_ptid ().pid ());
6500 /* Check also for any pending fork events in the stop reply queue. */
6501 remote_notif_get_pending_events (¬if_client_stop
);
6502 for (stop_reply_up
&reply
: rs
->stop_reply_queue
)
6504 if (reply
->ptid
.pid () != pid
)
6507 if (!is_fork_status (reply
->ws
.kind ()))
6510 remote_detach_pid (reply
->ws
.child_ptid ().pid ());
6513 thread_info
*tp
= this->find_thread (inferior_ptid
);
6515 /* Check to see if we are detaching a fork parent. Note that if we
6516 are detaching a fork child, tp == NULL. */
6517 is_fork_parent
= (tp
!= NULL
6518 && tp
->pending_follow
.kind () == TARGET_WAITKIND_FORKED
);
6520 /* If doing detach-on-fork, we don't mourn, because that will delete
6521 breakpoints that should be available for the followed inferior. */
6522 if (!is_fork_parent
)
6524 /* Save the pid as a string before mourning, since that will
6525 unpush the remote target, and we need the string after. */
6526 std::string infpid
= target_pid_to_str (ptid_t (pid
));
6528 target_mourn_inferior (inferior_ptid
);
6529 if (print_inferior_events
)
6530 gdb_printf (_("[Inferior %d (%s) detached]\n"),
6531 inf
->num
, infpid
.c_str ());
6535 switch_to_no_thread ();
6536 detach_inferior (current_inferior ());
6541 remote_target::detach (inferior
*inf
, int from_tty
)
6543 remote_detach_1 (inf
, from_tty
);
6547 extended_remote_target::detach (inferior
*inf
, int from_tty
)
6549 remote_detach_1 (inf
, from_tty
);
6552 /* Target follow-fork function for remote targets. On entry, and
6553 at return, the current inferior is the fork parent.
6555 Note that although this is currently only used for extended-remote,
6556 it is named remote_follow_fork in anticipation of using it for the
6557 remote target as well. */
6560 remote_target::follow_fork (inferior
*child_inf
, ptid_t child_ptid
,
6561 target_waitkind fork_kind
, bool follow_child
,
6564 process_stratum_target::follow_fork (child_inf
, child_ptid
,
6565 fork_kind
, follow_child
, detach_fork
);
6567 if ((fork_kind
== TARGET_WAITKIND_FORKED
6568 && m_features
.remote_fork_event_p ())
6569 || (fork_kind
== TARGET_WAITKIND_VFORKED
6570 && m_features
.remote_vfork_event_p ()))
6572 /* When following the parent and detaching the child, we detach
6573 the child here. For the case of following the child and
6574 detaching the parent, the detach is done in the target-
6575 independent follow fork code in infrun.c. We can't use
6576 target_detach when detaching an unfollowed child because
6577 the client side doesn't know anything about the child. */
6578 if (detach_fork
&& !follow_child
)
6580 /* Detach the fork child. */
6581 remote_detach_pid (child_ptid
.pid ());
6587 remote_target::follow_clone (ptid_t child_ptid
)
6589 remote_add_thread (child_ptid
, false, false, false);
6592 /* Target follow-exec function for remote targets. Save EXECD_PATHNAME
6593 in the program space of the new inferior. */
6596 remote_target::follow_exec (inferior
*follow_inf
, ptid_t ptid
,
6597 const char *execd_pathname
)
6599 process_stratum_target::follow_exec (follow_inf
, ptid
, execd_pathname
);
6601 /* We know that this is a target file name, so if it has the "target:"
6602 prefix we strip it off before saving it in the program space. */
6603 if (is_target_filename (execd_pathname
))
6604 execd_pathname
+= strlen (TARGET_SYSROOT_PREFIX
);
6606 set_pspace_remote_exec_file (follow_inf
->pspace
, execd_pathname
);
6609 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
6612 remote_target::disconnect (const char *args
, int from_tty
)
6615 error (_("Argument given to \"disconnect\" when remotely debugging."));
6617 /* Make sure we unpush even the extended remote targets. Calling
6618 target_mourn_inferior won't unpush, and
6619 remote_target::mourn_inferior won't unpush if there is more than
6620 one inferior left. */
6621 remote_unpush_target (this);
6624 gdb_puts ("Ending remote debugging.\n");
6627 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
6628 be chatty about it. */
6631 extended_remote_target::attach (const char *args
, int from_tty
)
6633 struct remote_state
*rs
= get_remote_state ();
6635 char *wait_status
= NULL
;
6637 pid
= parse_pid_to_attach (args
);
6639 /* Remote PID can be freely equal to getpid, do not check it here the same
6640 way as in other targets. */
6642 if (m_features
.packet_support (PACKET_vAttach
) == PACKET_DISABLE
)
6643 error (_("This target does not support attaching to a process"));
6645 target_announce_attach (from_tty
, pid
);
6647 xsnprintf (rs
->buf
.data (), get_remote_packet_size (), "vAttach;%x", pid
);
6651 packet_result result
= m_features
.packet_ok (rs
->buf
, PACKET_vAttach
);
6652 switch (result
.status ())
6655 if (!target_is_non_stop_p ())
6657 /* Save the reply for later. */
6658 wait_status
= (char *) alloca (strlen (rs
->buf
.data ()) + 1);
6659 strcpy (wait_status
, rs
->buf
.data ());
6661 else if (strcmp (rs
->buf
.data (), "OK") != 0)
6662 error (_("Attaching to %s failed with: %s"),
6663 target_pid_to_str (ptid_t (pid
)).c_str (),
6666 case PACKET_UNKNOWN
:
6667 error (_("This target does not support attaching to a process"));
6669 error (_("Attaching to %s failed: %s"),
6670 target_pid_to_str (ptid_t (pid
)).c_str (), result
.err_msg ());
6673 switch_to_inferior_no_thread (remote_add_inferior (false, pid
, 1, 0));
6675 inferior_ptid
= ptid_t (pid
);
6677 if (target_is_non_stop_p ())
6679 /* Get list of threads. */
6680 update_thread_list ();
6682 thread_info
*thread
= first_thread_of_inferior (current_inferior ());
6683 if (thread
!= nullptr)
6684 switch_to_thread (thread
);
6686 /* Invalidate our notion of the remote current thread. */
6687 record_currthread (rs
, minus_one_ptid
);
6691 /* Now, if we have thread information, update the main thread's
6693 ptid_t curr_ptid
= remote_current_thread (ptid_t (pid
));
6695 /* Add the main thread to the thread list. We add the thread
6696 silently in this case (the final true parameter). */
6697 thread_info
*thr
= remote_add_thread (curr_ptid
, true, true, true);
6699 switch_to_thread (thr
);
6702 /* Next, if the target can specify a description, read it. We do
6703 this before anything involving memory or registers. */
6704 target_find_description ();
6706 if (!target_is_non_stop_p ())
6708 /* Use the previously fetched status. */
6709 gdb_assert (wait_status
!= NULL
);
6711 notif_event_up reply
6712 = remote_notif_parse (this, ¬if_client_stop
, wait_status
);
6713 push_stop_reply (as_stop_reply_up (std::move (reply
)));
6717 gdb_assert (wait_status
== NULL
);
6719 gdb_assert (target_can_async_p ());
6723 /* Implementation of the to_post_attach method. */
6726 extended_remote_target::post_attach (int pid
)
6728 /* Get text, data & bss offsets. */
6731 /* In certain cases GDB might not have had the chance to start
6732 symbol lookup up until now. This could happen if the debugged
6733 binary is not using shared libraries, the vsyscall page is not
6734 present (on Linux) and the binary itself hadn't changed since the
6735 debugging process was started. */
6736 if (current_program_space
->symfile_object_file
!= NULL
)
6737 remote_check_symbols();
6741 /* Check for the availability of vCont. This function should also check
6745 remote_target::remote_vcont_probe ()
6747 remote_state
*rs
= get_remote_state ();
6750 strcpy (rs
->buf
.data (), "vCont?");
6753 buf
= rs
->buf
.data ();
6755 /* Make sure that the features we assume are supported. */
6756 if (startswith (buf
, "vCont"))
6759 int support_c
, support_C
;
6761 rs
->supports_vCont
.s
= 0;
6762 rs
->supports_vCont
.S
= 0;
6765 rs
->supports_vCont
.t
= 0;
6766 rs
->supports_vCont
.r
= 0;
6767 while (p
&& *p
== ';')
6770 if (*p
== 's' && (*(p
+ 1) == ';' || *(p
+ 1) == 0))
6771 rs
->supports_vCont
.s
= 1;
6772 else if (*p
== 'S' && (*(p
+ 1) == ';' || *(p
+ 1) == 0))
6773 rs
->supports_vCont
.S
= 1;
6774 else if (*p
== 'c' && (*(p
+ 1) == ';' || *(p
+ 1) == 0))
6776 else if (*p
== 'C' && (*(p
+ 1) == ';' || *(p
+ 1) == 0))
6778 else if (*p
== 't' && (*(p
+ 1) == ';' || *(p
+ 1) == 0))
6779 rs
->supports_vCont
.t
= 1;
6780 else if (*p
== 'r' && (*(p
+ 1) == ';' || *(p
+ 1) == 0))
6781 rs
->supports_vCont
.r
= 1;
6783 p
= strchr (p
, ';');
6786 /* If c, and C are not all supported, we can't use vCont. Clearing
6787 BUF will make packet_ok disable the packet. */
6788 if (!support_c
|| !support_C
)
6792 m_features
.packet_ok (rs
->buf
, PACKET_vCont
);
6795 /* Helper function for building "vCont" resumptions. Write a
6796 resumption to P. ENDP points to one-passed-the-end of the buffer
6797 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
6798 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
6799 resumed thread should be single-stepped and/or signalled. If PTID
6800 equals minus_one_ptid, then all threads are resumed; if PTID
6801 represents a process, then all threads of the process are
6805 remote_target::append_resumption (char *p
, char *endp
,
6806 ptid_t ptid
, int step
, gdb_signal siggnal
)
6808 struct remote_state
*rs
= get_remote_state ();
6810 if (step
&& siggnal
!= GDB_SIGNAL_0
)
6811 p
+= xsnprintf (p
, endp
- p
, ";S%02x", siggnal
);
6813 /* GDB is willing to range step. */
6814 && use_range_stepping
6815 /* Target supports range stepping. */
6816 && rs
->supports_vCont
.r
6817 /* We don't currently support range stepping multiple
6818 threads with a wildcard (though the protocol allows it,
6819 so stubs shouldn't make an active effort to forbid
6821 && !(m_features
.remote_multi_process_p () && ptid
.is_pid ()))
6823 struct thread_info
*tp
;
6825 if (ptid
== minus_one_ptid
)
6827 /* If we don't know about the target thread's tid, then
6828 we're resuming magic_null_ptid (see caller). */
6829 tp
= this->find_thread (magic_null_ptid
);
6832 tp
= this->find_thread (ptid
);
6833 gdb_assert (tp
!= NULL
);
6835 if (tp
->control
.may_range_step
)
6837 int addr_size
= gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
6839 p
+= xsnprintf (p
, endp
- p
, ";r%s,%s",
6840 phex_nz (tp
->control
.step_range_start
,
6842 phex_nz (tp
->control
.step_range_end
,
6846 p
+= xsnprintf (p
, endp
- p
, ";s");
6849 p
+= xsnprintf (p
, endp
- p
, ";s");
6850 else if (siggnal
!= GDB_SIGNAL_0
)
6851 p
+= xsnprintf (p
, endp
- p
, ";C%02x", siggnal
);
6853 p
+= xsnprintf (p
, endp
- p
, ";c");
6855 if (m_features
.remote_multi_process_p () && ptid
.is_pid ())
6859 /* All (-1) threads of process. */
6860 nptid
= ptid_t (ptid
.pid (), -1);
6862 p
+= xsnprintf (p
, endp
- p
, ":");
6863 p
= write_ptid (p
, endp
, nptid
);
6865 else if (ptid
!= minus_one_ptid
)
6867 p
+= xsnprintf (p
, endp
- p
, ":");
6868 p
= write_ptid (p
, endp
, ptid
);
6874 /* Clear the thread's private info on resume. */
6877 resume_clear_thread_private_info (struct thread_info
*thread
)
6879 if (thread
->priv
!= NULL
)
6881 remote_thread_info
*priv
= get_remote_thread_info (thread
);
6883 priv
->stop_reason
= TARGET_STOPPED_BY_NO_REASON
;
6884 priv
->watch_data_address
= 0;
6888 /* Append a vCont continue-with-signal action for threads that have a
6889 non-zero stop signal. */
6892 remote_target::append_pending_thread_resumptions (char *p
, char *endp
,
6895 for (thread_info
*thread
: all_non_exited_threads (this, ptid
))
6896 if (inferior_ptid
!= thread
->ptid
6897 && thread
->stop_signal () != GDB_SIGNAL_0
)
6899 p
= append_resumption (p
, endp
, thread
->ptid
,
6900 0, thread
->stop_signal ());
6901 thread
->set_stop_signal (GDB_SIGNAL_0
);
6902 resume_clear_thread_private_info (thread
);
6908 /* Set the target running, using the packets that use Hc
6912 remote_target::remote_resume_with_hc (ptid_t ptid
, int step
,
6915 struct remote_state
*rs
= get_remote_state ();
6918 rs
->last_sent_signal
= siggnal
;
6919 rs
->last_sent_step
= step
;
6921 /* The c/s/C/S resume packets use Hc, so set the continue
6923 if (ptid
== minus_one_ptid
)
6924 set_continue_thread (any_thread_ptid
);
6926 set_continue_thread (ptid
);
6928 for (thread_info
*thread
: all_non_exited_threads (this))
6929 resume_clear_thread_private_info (thread
);
6931 buf
= rs
->buf
.data ();
6932 if (::execution_direction
== EXEC_REVERSE
)
6934 /* We don't pass signals to the target in reverse exec mode. */
6935 if (info_verbose
&& siggnal
!= GDB_SIGNAL_0
)
6936 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
6939 if (step
&& m_features
.packet_support (PACKET_bs
) == PACKET_DISABLE
)
6940 error (_("Remote reverse-step not supported."));
6941 if (!step
&& m_features
.packet_support (PACKET_bc
) == PACKET_DISABLE
)
6942 error (_("Remote reverse-continue not supported."));
6944 strcpy (buf
, step
? "bs" : "bc");
6946 else if (siggnal
!= GDB_SIGNAL_0
)
6948 buf
[0] = step
? 'S' : 'C';
6949 buf
[1] = tohex (((int) siggnal
>> 4) & 0xf);
6950 buf
[2] = tohex (((int) siggnal
) & 0xf);
6954 strcpy (buf
, step
? "s" : "c");
6959 /* Resume the remote inferior by using a "vCont" packet. SCOPE_PTID,
6960 STEP, and SIGGNAL have the same meaning as in target_resume. This
6961 function returns non-zero iff it resumes the inferior.
6963 This function issues a strict subset of all possible vCont commands
6967 remote_target::remote_resume_with_vcont (ptid_t scope_ptid
, int step
,
6968 enum gdb_signal siggnal
)
6970 struct remote_state
*rs
= get_remote_state ();
6974 /* No reverse execution actions defined for vCont. */
6975 if (::execution_direction
== EXEC_REVERSE
)
6978 if (m_features
.packet_support (PACKET_vCont
) == PACKET_DISABLE
)
6981 p
= rs
->buf
.data ();
6982 endp
= p
+ get_remote_packet_size ();
6984 /* If we could generate a wider range of packets, we'd have to worry
6985 about overflowing BUF. Should there be a generic
6986 "multi-part-packet" packet? */
6988 p
+= xsnprintf (p
, endp
- p
, "vCont");
6990 if (scope_ptid
== magic_null_ptid
)
6992 /* MAGIC_NULL_PTID means that we don't have any active threads,
6993 so we don't have any TID numbers the inferior will
6994 understand. Make sure to only send forms that do not specify
6996 append_resumption (p
, endp
, minus_one_ptid
, step
, siggnal
);
6998 else if (scope_ptid
== minus_one_ptid
|| scope_ptid
.is_pid ())
7000 /* Resume all threads (of all processes, or of a single
7001 process), with preference for INFERIOR_PTID. This assumes
7002 inferior_ptid belongs to the set of all threads we are about
7004 if (step
|| siggnal
!= GDB_SIGNAL_0
)
7006 /* Step inferior_ptid, with or without signal. */
7007 p
= append_resumption (p
, endp
, inferior_ptid
, step
, siggnal
);
7010 /* Also pass down any pending signaled resumption for other
7011 threads not the current. */
7012 p
= append_pending_thread_resumptions (p
, endp
, scope_ptid
);
7014 /* And continue others without a signal. */
7015 append_resumption (p
, endp
, scope_ptid
, /*step=*/ 0, GDB_SIGNAL_0
);
7019 /* Scheduler locking; resume only SCOPE_PTID. */
7020 append_resumption (p
, endp
, scope_ptid
, step
, siggnal
);
7023 gdb_assert (strlen (rs
->buf
.data ()) < get_remote_packet_size ());
7026 if (target_is_non_stop_p ())
7028 /* In non-stop, the stub replies to vCont with "OK". The stop
7029 reply will be reported asynchronously by means of a `%Stop'
7032 if (strcmp (rs
->buf
.data (), "OK") != 0)
7033 error (_("Unexpected vCont reply in non-stop mode: %s"),
7040 /* Tell the remote machine to resume. */
7043 remote_target::resume (ptid_t scope_ptid
, int step
, enum gdb_signal siggnal
)
7045 struct remote_state
*rs
= get_remote_state ();
7047 /* When connected in non-stop mode, the core resumes threads
7048 individually. Resuming remote threads directly in target_resume
7049 would thus result in sending one packet per thread. Instead, to
7050 minimize roundtrip latency, here we just store the resume
7051 request (put the thread in RESUMED_PENDING_VCONT state); the actual remote
7052 resumption will be done in remote_target::commit_resume, where we'll be
7053 able to do vCont action coalescing. */
7054 if (target_is_non_stop_p () && ::execution_direction
!= EXEC_REVERSE
)
7056 remote_thread_info
*remote_thr
7057 = get_remote_thread_info (inferior_thread ());
7059 /* We don't expect the core to ask to resume an already resumed (from
7060 its point of view) thread. */
7061 gdb_assert (remote_thr
->get_resume_state () == resume_state::NOT_RESUMED
);
7063 remote_thr
->set_resumed_pending_vcont (step
, siggnal
);
7065 /* There's actually nothing that says that the core can't
7066 request a wildcard resume in non-stop mode, though. It's
7067 just that we know it doesn't currently, so we don't bother
7069 gdb_assert (scope_ptid
== inferior_ptid
);
7073 commit_requested_thread_options ();
7075 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
7076 (explained in remote-notif.c:handle_notification) so
7077 remote_notif_process is not called. We need find a place where
7078 it is safe to start a 'vNotif' sequence. It is good to do it
7079 before resuming inferior, because inferior was stopped and no RSP
7080 traffic at that moment. */
7081 if (!target_is_non_stop_p ())
7082 remote_notif_process (rs
->notif_state
, ¬if_client_stop
);
7084 rs
->last_resume_exec_dir
= ::execution_direction
;
7086 /* Prefer vCont, and fallback to s/c/S/C, which use Hc. */
7087 if (!remote_resume_with_vcont (scope_ptid
, step
, siggnal
))
7088 remote_resume_with_hc (scope_ptid
, step
, siggnal
);
7090 /* Update resumed state tracked by the remote target. */
7091 for (thread_info
*tp
: all_non_exited_threads (this, scope_ptid
))
7092 get_remote_thread_info (tp
)->set_resumed ();
7094 /* We've just told the target to resume. The remote server will
7095 wait for the inferior to stop, and then send a stop reply. In
7096 the mean time, we can't start another command/query ourselves
7097 because the stub wouldn't be ready to process it. This applies
7098 only to the base all-stop protocol, however. In non-stop (which
7099 only supports vCont), the stub replies with an "OK", and is
7100 immediate able to process further serial input. */
7101 if (!target_is_non_stop_p ())
7102 rs
->waiting_for_stop_reply
= 1;
7105 /* Private per-inferior info for target remote processes. */
7107 struct remote_inferior
: public private_inferior
7109 /* Whether we can send a wildcard vCont for this process. */
7110 bool may_wildcard_vcont
= true;
7113 /* Get the remote private inferior data associated to INF. */
7115 static remote_inferior
*
7116 get_remote_inferior (inferior
*inf
)
7118 if (inf
->priv
== NULL
)
7119 inf
->priv
= std::make_unique
<remote_inferior
> ();
7121 return gdb::checked_static_cast
<remote_inferior
*> (inf
->priv
.get ());
7124 /* Class used to track the construction of a vCont packet in the
7125 outgoing packet buffer. This is used to send multiple vCont
7126 packets if we have more actions than would fit a single packet. */
7131 explicit vcont_builder (remote_target
*remote
)
7138 void push_action (ptid_t ptid
, bool step
, gdb_signal siggnal
);
7143 /* The remote target. */
7144 remote_target
*m_remote
;
7146 /* Pointer to the first action. P points here if no action has been
7148 char *m_first_action
;
7150 /* Where the next action will be appended. */
7153 /* The end of the buffer. Must never write past this. */
7157 /* Prepare the outgoing buffer for a new vCont packet. */
7160 vcont_builder::restart ()
7162 struct remote_state
*rs
= m_remote
->get_remote_state ();
7164 m_p
= rs
->buf
.data ();
7165 m_endp
= m_p
+ m_remote
->get_remote_packet_size ();
7166 m_p
+= xsnprintf (m_p
, m_endp
- m_p
, "vCont");
7167 m_first_action
= m_p
;
7170 /* If the vCont packet being built has any action, send it to the
7174 vcont_builder::flush ()
7176 struct remote_state
*rs
;
7178 if (m_p
== m_first_action
)
7181 rs
= m_remote
->get_remote_state ();
7182 m_remote
->putpkt (rs
->buf
);
7183 m_remote
->getpkt (&rs
->buf
);
7184 if (strcmp (rs
->buf
.data (), "OK") != 0)
7185 error (_("Unexpected vCont reply in non-stop mode: %s"), rs
->buf
.data ());
7188 /* The largest action is range-stepping, with its two addresses. This
7189 is more than sufficient. If a new, bigger action is created, it'll
7190 quickly trigger a failed assertion in append_resumption (and we'll
7192 #define MAX_ACTION_SIZE 200
7194 /* Append a new vCont action in the outgoing packet being built. If
7195 the action doesn't fit the packet along with previous actions, push
7196 what we've got so far to the remote end and start over a new vCont
7197 packet (with the new action). */
7200 vcont_builder::push_action (ptid_t ptid
, bool step
, gdb_signal siggnal
)
7202 char buf
[MAX_ACTION_SIZE
+ 1];
7204 char *endp
= m_remote
->append_resumption (buf
, buf
+ sizeof (buf
),
7205 ptid
, step
, siggnal
);
7207 /* Check whether this new action would fit in the vCont packet along
7208 with previous actions. If not, send what we've got so far and
7209 start a new vCont packet. */
7210 size_t rsize
= endp
- buf
;
7211 if (rsize
> m_endp
- m_p
)
7216 /* Should now fit. */
7217 gdb_assert (rsize
<= m_endp
- m_p
);
7220 memcpy (m_p
, buf
, rsize
);
7225 /* to_commit_resume implementation. */
7228 remote_target::commit_resumed ()
7230 /* If connected in all-stop mode, we'd send the remote resume
7231 request directly from remote_resume. Likewise if
7232 reverse-debugging, as there are no defined vCont actions for
7233 reverse execution. */
7234 if (!target_is_non_stop_p () || ::execution_direction
== EXEC_REVERSE
)
7237 commit_requested_thread_options ();
7239 /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
7240 instead of resuming all threads of each process individually.
7241 However, if any thread of a process must remain halted, we can't
7242 send wildcard resumes and must send one action per thread.
7244 Care must be taken to not resume threads/processes the server
7245 side already told us are stopped, but the core doesn't know about
7246 yet, because the events are still in the vStopped notification
7249 #1 => vCont s:p1.1;c
7251 #3 <= %Stopped T05 p1.1
7256 #8 (infrun handles the stop for p1.1 and continues stepping)
7257 #9 => vCont s:p1.1;c
7259 The last vCont above would resume thread p1.2 by mistake, because
7260 the server has no idea that the event for p1.2 had not been
7263 The server side must similarly ignore resume actions for the
7264 thread that has a pending %Stopped notification (and any other
7265 threads with events pending), until GDB acks the notification
7266 with vStopped. Otherwise, e.g., the following case is
7269 #1 => g (or any other packet)
7271 #3 <= %Stopped T05 p1.2
7272 #4 => vCont s:p1.1;c
7275 Above, the server must not resume thread p1.2. GDB can't know
7276 that p1.2 stopped until it acks the %Stopped notification, and
7277 since from GDB's perspective all threads should be running, it
7280 Finally, special care must also be given to handling fork/vfork
7281 events. A (v)fork event actually tells us that two processes
7282 stopped -- the parent and the child. Until we follow the fork,
7283 we must not resume the child. Therefore, if we have a pending
7284 fork follow, we must not send a global wildcard resume action
7285 (vCont;c). We can still send process-wide wildcards though. */
7287 /* Start by assuming a global wildcard (vCont;c) is possible. */
7288 bool may_global_wildcard_vcont
= true;
7290 /* And assume every process is individually wildcard-able too. */
7291 for (inferior
*inf
: all_non_exited_inferiors (this))
7293 remote_inferior
*priv
= get_remote_inferior (inf
);
7295 priv
->may_wildcard_vcont
= true;
7298 /* Check for any pending events (not reported or processed yet) and
7299 disable process and global wildcard resumes appropriately. */
7300 check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont
);
7302 bool any_pending_vcont_resume
= false;
7304 for (thread_info
*tp
: all_non_exited_threads (this))
7306 remote_thread_info
*priv
= get_remote_thread_info (tp
);
7308 /* If a thread of a process is not meant to be resumed, then we
7309 can't wildcard that process. */
7310 if (priv
->get_resume_state () == resume_state::NOT_RESUMED
)
7312 get_remote_inferior (tp
->inf
)->may_wildcard_vcont
= false;
7314 /* And if we can't wildcard a process, we can't wildcard
7315 everything either. */
7316 may_global_wildcard_vcont
= false;
7320 if (priv
->get_resume_state () == resume_state::RESUMED_PENDING_VCONT
)
7321 any_pending_vcont_resume
= true;
7323 /* If a thread is the parent of an unfollowed fork/vfork/clone,
7324 then we can't do a global wildcard, as that would resume the
7326 if (thread_pending_child_status (tp
) != nullptr)
7327 may_global_wildcard_vcont
= false;
7330 /* We didn't have any resumed thread pending a vCont resume, so nothing to
7332 if (!any_pending_vcont_resume
)
7335 /* Now let's build the vCont packet(s). Actions must be appended
7336 from narrower to wider scopes (thread -> process -> global). If
7337 we end up with too many actions for a single packet vcont_builder
7338 flushes the current vCont packet to the remote side and starts a
7340 struct vcont_builder
vcont_builder (this);
7342 /* Threads first. */
7343 for (thread_info
*tp
: all_non_exited_threads (this))
7345 remote_thread_info
*remote_thr
= get_remote_thread_info (tp
);
7347 /* If the thread was previously vCont-resumed, no need to send a specific
7348 action for it. If we didn't receive a resume request for it, don't
7349 send an action for it either. */
7350 if (remote_thr
->get_resume_state () != resume_state::RESUMED_PENDING_VCONT
)
7353 gdb_assert (!thread_is_in_step_over_chain (tp
));
7355 /* We should never be commit-resuming a thread that has a stop reply.
7356 Otherwise, we would end up reporting a stop event for a thread while
7357 it is running on the remote target. */
7358 remote_state
*rs
= get_remote_state ();
7359 for (const auto &stop_reply
: rs
->stop_reply_queue
)
7360 gdb_assert (stop_reply
->ptid
!= tp
->ptid
);
7362 const resumed_pending_vcont_info
&info
7363 = remote_thr
->resumed_pending_vcont_info ();
7365 /* Check if we need to send a specific action for this thread. If not,
7366 it will be included in a wildcard resume instead. */
7367 if (info
.step
|| info
.sig
!= GDB_SIGNAL_0
7368 || !get_remote_inferior (tp
->inf
)->may_wildcard_vcont
)
7369 vcont_builder
.push_action (tp
->ptid
, info
.step
, info
.sig
);
7371 remote_thr
->set_resumed ();
7374 /* Now check whether we can send any process-wide wildcard. This is
7375 to avoid sending a global wildcard in the case nothing is
7376 supposed to be resumed. */
7377 bool any_process_wildcard
= false;
7379 for (inferior
*inf
: all_non_exited_inferiors (this))
7381 if (get_remote_inferior (inf
)->may_wildcard_vcont
)
7383 any_process_wildcard
= true;
7388 if (any_process_wildcard
)
7390 /* If all processes are wildcard-able, then send a single "c"
7391 action, otherwise, send an "all (-1) threads of process"
7392 continue action for each running process, if any. */
7393 if (may_global_wildcard_vcont
)
7395 vcont_builder
.push_action (minus_one_ptid
,
7396 false, GDB_SIGNAL_0
);
7400 for (inferior
*inf
: all_non_exited_inferiors (this))
7402 if (get_remote_inferior (inf
)->may_wildcard_vcont
)
7404 vcont_builder
.push_action (ptid_t (inf
->pid
),
7405 false, GDB_SIGNAL_0
);
7411 vcont_builder
.flush ();
7414 /* Implementation of target_has_pending_events. */
7417 remote_target::has_pending_events ()
7419 if (target_can_async_p ())
7421 remote_state
*rs
= get_remote_state ();
7423 if (rs
->async_event_handler_marked ())
7426 /* Note that BUFCNT can be negative, indicating sticky
7428 if (rs
->remote_desc
->bufcnt
!= 0)
7436 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
7437 thread, all threads of a remote process, or all threads of all
7441 remote_target::remote_stop_ns (ptid_t ptid
)
7443 struct remote_state
*rs
= get_remote_state ();
7444 char *p
= rs
->buf
.data ();
7445 char *endp
= p
+ get_remote_packet_size ();
7447 /* If any thread that needs to stop was resumed but pending a vCont
7448 resume, generate a phony stop_reply. However, first check
7449 whether the thread wasn't resumed with a signal. Generating a
7450 phony stop in that case would result in losing the signal. */
7451 bool needs_commit
= false;
7452 for (thread_info
*tp
: all_non_exited_threads (this, ptid
))
7454 remote_thread_info
*remote_thr
= get_remote_thread_info (tp
);
7456 if (remote_thr
->get_resume_state ()
7457 == resume_state::RESUMED_PENDING_VCONT
)
7459 const resumed_pending_vcont_info
&info
7460 = remote_thr
->resumed_pending_vcont_info ();
7461 if (info
.sig
!= GDB_SIGNAL_0
)
7463 /* This signal must be forwarded to the inferior. We
7464 could commit-resume just this thread, but its simpler
7465 to just commit-resume everything. */
7466 needs_commit
= true;
7475 for (thread_info
*tp
: all_non_exited_threads (this, ptid
))
7477 remote_thread_info
*remote_thr
= get_remote_thread_info (tp
);
7479 if (remote_thr
->get_resume_state ()
7480 == resume_state::RESUMED_PENDING_VCONT
)
7482 remote_debug_printf ("Enqueueing phony stop reply for thread pending "
7483 "vCont-resume (%d, %ld, %s)", tp
->ptid
.pid(),
7485 pulongest (tp
->ptid
.tid ()));
7487 /* Check that the thread wasn't resumed with a signal.
7488 Generating a phony stop would result in losing the
7490 const resumed_pending_vcont_info
&info
7491 = remote_thr
->resumed_pending_vcont_info ();
7492 gdb_assert (info
.sig
== GDB_SIGNAL_0
);
7494 stop_reply_up sr
= std::make_unique
<stop_reply
> ();
7495 sr
->ptid
= tp
->ptid
;
7497 sr
->ws
.set_stopped (GDB_SIGNAL_0
);
7498 sr
->arch
= tp
->inf
->arch ();
7499 sr
->stop_reason
= TARGET_STOPPED_BY_NO_REASON
;
7500 sr
->watch_data_address
= 0;
7502 this->push_stop_reply (std::move (sr
));
7504 /* Pretend that this thread was actually resumed on the
7505 remote target, then stopped. If we leave it in the
7506 RESUMED_PENDING_VCONT state and the commit_resumed
7507 method is called while the stop reply is still in the
7508 queue, we'll end up reporting a stop event to the core
7509 for that thread while it is running on the remote
7510 target... that would be bad. */
7511 remote_thr
->set_resumed ();
7515 if (!rs
->supports_vCont
.t
)
7516 error (_("Remote server does not support stopping threads"));
7518 if (ptid
== minus_one_ptid
7519 || (!m_features
.remote_multi_process_p () && ptid
.is_pid ()))
7520 p
+= xsnprintf (p
, endp
- p
, "vCont;t");
7525 p
+= xsnprintf (p
, endp
- p
, "vCont;t:");
7528 /* All (-1) threads of process. */
7529 nptid
= ptid_t (ptid
.pid (), -1);
7532 /* Small optimization: if we already have a stop reply for
7533 this thread, no use in telling the stub we want this
7535 if (peek_stop_reply (ptid
))
7541 write_ptid (p
, endp
, nptid
);
7544 /* In non-stop, we get an immediate OK reply. The stop reply will
7545 come in asynchronously by notification. */
7548 if (strcmp (rs
->buf
.data (), "OK") != 0)
7549 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid
).c_str (),
7553 /* All-stop version of target_interrupt. Sends a break or a ^C to
7554 interrupt the remote target. It is undefined which thread of which
7555 process reports the interrupt. */
7558 remote_target::remote_interrupt_as ()
7560 struct remote_state
*rs
= get_remote_state ();
7562 rs
->ctrlc_pending_p
= 1;
7564 /* If the inferior is stopped already, but the core didn't know
7565 about it yet, just ignore the request. The pending stop events
7566 will be collected in remote_wait. */
7567 if (stop_reply_queue_length () > 0)
7570 /* Send interrupt_sequence to remote target. */
7571 send_interrupt_sequence ();
7574 /* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
7575 the remote target. It is undefined which thread of which process
7576 reports the interrupt. Throws an error if the packet is not
7577 supported by the server. */
7580 remote_target::remote_interrupt_ns ()
7582 struct remote_state
*rs
= get_remote_state ();
7583 char *p
= rs
->buf
.data ();
7584 char *endp
= p
+ get_remote_packet_size ();
7586 xsnprintf (p
, endp
- p
, "vCtrlC");
7588 /* In non-stop, we get an immediate OK reply. The stop reply will
7589 come in asynchronously by notification. */
7593 packet_result result
= m_features
.packet_ok (rs
->buf
, PACKET_vCtrlC
);
7594 switch (result
.status ())
7598 case PACKET_UNKNOWN
:
7599 error (_("No support for interrupting the remote target."));
7601 error (_("Interrupting target failed: %s"), result
.err_msg ());
7605 /* Implement the to_stop function for the remote targets. */
7608 remote_target::stop (ptid_t ptid
)
7610 REMOTE_SCOPED_DEBUG_ENTER_EXIT
;
7612 if (target_is_non_stop_p ())
7613 remote_stop_ns (ptid
);
7616 /* We don't currently have a way to transparently pause the
7617 remote target in all-stop mode. Interrupt it instead. */
7618 remote_interrupt_as ();
7622 /* Implement the to_interrupt function for the remote targets. */
7625 remote_target::interrupt ()
7627 REMOTE_SCOPED_DEBUG_ENTER_EXIT
;
7629 if (target_is_non_stop_p ())
7630 remote_interrupt_ns ();
7632 remote_interrupt_as ();
7635 /* Implement the to_pass_ctrlc function for the remote targets. */
7638 remote_target::pass_ctrlc ()
7640 REMOTE_SCOPED_DEBUG_ENTER_EXIT
;
7642 struct remote_state
*rs
= get_remote_state ();
7644 /* If we're starting up, we're not fully synced yet. Quit
7646 if (rs
->starting_up
)
7648 /* If ^C has already been sent once, offer to disconnect. */
7649 else if (rs
->ctrlc_pending_p
)
7652 target_interrupt ();
7655 /* Ask the user what to do when an interrupt is received. */
7658 remote_target::interrupt_query ()
7660 struct remote_state
*rs
= get_remote_state ();
7662 if (rs
->waiting_for_stop_reply
&& rs
->ctrlc_pending_p
)
7664 if (query (_("The target is not responding to interrupt requests.\n"
7665 "Stop debugging it? ")))
7667 remote_unpush_target (this);
7668 throw_error (TARGET_CLOSE_ERROR
, _("Disconnected from target."));
7673 if (query (_("Interrupted while waiting for the program.\n"
7674 "Give up waiting? ")))
7679 /* Enable/disable target terminal ownership. Most targets can use
7680 terminal groups to control terminal ownership. Remote targets are
7681 different in that explicit transfer of ownership to/from GDB/target
7685 remote_target::terminal_inferior ()
7687 /* NOTE: At this point we could also register our selves as the
7688 recipient of all input. Any characters typed could then be
7689 passed on down to the target. */
7693 remote_target::terminal_ours ()
7698 remote_console_output (const char *msg
, ui_file
*stream
)
7702 for (p
= msg
; p
[0] && p
[1]; p
+= 2)
7705 char c
= fromhex (p
[0]) * 16 + fromhex (p
[1]);
7714 /* Return the length of the stop reply queue. */
7717 remote_target::stop_reply_queue_length ()
7719 remote_state
*rs
= get_remote_state ();
7720 return rs
->stop_reply_queue
.size ();
7724 remote_notif_stop_parse (remote_target
*remote
,
7725 const notif_client
*self
, const char *buf
,
7726 struct notif_event
*event
)
7728 remote
->remote_parse_stop_reply (buf
, (struct stop_reply
*) event
);
7732 remote_notif_stop_ack (remote_target
*remote
,
7733 const notif_client
*self
, const char *buf
,
7734 notif_event_up event
)
7736 stop_reply_up stop_reply
= as_stop_reply_up (std::move (event
));
7739 putpkt (remote
, self
->ack_command
);
7741 /* Kind can be TARGET_WAITKIND_IGNORE if we have meanwhile discarded
7742 the notification. It was left in the queue because we need to
7743 acknowledge it and pull the rest of the notifications out. */
7744 if (stop_reply
->ws
.kind () != TARGET_WAITKIND_IGNORE
)
7745 remote
->push_stop_reply (std::move (stop_reply
));
7749 remote_notif_stop_can_get_pending_events (remote_target
*remote
,
7750 const notif_client
*self
)
7752 /* We can't get pending events in remote_notif_process for
7753 notification stop, and we have to do this in remote_wait_ns
7754 instead. If we fetch all queued events from stub, remote stub
7755 may exit and we have no chance to process them back in
7757 remote_state
*rs
= remote
->get_remote_state ();
7758 rs
->mark_async_event_handler ();
7762 static notif_event_up
7763 remote_notif_stop_alloc_reply ()
7765 return notif_event_up (new struct stop_reply ());
7768 /* A client of notification Stop. */
7770 const notif_client notif_client_stop
=
7774 remote_notif_stop_parse
,
7775 remote_notif_stop_ack
,
7776 remote_notif_stop_can_get_pending_events
,
7777 remote_notif_stop_alloc_reply
,
7781 /* If CONTEXT contains any fork/vfork/clone child threads that have
7782 not been reported yet, remove them from the CONTEXT list. If such
7783 a thread exists it is because we are stopped at a fork/vfork/clone
7784 catchpoint and have not yet called follow_fork/follow_clone, which
7785 will set up the host-side data structures for the new child. */
7788 remote_target::remove_new_children (threads_listing_context
*context
)
7790 const notif_client
*notif
= ¬if_client_stop
;
7792 /* For any threads stopped at a (v)fork/clone event, remove the
7793 corresponding child threads from the CONTEXT list. */
7794 for (thread_info
*thread
: all_non_exited_threads (this))
7796 const target_waitstatus
*ws
= thread_pending_child_status (thread
);
7801 context
->remove_thread (ws
->child_ptid ());
7804 /* Check for any pending (v)fork/clone events (not reported or
7805 processed yet) in process PID and remove those child threads from
7806 the CONTEXT list as well. */
7807 remote_notif_get_pending_events (notif
);
7808 for (auto &event
: get_remote_state ()->stop_reply_queue
)
7809 if (is_new_child_status (event
->ws
.kind ()))
7810 context
->remove_thread (event
->ws
.child_ptid ());
7811 else if (event
->ws
.kind () == TARGET_WAITKIND_THREAD_EXITED
)
7812 context
->remove_thread (event
->ptid
);
7815 /* Check whether any event pending in the vStopped queue would prevent a
7816 global or process wildcard vCont action. Set *may_global_wildcard to
7817 false if we can't do a global wildcard (vCont;c), and clear the event
7818 inferior's may_wildcard_vcont flag if we can't do a process-wide
7819 wildcard resume (vCont;c:pPID.-1). */
7822 remote_target::check_pending_events_prevent_wildcard_vcont
7823 (bool *may_global_wildcard
)
7825 const notif_client
*notif
= ¬if_client_stop
;
7827 remote_notif_get_pending_events (notif
);
7828 for (auto &event
: get_remote_state ()->stop_reply_queue
)
7830 if (event
->ws
.kind () == TARGET_WAITKIND_NO_RESUMED
7831 || event
->ws
.kind () == TARGET_WAITKIND_NO_HISTORY
)
7834 if (event
->ws
.kind () == TARGET_WAITKIND_FORKED
7835 || event
->ws
.kind () == TARGET_WAITKIND_VFORKED
)
7836 *may_global_wildcard
= false;
7838 /* This may be the first time we heard about this process.
7839 Regardless, we must not do a global wildcard resume, otherwise
7840 we'd resume this process too. */
7841 *may_global_wildcard
= false;
7842 if (event
->ptid
!= null_ptid
)
7844 inferior
*inf
= find_inferior_ptid (this, event
->ptid
);
7846 get_remote_inferior (inf
)->may_wildcard_vcont
= false;
7851 /* Discard all pending stop replies of inferior INF. */
7854 remote_target::discard_pending_stop_replies (struct inferior
*inf
)
7856 struct remote_state
*rs
= get_remote_state ();
7857 struct remote_notif_state
*rns
= rs
->notif_state
;
7859 /* This function can be notified when an inferior exists. When the
7860 target is not remote, the notification state is NULL. */
7861 if (rs
->remote_desc
== NULL
)
7864 struct notif_event
*notif_event
7865 = rns
->pending_event
[notif_client_stop
.id
].get ();
7866 auto *reply
= static_cast<stop_reply
*> (notif_event
);
7868 /* Discard the in-flight notification. */
7869 if (reply
!= NULL
&& reply
->ptid
.pid () == inf
->pid
)
7871 /* Leave the notification pending, since the server expects that
7872 we acknowledge it with vStopped. But clear its contents, so
7873 that later on when we acknowledge it, we also discard it. */
7875 ("discarding in-flight notification: ptid: %s, ws: %s\n",
7876 reply
->ptid
.to_string().c_str(),
7877 reply
->ws
.to_string ().c_str ());
7878 reply
->ws
.set_ignore ();
7881 /* Discard the stop replies we have already pulled with
7883 auto iter
= std::remove_if (rs
->stop_reply_queue
.begin (),
7884 rs
->stop_reply_queue
.end (),
7885 [=] (const stop_reply_up
&event
)
7887 return event
->ptid
.pid () == inf
->pid
;
7889 for (auto it
= iter
; it
!= rs
->stop_reply_queue
.end (); ++it
)
7891 ("discarding queued stop reply: ptid: %s, ws: %s\n",
7892 (*it
)->ptid
.to_string().c_str(),
7893 (*it
)->ws
.to_string ().c_str ());
7894 rs
->stop_reply_queue
.erase (iter
, rs
->stop_reply_queue
.end ());
7897 /* Discard the stop replies for RS in stop_reply_queue. */
7900 remote_target::discard_pending_stop_replies_in_queue ()
7902 remote_state
*rs
= get_remote_state ();
7904 /* Discard the stop replies we have already pulled with
7906 auto iter
= std::remove_if (rs
->stop_reply_queue
.begin (),
7907 rs
->stop_reply_queue
.end (),
7908 [=] (const stop_reply_up
&event
)
7910 return event
->rs
== rs
;
7912 rs
->stop_reply_queue
.erase (iter
, rs
->stop_reply_queue
.end ());
7915 /* Remove the first reply in 'stop_reply_queue' which matches
7919 remote_target::remote_notif_remove_queued_reply (ptid_t ptid
)
7921 remote_state
*rs
= get_remote_state ();
7923 auto iter
= std::find_if (rs
->stop_reply_queue
.begin (),
7924 rs
->stop_reply_queue
.end (),
7925 [=] (const stop_reply_up
&event
)
7927 return event
->ptid
.matches (ptid
);
7929 stop_reply_up result
;
7930 if (iter
!= rs
->stop_reply_queue
.end ())
7932 result
= std::move (*iter
);
7933 rs
->stop_reply_queue
.erase (iter
);
7937 gdb_printf (gdb_stdlog
,
7938 "notif: discard queued event: 'Stop' in %s\n",
7939 ptid
.to_string ().c_str ());
7944 /* Look for a queued stop reply belonging to PTID. If one is found,
7945 remove it from the queue, and return it. Returns NULL if none is
7946 found. If there are still queued events left to process, tell the
7947 event loop to get back to target_wait soon. */
7950 remote_target::queued_stop_reply (ptid_t ptid
)
7952 remote_state
*rs
= get_remote_state ();
7953 stop_reply_up r
= remote_notif_remove_queued_reply (ptid
);
7955 if (!rs
->stop_reply_queue
.empty () && target_can_async_p ())
7957 /* There's still at least an event left. */
7958 rs
->mark_async_event_handler ();
7964 /* Push a fully parsed stop reply in the stop reply queue. Since we
7965 know that we now have at least one queued event left to pass to the
7966 core side, tell the event loop to get back to target_wait soon. */
7969 remote_target::push_stop_reply (stop_reply_up new_event
)
7971 remote_state
*rs
= get_remote_state ();
7972 rs
->stop_reply_queue
.push_back (std::move (new_event
));
7975 gdb_printf (gdb_stdlog
,
7976 "notif: push 'Stop' %s to queue %d\n",
7977 new_event
->ptid
.to_string ().c_str (),
7978 int (rs
->stop_reply_queue
.size ()));
7980 /* Mark the pending event queue only if async mode is currently enabled.
7981 If async mode is not currently enabled, then, if it later becomes
7982 enabled, and there are events in this queue, we will mark the event
7983 token at that point, see remote_target::async. */
7984 if (target_is_async_p ())
7985 rs
->mark_async_event_handler ();
7988 /* Returns true if we have a stop reply for PTID. */
7991 remote_target::peek_stop_reply (ptid_t ptid
)
7993 remote_state
*rs
= get_remote_state ();
7994 for (auto &event
: rs
->stop_reply_queue
)
7995 if (ptid
== event
->ptid
7996 && event
->ws
.kind () == TARGET_WAITKIND_STOPPED
)
8001 /* Helper for remote_parse_stop_reply. Return nonzero if the substring
8002 starting with P and ending with PEND matches PREFIX. */
8005 strprefix (const char *p
, const char *pend
, const char *prefix
)
8007 for ( ; p
< pend
; p
++, prefix
++)
8010 return *prefix
== '\0';
8013 /* Parse the stop reply in BUF. Either the function succeeds, and the
8014 result is stored in EVENT, or throws an error. */
8017 remote_target::remote_parse_stop_reply (const char *buf
, stop_reply
*event
)
8019 remote_arch_state
*rsa
= NULL
;
8024 event
->ptid
= null_ptid
;
8025 event
->rs
= get_remote_state ();
8026 event
->ws
.set_ignore ();
8027 event
->stop_reason
= TARGET_STOPPED_BY_NO_REASON
;
8028 event
->regcache
.clear ();
8033 case 'T': /* Status with PC, SP, FP, ... */
8034 /* Expedited reply, containing Signal, {regno, reg} repeat. */
8035 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
8037 n... = register number
8038 r... = register contents
8041 p
= &buf
[3]; /* after Txx */
8047 p1
= strchr (p
, ':');
8049 error (_("Malformed packet(a) (missing colon): %s\n\
8053 error (_("Malformed packet(a) (missing register number): %s\n\
8057 /* Some "registers" are actually extended stop information.
8058 Note if you're adding a new entry here: GDB 7.9 and
8059 earlier assume that all register "numbers" that start
8060 with an hex digit are real register numbers. Make sure
8061 the server only sends such a packet if it knows the
8062 client understands it. */
8064 if (strprefix (p
, p1
, "thread"))
8065 event
->ptid
= read_ptid (++p1
, &p
);
8066 else if (strprefix (p
, p1
, "syscall_entry"))
8070 p
= unpack_varlen_hex (++p1
, &sysno
);
8071 event
->ws
.set_syscall_entry ((int) sysno
);
8073 else if (strprefix (p
, p1
, "syscall_return"))
8077 p
= unpack_varlen_hex (++p1
, &sysno
);
8078 event
->ws
.set_syscall_return ((int) sysno
);
8080 else if (strprefix (p
, p1
, "watch")
8081 || strprefix (p
, p1
, "rwatch")
8082 || strprefix (p
, p1
, "awatch"))
8084 event
->stop_reason
= TARGET_STOPPED_BY_WATCHPOINT
;
8085 p
= unpack_varlen_hex (++p1
, &addr
);
8086 event
->watch_data_address
= (CORE_ADDR
) addr
;
8088 else if (strprefix (p
, p1
, "swbreak"))
8090 event
->stop_reason
= TARGET_STOPPED_BY_SW_BREAKPOINT
;
8092 /* Make sure the stub doesn't forget to indicate support
8094 if (m_features
.packet_support (PACKET_swbreak_feature
)
8096 error (_("Unexpected swbreak stop reason"));
8098 /* The value part is documented as "must be empty",
8099 though we ignore it, in case we ever decide to make
8100 use of it in a backward compatible way. */
8101 p
= strchrnul (p1
+ 1, ';');
8103 else if (strprefix (p
, p1
, "hwbreak"))
8105 event
->stop_reason
= TARGET_STOPPED_BY_HW_BREAKPOINT
;
8107 /* Make sure the stub doesn't forget to indicate support
8109 if (m_features
.packet_support (PACKET_hwbreak_feature
)
8111 error (_("Unexpected hwbreak stop reason"));
8114 p
= strchrnul (p1
+ 1, ';');
8116 else if (strprefix (p
, p1
, "library"))
8118 event
->ws
.set_loaded ();
8119 p
= strchrnul (p1
+ 1, ';');
8121 else if (strprefix (p
, p1
, "replaylog"))
8123 event
->ws
.set_no_history ();
8124 /* p1 will indicate "begin" or "end", but it makes
8125 no difference for now, so ignore it. */
8126 p
= strchrnul (p1
+ 1, ';');
8128 else if (strprefix (p
, p1
, "core"))
8132 p
= unpack_varlen_hex (++p1
, &c
);
8135 else if (strprefix (p
, p1
, "fork"))
8136 event
->ws
.set_forked (read_ptid (++p1
, &p
));
8137 else if (strprefix (p
, p1
, "vfork"))
8138 event
->ws
.set_vforked (read_ptid (++p1
, &p
));
8139 else if (strprefix (p
, p1
, "clone"))
8140 event
->ws
.set_thread_cloned (read_ptid (++p1
, &p
));
8141 else if (strprefix (p
, p1
, "vforkdone"))
8143 event
->ws
.set_vfork_done ();
8144 p
= strchrnul (p1
+ 1, ';');
8146 else if (strprefix (p
, p1
, "exec"))
8151 /* Determine the length of the execd pathname. */
8152 p
= unpack_varlen_hex (++p1
, &ignored
);
8153 pathlen
= (p
- p1
) / 2;
8155 /* Save the pathname for event reporting and for
8156 the next run command. */
8157 gdb::unique_xmalloc_ptr
<char> pathname
8158 ((char *) xmalloc (pathlen
+ 1));
8159 hex2bin (p1
, (gdb_byte
*) pathname
.get (), pathlen
);
8160 pathname
.get ()[pathlen
] = '\0';
8162 /* This is freed during event handling. */
8163 event
->ws
.set_execd (std::move (pathname
));
8165 /* Skip the registers included in this packet, since
8166 they may be for an architecture different from the
8167 one used by the original program. */
8170 else if (strprefix (p
, p1
, "create"))
8172 event
->ws
.set_thread_created ();
8173 p
= strchrnul (p1
+ 1, ';');
8182 p
= strchrnul (p1
+ 1, ';');
8187 /* Maybe a real ``P'' register number. */
8188 p_temp
= unpack_varlen_hex (p
, &pnum
);
8189 /* If the first invalid character is the colon, we got a
8190 register number. Otherwise, it's an unknown stop
8194 /* If we haven't parsed the event's thread yet, find
8195 it now, in order to find the architecture of the
8196 reported expedited registers. */
8197 if (event
->ptid
== null_ptid
)
8199 /* If there is no thread-id information then leave
8200 the event->ptid as null_ptid. Later in
8201 process_stop_reply we will pick a suitable
8203 const char *thr
= strstr (p1
+ 1, ";thread:");
8205 event
->ptid
= read_ptid (thr
+ strlen (";thread:"),
8212 = (event
->ptid
== null_ptid
8214 : find_inferior_ptid (this, event
->ptid
));
8215 /* If this is the first time we learn anything
8216 about this process, skip the registers
8217 included in this packet, since we don't yet
8218 know which architecture to use to parse them.
8219 We'll determine the architecture later when
8220 we process the stop reply and retrieve the
8221 target description, via
8222 remote_notice_new_inferior ->
8223 post_create_inferior. */
8226 p
= strchrnul (p1
+ 1, ';');
8231 event
->arch
= inf
->arch ();
8232 rsa
= event
->rs
->get_remote_arch_state (event
->arch
);
8236 = packet_reg_from_pnum (event
->arch
, rsa
, pnum
);
8237 cached_reg_t cached_reg
;
8240 error (_("Remote sent bad register number %s: %s\n\
8242 hex_string (pnum
), p
, buf
);
8244 int reg_size
= register_size (event
->arch
, reg
->regnum
);
8245 cached_reg
.num
= reg
->regnum
;
8246 cached_reg
.data
.resize (reg_size
);
8249 fieldsize
= hex2bin (p
, cached_reg
.data
.data (),
8250 cached_reg
.data
.size ());
8252 if (fieldsize
< reg_size
)
8253 warning (_("Remote reply is too short: %s"), buf
);
8255 event
->regcache
.push_back (std::move (cached_reg
));
8259 /* Not a number. Silently skip unknown optional
8261 p
= strchrnul (p1
+ 1, ';');
8266 error (_("Remote register badly formatted: %s\nhere: %s"),
8271 if (event
->ws
.kind () != TARGET_WAITKIND_IGNORE
)
8275 case 'S': /* Old style status, just signal only. */
8279 sig
= (fromhex (buf
[1]) << 4) + fromhex (buf
[2]);
8280 if (GDB_SIGNAL_FIRST
<= sig
&& sig
< GDB_SIGNAL_LAST
)
8281 event
->ws
.set_stopped ((enum gdb_signal
) sig
);
8283 event
->ws
.set_stopped (GDB_SIGNAL_UNKNOWN
);
8286 case 'w': /* Thread exited. */
8290 p
= unpack_varlen_hex (&buf
[1], &value
);
8291 event
->ws
.set_thread_exited (value
);
8293 error (_("stop reply packet badly formatted: %s"), buf
);
8294 event
->ptid
= read_ptid (++p
, NULL
);
8297 case 'W': /* Target exited. */
8302 /* GDB used to accept only 2 hex chars here. Stubs should
8303 only send more if they detect GDB supports multi-process
8305 p
= unpack_varlen_hex (&buf
[1], &value
);
8309 /* The remote process exited. */
8310 event
->ws
.set_exited (value
);
8314 /* The remote process exited with a signal. */
8315 if (GDB_SIGNAL_FIRST
<= value
&& value
< GDB_SIGNAL_LAST
)
8316 event
->ws
.set_signalled ((enum gdb_signal
) value
);
8318 event
->ws
.set_signalled (GDB_SIGNAL_UNKNOWN
);
8321 /* If no process is specified, return null_ptid, and let the
8322 caller figure out the right process to use. */
8332 else if (startswith (p
, "process:"))
8336 p
+= sizeof ("process:") - 1;
8337 unpack_varlen_hex (p
, &upid
);
8341 error (_("unknown stop reply packet: %s"), buf
);
8344 error (_("unknown stop reply packet: %s"), buf
);
8345 event
->ptid
= ptid_t (pid
);
8349 event
->ws
.set_no_resumed ();
8350 event
->ptid
= minus_one_ptid
;
8355 /* When the stub wants to tell GDB about a new notification reply, it
8356 sends a notification (%Stop, for example). Those can come it at
8357 any time, hence, we have to make sure that any pending
8358 putpkt/getpkt sequence we're making is finished, before querying
8359 the stub for more events with the corresponding ack command
8360 (vStopped, for example). E.g., if we started a vStopped sequence
8361 immediately upon receiving the notification, something like this
8369 1.6) <-- (registers reply to step #1.3)
8371 Obviously, the reply in step #1.6 would be unexpected to a vStopped
8374 To solve this, whenever we parse a %Stop notification successfully,
8375 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
8376 doing whatever we were doing:
8382 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
8383 2.5) <-- (registers reply to step #2.3)
8385 Eventually after step #2.5, we return to the event loop, which
8386 notices there's an event on the
8387 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
8388 associated callback --- the function below. At this point, we're
8389 always safe to start a vStopped sequence. :
8392 2.7) <-- T05 thread:2
8398 remote_target::remote_notif_get_pending_events (const notif_client
*nc
)
8400 struct remote_state
*rs
= get_remote_state ();
8402 if (rs
->notif_state
->pending_event
[nc
->id
] != NULL
)
8405 gdb_printf (gdb_stdlog
,
8406 "notif: process: '%s' ack pending event\n",
8410 nc
->ack (this, nc
, rs
->buf
.data (),
8411 std::move (rs
->notif_state
->pending_event
[nc
->id
]));
8416 if (strcmp (rs
->buf
.data (), "OK") == 0)
8419 remote_notif_ack (this, nc
, rs
->buf
.data ());
8425 gdb_printf (gdb_stdlog
,
8426 "notif: process: '%s' no pending reply\n",
8431 /* Wrapper around remote_target::remote_notif_get_pending_events to
8432 avoid having to export the whole remote_target class. */
8435 remote_notif_get_pending_events (remote_target
*remote
, const notif_client
*nc
)
8437 remote
->remote_notif_get_pending_events (nc
);
8440 /* Called from process_stop_reply when the stop packet we are responding
8441 to didn't include a process-id or thread-id. STATUS is the stop event
8442 we are responding to.
8444 It is the task of this function to select a suitable thread (or process)
8445 and return its ptid, this is the thread (or process) we will assume the
8446 stop event came from.
8448 In some cases there isn't really any choice about which thread (or
8449 process) is selected, a basic remote with a single process containing a
8450 single thread might choose not to send any process-id or thread-id in
8451 its stop packets, this function will select and return the one and only
8454 However, if a target supports multiple threads (or processes) and still
8455 doesn't include a thread-id (or process-id) in its stop packet then
8456 first, this is a badly behaving target, and second, we're going to have
8457 to select a thread (or process) at random and use that. This function
8458 will print a warning to the user if it detects that there is the
8459 possibility that GDB is guessing which thread (or process) to
8462 Note that this is called before GDB fetches the updated thread list from the
8463 target. So it's possible for the stop reply to be ambiguous and for GDB to
8464 not realize it. For example, if there's initially one thread, the target
8465 spawns a second thread, and then sends a stop reply without an id that
8466 concerns the first thread. GDB will assume the stop reply is about the
8467 first thread - the only thread it knows about - without printing a warning.
8468 Anyway, if the remote meant for the stop reply to be about the second thread,
8469 then it would be really broken, because GDB doesn't know about that thread
8473 remote_target::select_thread_for_ambiguous_stop_reply
8474 (const target_waitstatus
&status
)
8476 REMOTE_SCOPED_DEBUG_ENTER_EXIT
;
8478 /* Some stop events apply to all threads in an inferior, while others
8479 only apply to a single thread. */
8480 bool process_wide_stop
8481 = (status
.kind () == TARGET_WAITKIND_EXITED
8482 || status
.kind () == TARGET_WAITKIND_SIGNALLED
);
8484 remote_debug_printf ("process_wide_stop = %d", process_wide_stop
);
8486 thread_info
*first_resumed_thread
= nullptr;
8487 bool ambiguous
= false;
8489 /* Consider all non-exited threads of the target, find the first resumed
8491 for (thread_info
*thr
: all_non_exited_threads (this))
8493 remote_thread_info
*remote_thr
= get_remote_thread_info (thr
);
8495 if (remote_thr
->get_resume_state () != resume_state::RESUMED
)
8498 if (first_resumed_thread
== nullptr)
8499 first_resumed_thread
= thr
;
8500 else if (!process_wide_stop
8501 || first_resumed_thread
->ptid
.pid () != thr
->ptid
.pid ())
8505 gdb_assert (first_resumed_thread
!= nullptr);
8507 remote_debug_printf ("first resumed thread is %s",
8508 pid_to_str (first_resumed_thread
->ptid
).c_str ());
8509 remote_debug_printf ("is this guess ambiguous? = %d", ambiguous
);
8511 /* Warn if the remote target is sending ambiguous stop replies. */
8514 static bool warned
= false;
8518 /* If you are seeing this warning then the remote target has
8519 stopped without specifying a thread-id, but the target
8520 does have multiple threads (or inferiors), and so GDB is
8521 having to guess which thread stopped.
8523 Examples of what might cause this are the target sending
8524 and 'S' stop packet, or a 'T' stop packet and not
8525 including a thread-id.
8527 Additionally, the target might send a 'W' or 'X packet
8528 without including a process-id, when the target has
8529 multiple running inferiors. */
8530 if (process_wide_stop
)
8531 warning (_("multi-inferior target stopped without "
8532 "sending a process-id, using first "
8533 "non-exited inferior"));
8535 warning (_("multi-threaded target stopped without "
8536 "sending a thread-id, using first "
8537 "non-exited thread"));
8542 /* If this is a stop for all threads then don't use a particular threads
8543 ptid, instead create a new ptid where only the pid field is set. */
8544 if (process_wide_stop
)
8545 return ptid_t (first_resumed_thread
->ptid
.pid ());
8547 return first_resumed_thread
->ptid
;
8550 /* Called when it is decided that STOP_REPLY holds the info of the
8551 event that is to be returned to the core. This function always
8552 destroys STOP_REPLY. */
8555 remote_target::process_stop_reply (stop_reply_up stop_reply
,
8556 struct target_waitstatus
*status
)
8558 *status
= stop_reply
->ws
;
8559 ptid_t ptid
= stop_reply
->ptid
;
8560 struct remote_state
*rs
= get_remote_state ();
8562 /* Forget about last reply's expedited registers. */
8563 rs
->last_seen_expedited_registers
.clear ();
8565 /* If no thread/process was reported by the stub then select a suitable
8567 if (ptid
== null_ptid
)
8568 ptid
= select_thread_for_ambiguous_stop_reply (*status
);
8569 gdb_assert (ptid
!= null_ptid
);
8571 if (status
->kind () != TARGET_WAITKIND_EXITED
8572 && status
->kind () != TARGET_WAITKIND_SIGNALLED
8573 && status
->kind () != TARGET_WAITKIND_NO_RESUMED
)
8575 remote_notice_new_inferior (ptid
, false);
8577 /* Expedited registers. */
8578 if (!stop_reply
->regcache
.empty ())
8580 /* 'w' stop replies don't cary expedited registers (which
8581 wouldn't make any sense for a thread that is gone
8583 gdb_assert (status
->kind () != TARGET_WAITKIND_THREAD_EXITED
);
8586 = get_thread_arch_regcache (find_inferior_ptid (this, ptid
), ptid
,
8589 for (cached_reg_t
®
: stop_reply
->regcache
)
8591 regcache
->raw_supply (reg
.num
, reg
.data
);
8592 rs
->last_seen_expedited_registers
.insert (reg
.num
);
8596 remote_thread_info
*remote_thr
= get_remote_thread_info (this, ptid
);
8597 remote_thr
->core
= stop_reply
->core
;
8598 remote_thr
->stop_reason
= stop_reply
->stop_reason
;
8599 remote_thr
->watch_data_address
= stop_reply
->watch_data_address
;
8601 if (target_is_non_stop_p ())
8603 /* If the target works in non-stop mode, a stop-reply indicates that
8604 only this thread stopped. */
8605 remote_thr
->set_not_resumed ();
8609 /* If the target works in all-stop mode, a stop-reply indicates that
8610 all the target's threads stopped. */
8611 for (thread_info
*tp
: all_non_exited_threads (this))
8612 get_remote_thread_info (tp
)->set_not_resumed ();
8619 /* The non-stop mode version of target_wait. */
8622 remote_target::wait_ns (ptid_t ptid
, struct target_waitstatus
*status
,
8623 target_wait_flags options
)
8625 struct remote_state
*rs
= get_remote_state ();
8627 bool is_notif
= false;
8629 /* If in non-stop mode, get out of getpkt even if a
8630 notification is received. */
8632 ret
= getpkt (&rs
->buf
, false /* forever */, &is_notif
);
8635 if (ret
!= -1 && !is_notif
)
8638 case 'E': /* Error of some sort. */
8639 /* We're out of sync with the target now. Did it continue
8640 or not? We can't tell which thread it was in non-stop,
8641 so just ignore this. */
8642 warning (_("Remote failure reply: %s"), rs
->buf
.data ());
8644 case 'O': /* Console output. */
8645 remote_console_output (&rs
->buf
[1], gdb_stdtarg
);
8648 warning (_("Invalid remote reply: %s"), rs
->buf
.data ());
8652 /* Acknowledge a pending stop reply that may have arrived in the
8654 if (rs
->notif_state
->pending_event
[notif_client_stop
.id
] != NULL
)
8655 remote_notif_get_pending_events (¬if_client_stop
);
8657 /* If indeed we noticed a stop reply, we're done. */
8658 stop_reply_up stop_reply
= queued_stop_reply (ptid
);
8659 if (stop_reply
!= NULL
)
8660 return process_stop_reply (std::move (stop_reply
), status
);
8662 /* Still no event. If we're just polling for an event, then
8663 return to the event loop. */
8664 if (options
& TARGET_WNOHANG
)
8666 status
->set_ignore ();
8667 return minus_one_ptid
;
8670 /* Otherwise do a blocking wait. */
8671 ret
= getpkt (&rs
->buf
, true /* forever */, &is_notif
);
8675 /* Return the first resumed thread. */
8678 first_remote_resumed_thread (remote_target
*target
)
8680 for (thread_info
*tp
: all_non_exited_threads (target
, minus_one_ptid
))
8686 /* Wait until the remote machine stops, then return, storing status in
8687 STATUS just as `wait' would. */
8690 remote_target::wait_as (ptid_t ptid
, target_waitstatus
*status
,
8691 target_wait_flags options
)
8693 struct remote_state
*rs
= get_remote_state ();
8694 ptid_t event_ptid
= null_ptid
;
8696 stop_reply_up stop_reply
;
8700 status
->set_ignore ();
8702 stop_reply
= queued_stop_reply (ptid
);
8703 if (stop_reply
!= NULL
)
8705 /* None of the paths that push a stop reply onto the queue should
8706 have set the waiting_for_stop_reply flag. */
8707 gdb_assert (!rs
->waiting_for_stop_reply
);
8708 event_ptid
= process_stop_reply (std::move (stop_reply
), status
);
8712 bool forever
= ((options
& TARGET_WNOHANG
) == 0
8713 && rs
->wait_forever_enabled_p
);
8715 if (!rs
->waiting_for_stop_reply
)
8717 status
->set_no_resumed ();
8718 return minus_one_ptid
;
8721 /* FIXME: cagney/1999-09-27: If we're in async mode we should
8722 _never_ wait for ever -> test on target_is_async_p().
8723 However, before we do that we need to ensure that the caller
8724 knows how to take the target into/out of async mode. */
8726 int ret
= getpkt (&rs
->buf
, forever
, &is_notif
);
8728 /* GDB gets a notification. Return to core as this event is
8730 if (ret
!= -1 && is_notif
)
8731 return minus_one_ptid
;
8733 if (ret
== -1 && (options
& TARGET_WNOHANG
) != 0)
8734 return minus_one_ptid
;
8736 buf
= rs
->buf
.data ();
8738 /* Assume that the target has acknowledged Ctrl-C unless we receive
8739 an 'F' or 'O' packet. */
8740 if (buf
[0] != 'F' && buf
[0] != 'O')
8741 rs
->ctrlc_pending_p
= 0;
8745 case 'E': /* Error of some sort. */
8746 /* We're out of sync with the target now. Did it continue or
8747 not? Not is more likely, so report a stop. */
8748 rs
->waiting_for_stop_reply
= 0;
8750 warning (_("Remote failure reply: %s"), buf
);
8751 status
->set_stopped (GDB_SIGNAL_0
);
8753 case 'F': /* File-I/O request. */
8754 /* GDB may access the inferior memory while handling the File-I/O
8755 request, but we don't want GDB accessing memory while waiting
8756 for a stop reply. See the comments in putpkt_binary. Set
8757 waiting_for_stop_reply to 0 temporarily. */
8758 rs
->waiting_for_stop_reply
= 0;
8759 remote_fileio_request (this, buf
, rs
->ctrlc_pending_p
);
8760 rs
->ctrlc_pending_p
= 0;
8761 /* GDB handled the File-I/O request, and the target is running
8762 again. Keep waiting for events. */
8763 rs
->waiting_for_stop_reply
= 1;
8765 case 'N': case 'T': case 'S': case 'X': case 'W': case 'w':
8767 /* There is a stop reply to handle. */
8768 rs
->waiting_for_stop_reply
= 0;
8771 = as_stop_reply_up (remote_notif_parse (this,
8775 event_ptid
= process_stop_reply (std::move (stop_reply
), status
);
8778 case 'O': /* Console output. */
8779 remote_console_output (buf
+ 1, gdb_stdtarg
);
8782 if (rs
->last_sent_signal
!= GDB_SIGNAL_0
)
8784 /* Zero length reply means that we tried 'S' or 'C' and the
8785 remote system doesn't support it. */
8786 target_terminal::ours_for_output ();
8788 ("Can't send signals to this remote system. %s not sent.\n",
8789 gdb_signal_to_name (rs
->last_sent_signal
));
8790 rs
->last_sent_signal
= GDB_SIGNAL_0
;
8791 target_terminal::inferior ();
8793 strcpy (buf
, rs
->last_sent_step
? "s" : "c");
8799 warning (_("Invalid remote reply: %s"), buf
);
8804 if (status
->kind () == TARGET_WAITKIND_NO_RESUMED
)
8805 return minus_one_ptid
;
8806 else if (status
->kind () == TARGET_WAITKIND_IGNORE
)
8808 /* Nothing interesting happened. If we're doing a non-blocking
8809 poll, we're done. Otherwise, go back to waiting. */
8810 if (options
& TARGET_WNOHANG
)
8811 return minus_one_ptid
;
8815 else if (status
->kind () != TARGET_WAITKIND_EXITED
8816 && status
->kind () != TARGET_WAITKIND_SIGNALLED
)
8818 if (event_ptid
!= null_ptid
)
8819 record_currthread (rs
, event_ptid
);
8821 event_ptid
= first_remote_resumed_thread (this);
8825 /* A process exit. Invalidate our notion of current thread. */
8826 record_currthread (rs
, minus_one_ptid
);
8827 /* It's possible that the packet did not include a pid. */
8828 if (event_ptid
== null_ptid
)
8829 event_ptid
= first_remote_resumed_thread (this);
8830 /* EVENT_PTID could still be NULL_PTID. Double-check. */
8831 if (event_ptid
== null_ptid
)
8832 event_ptid
= magic_null_ptid
;
8838 /* Wait until the remote machine stops, then return, storing status in
8839 STATUS just as `wait' would. */
8842 remote_target::wait (ptid_t ptid
, struct target_waitstatus
*status
,
8843 target_wait_flags options
)
8845 REMOTE_SCOPED_DEBUG_ENTER_EXIT
;
8847 remote_state
*rs
= get_remote_state ();
8849 /* Start by clearing the flag that asks for our wait method to be called,
8850 we'll mark it again at the end if needed. If the target is not in
8851 async mode then the async token should not be marked. */
8852 if (target_is_async_p ())
8853 rs
->clear_async_event_handler ();
8855 gdb_assert (!rs
->async_event_handler_marked ());
8859 if (target_is_non_stop_p ())
8860 event_ptid
= wait_ns (ptid
, status
, options
);
8862 event_ptid
= wait_as (ptid
, status
, options
);
8864 if (target_is_async_p ())
8866 /* If there are events left in the queue, or unacknowledged
8867 notifications, then tell the event loop to call us again. */
8868 if (!rs
->stop_reply_queue
.empty ()
8869 || rs
->notif_state
->pending_event
[notif_client_stop
.id
] != nullptr)
8870 rs
->mark_async_event_handler ();
8876 /* Fetch a single register using a 'p' packet. */
8879 remote_target::fetch_register_using_p (struct regcache
*regcache
,
8882 struct gdbarch
*gdbarch
= regcache
->arch ();
8883 struct remote_state
*rs
= get_remote_state ();
8885 gdb_byte
*regp
= (gdb_byte
*) alloca (register_size (gdbarch
, reg
->regnum
));
8888 if (m_features
.packet_support (PACKET_p
) == PACKET_DISABLE
)
8891 if (reg
->pnum
== -1)
8894 p
= rs
->buf
.data ();
8896 p
+= hexnumstr (p
, reg
->pnum
);
8901 buf
= rs
->buf
.data ();
8903 packet_result result
= m_features
.packet_ok (rs
->buf
, PACKET_p
);
8904 switch (result
.status ())
8908 case PACKET_UNKNOWN
:
8911 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
8912 gdbarch_register_name (regcache
->arch (), reg
->regnum
),
8916 /* If this register is unfetchable, tell the regcache. */
8919 regcache
->raw_supply (reg
->regnum
, NULL
);
8923 /* Otherwise, parse and supply the value. */
8929 error (_("fetch_register_using_p: early buf termination"));
8931 regp
[i
++] = fromhex (p
[0]) * 16 + fromhex (p
[1]);
8934 regcache
->raw_supply (reg
->regnum
, regp
);
8938 /* Fetch the registers included in the target's 'g' packet. */
8941 remote_target::send_g_packet ()
8943 struct remote_state
*rs
= get_remote_state ();
8946 xsnprintf (rs
->buf
.data (), get_remote_packet_size (), "g");
8949 packet_result result
= packet_check_result (rs
->buf
);
8950 if (result
.status () == PACKET_ERROR
)
8951 error (_("Could not read registers; remote failure reply '%s'"),
8954 /* We can get out of synch in various cases. If the first character
8955 in the buffer is not a hex character, assume that has happened
8956 and try to fetch another packet to read. */
8957 while ((rs
->buf
[0] < '0' || rs
->buf
[0] > '9')
8958 && (rs
->buf
[0] < 'A' || rs
->buf
[0] > 'F')
8959 && (rs
->buf
[0] < 'a' || rs
->buf
[0] > 'f')
8960 && rs
->buf
[0] != 'x') /* New: unavailable register value. */
8962 remote_debug_printf ("Bad register packet; fetching a new packet");
8966 buf_len
= strlen (rs
->buf
.data ());
8968 /* Sanity check the received packet. */
8969 if (buf_len
% 2 != 0)
8970 error (_("Remote 'g' packet reply is of odd length: %s"), rs
->buf
.data ());
8976 remote_target::process_g_packet (struct regcache
*regcache
)
8978 struct gdbarch
*gdbarch
= regcache
->arch ();
8979 struct remote_state
*rs
= get_remote_state ();
8980 remote_arch_state
*rsa
= rs
->get_remote_arch_state (gdbarch
);
8985 buf_len
= strlen (rs
->buf
.data ());
8987 /* Further sanity checks, with knowledge of the architecture. */
8988 if (buf_len
> 2 * rsa
->sizeof_g_packet
)
8989 error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
8991 rsa
->sizeof_g_packet
, buf_len
/ 2,
8994 /* Save the size of the packet sent to us by the target. It is used
8995 as a heuristic when determining the max size of packets that the
8996 target can safely receive. */
8997 if (rsa
->actual_register_packet_size
== 0)
8998 rsa
->actual_register_packet_size
= buf_len
;
9000 /* If this is smaller than we guessed the 'g' packet would be,
9001 update our records. A 'g' reply that doesn't include a register's
9002 value implies either that the register is not available, or that
9003 the 'p' packet must be used. */
9004 if (buf_len
< 2 * rsa
->sizeof_g_packet
)
9006 long sizeof_g_packet
= buf_len
/ 2;
9008 for (i
= 0; i
< gdbarch_num_regs (gdbarch
); i
++)
9010 long offset
= rsa
->regs
[i
].offset
;
9011 long reg_size
= register_size (gdbarch
, i
);
9013 if (rsa
->regs
[i
].pnum
== -1)
9016 if (offset
>= sizeof_g_packet
)
9017 rsa
->regs
[i
].in_g_packet
= false;
9018 else if (offset
+ reg_size
> sizeof_g_packet
)
9019 error (_("Truncated register %d in remote 'g' packet"), i
);
9021 rsa
->regs
[i
].in_g_packet
= true;
9024 /* Looks valid enough, we can assume this is the correct length
9025 for a 'g' packet. It's important not to adjust
9026 rsa->sizeof_g_packet if we have truncated registers otherwise
9027 this "if" won't be run the next time the method is called
9028 with a packet of the same size and one of the internal errors
9029 below will trigger instead. */
9030 rsa
->sizeof_g_packet
= sizeof_g_packet
;
9033 regs
= (char *) alloca (rsa
->sizeof_g_packet
);
9035 /* Unimplemented registers read as all bits zero. */
9036 memset (regs
, 0, rsa
->sizeof_g_packet
);
9038 /* Reply describes registers byte by byte, each byte encoded as two
9039 hex characters. Suck them all up, then supply them to the
9040 register caching/storage mechanism. */
9042 p
= rs
->buf
.data ();
9043 for (i
= 0; i
< rsa
->sizeof_g_packet
; i
++)
9045 if (p
[0] == 0 || p
[1] == 0)
9046 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
9047 internal_error (_("unexpected end of 'g' packet reply"));
9049 if (p
[0] == 'x' && p
[1] == 'x')
9050 regs
[i
] = 0; /* 'x' */
9052 regs
[i
] = fromhex (p
[0]) * 16 + fromhex (p
[1]);
9056 for (i
= 0; i
< gdbarch_num_regs (gdbarch
); i
++)
9058 struct packet_reg
*r
= &rsa
->regs
[i
];
9059 long reg_size
= register_size (gdbarch
, i
);
9063 if ((r
->offset
+ reg_size
) * 2 > strlen (rs
->buf
.data ()))
9064 /* This shouldn't happen - we adjusted in_g_packet above. */
9065 internal_error (_("unexpected end of 'g' packet reply"));
9066 else if (rs
->buf
[r
->offset
* 2] == 'x')
9068 gdb_assert (r
->offset
* 2 < strlen (rs
->buf
.data ()));
9069 /* The register isn't available, mark it as such (at
9070 the same time setting the value to zero). */
9071 regcache
->raw_supply (r
->regnum
, NULL
);
9074 regcache
->raw_supply (r
->regnum
, regs
+ r
->offset
);
9080 remote_target::fetch_registers_using_g (struct regcache
*regcache
)
9083 process_g_packet (regcache
);
9086 /* Make the remote selected traceframe match GDB's selected
9090 remote_target::set_remote_traceframe ()
9093 struct remote_state
*rs
= get_remote_state ();
9095 if (rs
->remote_traceframe_number
== get_traceframe_number ())
9098 /* Avoid recursion, remote_trace_find calls us again. */
9099 rs
->remote_traceframe_number
= get_traceframe_number ();
9101 newnum
= target_trace_find (tfind_number
,
9102 get_traceframe_number (), 0, 0, NULL
);
9104 /* Should not happen. If it does, all bets are off. */
9105 if (newnum
!= get_traceframe_number ())
9106 warning (_("could not set remote traceframe"));
9110 remote_target::fetch_registers (struct regcache
*regcache
, int regnum
)
9112 struct gdbarch
*gdbarch
= regcache
->arch ();
9113 struct remote_state
*rs
= get_remote_state ();
9114 remote_arch_state
*rsa
= rs
->get_remote_arch_state (gdbarch
);
9117 set_remote_traceframe ();
9118 set_general_thread (regcache
->ptid ());
9122 packet_reg
*reg
= packet_reg_from_regnum (gdbarch
, rsa
, regnum
);
9124 gdb_assert (reg
!= NULL
);
9126 /* If this register might be in the 'g' packet, try that first -
9127 we are likely to read more than one register. If this is the
9128 first 'g' packet, we might be overly optimistic about its
9129 contents, so fall back to 'p'. */
9130 if (reg
->in_g_packet
)
9132 fetch_registers_using_g (regcache
);
9133 if (reg
->in_g_packet
)
9137 if (fetch_register_using_p (regcache
, reg
))
9140 /* This register is not available. */
9141 regcache
->raw_supply (reg
->regnum
, NULL
);
9146 fetch_registers_using_g (regcache
);
9148 for (i
= 0; i
< gdbarch_num_regs (gdbarch
); i
++)
9149 if (!rsa
->regs
[i
].in_g_packet
)
9150 if (!fetch_register_using_p (regcache
, &rsa
->regs
[i
]))
9152 /* This register is not available. */
9153 regcache
->raw_supply (i
, NULL
);
9157 /* Prepare to store registers. Since we may send them all (using a
9158 'G' request), we have to read out the ones we don't want to change
9162 remote_target::prepare_to_store (struct regcache
*regcache
)
9164 struct remote_state
*rs
= get_remote_state ();
9165 remote_arch_state
*rsa
= rs
->get_remote_arch_state (regcache
->arch ());
9168 /* Make sure the entire registers array is valid. */
9169 switch (m_features
.packet_support (PACKET_P
))
9171 case PACKET_DISABLE
:
9172 case PACKET_SUPPORT_UNKNOWN
:
9173 /* Make sure all the necessary registers are cached. */
9174 for (i
= 0; i
< gdbarch_num_regs (regcache
->arch ()); i
++)
9175 if (rsa
->regs
[i
].in_g_packet
)
9176 regcache
->raw_update (rsa
->regs
[i
].regnum
);
9183 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
9184 packet was not recognized. */
9187 remote_target::store_register_using_P (const struct regcache
*regcache
,
9190 struct gdbarch
*gdbarch
= regcache
->arch ();
9191 struct remote_state
*rs
= get_remote_state ();
9192 /* Try storing a single register. */
9193 char *buf
= rs
->buf
.data ();
9194 gdb_byte
*regp
= (gdb_byte
*) alloca (register_size (gdbarch
, reg
->regnum
));
9197 if (m_features
.packet_support (PACKET_P
) == PACKET_DISABLE
)
9200 if (reg
->pnum
== -1)
9203 xsnprintf (buf
, get_remote_packet_size (), "P%s=", phex_nz (reg
->pnum
, 0));
9204 p
= buf
+ strlen (buf
);
9205 regcache
->raw_collect (reg
->regnum
, regp
);
9206 bin2hex (regp
, p
, register_size (gdbarch
, reg
->regnum
));
9210 packet_result result
= m_features
.packet_ok (rs
->buf
, PACKET_P
);
9211 switch (result
.status ())
9216 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
9217 gdbarch_register_name (gdbarch
, reg
->regnum
), result
.err_msg ());
9218 case PACKET_UNKNOWN
:
9221 internal_error (_("Bad result from packet_ok"));
9225 /* Store register REGNUM, or all registers if REGNUM == -1, from the
9226 contents of the register cache buffer. FIXME: ignores errors. */
9229 remote_target::store_registers_using_G (const struct regcache
*regcache
)
9231 struct remote_state
*rs
= get_remote_state ();
9232 remote_arch_state
*rsa
= rs
->get_remote_arch_state (regcache
->arch ());
9236 /* Extract all the registers in the regcache copying them into a
9241 regs
= (gdb_byte
*) alloca (rsa
->sizeof_g_packet
);
9242 memset (regs
, 0, rsa
->sizeof_g_packet
);
9243 for (i
= 0; i
< gdbarch_num_regs (regcache
->arch ()); i
++)
9245 struct packet_reg
*r
= &rsa
->regs
[i
];
9248 regcache
->raw_collect (r
->regnum
, regs
+ r
->offset
);
9252 /* Command describes registers byte by byte,
9253 each byte encoded as two hex characters. */
9254 p
= rs
->buf
.data ();
9256 bin2hex (regs
, p
, rsa
->sizeof_g_packet
);
9259 packet_result pkt_status
= packet_check_result (rs
->buf
);
9260 if (pkt_status
.status () == PACKET_ERROR
)
9261 error (_("Could not write registers; remote failure reply '%s'"),
9262 pkt_status
.err_msg ());
9265 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
9266 of the register cache buffer. FIXME: ignores errors. */
9269 remote_target::store_registers (struct regcache
*regcache
, int regnum
)
9271 struct gdbarch
*gdbarch
= regcache
->arch ();
9272 struct remote_state
*rs
= get_remote_state ();
9273 remote_arch_state
*rsa
= rs
->get_remote_arch_state (gdbarch
);
9276 set_remote_traceframe ();
9277 set_general_thread (regcache
->ptid ());
9281 packet_reg
*reg
= packet_reg_from_regnum (gdbarch
, rsa
, regnum
);
9283 gdb_assert (reg
!= NULL
);
9285 /* Always prefer to store registers using the 'P' packet if
9286 possible; we often change only a small number of registers.
9287 Sometimes we change a larger number; we'd need help from a
9288 higher layer to know to use 'G'. */
9289 if (store_register_using_P (regcache
, reg
))
9292 /* For now, don't complain if we have no way to write the
9293 register. GDB loses track of unavailable registers too
9294 easily. Some day, this may be an error. We don't have
9295 any way to read the register, either... */
9296 if (!reg
->in_g_packet
)
9299 store_registers_using_G (regcache
);
9303 store_registers_using_G (regcache
);
9305 for (i
= 0; i
< gdbarch_num_regs (gdbarch
); i
++)
9306 if (!rsa
->regs
[i
].in_g_packet
)
9307 if (!store_register_using_P (regcache
, &rsa
->regs
[i
]))
9308 /* See above for why we do not issue an error here. */
9313 /* Return the number of hex digits in num. */
9316 hexnumlen (ULONGEST num
)
9320 for (i
= 0; num
!= 0; i
++)
9323 return std::max (i
, 1);
9326 /* Set BUF to the minimum number of hex digits representing NUM. */
9329 hexnumstr (char *buf
, ULONGEST num
)
9331 int len
= hexnumlen (num
);
9333 return hexnumnstr (buf
, num
, len
);
9337 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
9340 hexnumnstr (char *buf
, ULONGEST num
, int width
)
9346 for (i
= width
- 1; i
>= 0; i
--)
9348 buf
[i
] = "0123456789abcdef"[(num
& 0xf)];
9355 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
9358 remote_address_masked (CORE_ADDR addr
)
9360 unsigned int address_size
= remote_address_size
;
9362 /* If "remoteaddresssize" was not set, default to target address size. */
9364 address_size
= gdbarch_addr_bit (current_inferior ()->arch ());
9366 if (address_size
> 0
9367 && address_size
< (sizeof (ULONGEST
) * 8))
9369 /* Only create a mask when that mask can safely be constructed
9370 in a ULONGEST variable. */
9373 mask
= (mask
<< address_size
) - 1;
9379 /* Determine whether the remote target supports binary downloading.
9380 This is accomplished by sending a no-op memory write of zero length
9381 to the target at the specified address. It does not suffice to send
9382 the whole packet, since many stubs strip the eighth bit and
9383 subsequently compute a wrong checksum, which causes real havoc with
9386 NOTE: This can still lose if the serial line is not eight-bit
9387 clean. In cases like this, the user should clear "remote
9391 remote_target::check_binary_download (CORE_ADDR addr
)
9393 struct remote_state
*rs
= get_remote_state ();
9395 switch (m_features
.packet_support (PACKET_X
))
9397 case PACKET_DISABLE
:
9401 case PACKET_SUPPORT_UNKNOWN
:
9405 p
= rs
->buf
.data ();
9407 p
+= hexnumstr (p
, (ULONGEST
) addr
);
9409 p
+= hexnumstr (p
, (ULONGEST
) 0);
9413 putpkt_binary (rs
->buf
.data (), (int) (p
- rs
->buf
.data ()));
9416 if (rs
->buf
[0] == '\0')
9418 remote_debug_printf ("binary downloading NOT supported by target");
9419 m_features
.m_protocol_packets
[PACKET_X
].support
= PACKET_DISABLE
;
9423 remote_debug_printf ("binary downloading supported by target");
9424 m_features
.m_protocol_packets
[PACKET_X
].support
= PACKET_ENABLE
;
9431 /* Helper function to resize the payload in order to try to get a good
9432 alignment. We try to write an amount of data such that the next write will
9433 start on an address aligned on REMOTE_ALIGN_WRITES. */
9436 align_for_efficient_write (int todo
, CORE_ADDR memaddr
)
9438 return ((memaddr
+ todo
) & ~(REMOTE_ALIGN_WRITES
- 1)) - memaddr
;
9441 /* Write memory data directly to the remote machine.
9442 This does not inform the data cache; the data cache uses this.
9443 HEADER is the starting part of the packet.
9444 MEMADDR is the address in the remote memory space.
9445 MYADDR is the address of the buffer in our space.
9446 LEN_UNITS is the number of addressable units to write.
9447 UNIT_SIZE is the length in bytes of an addressable unit.
9448 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
9449 should send data as binary ('X'), or hex-encoded ('M').
9451 The function creates packet of the form
9452 <HEADER><ADDRESS>,<LENGTH>:<DATA>
9454 where encoding of <DATA> is terminated by PACKET_FORMAT.
9456 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
9459 Return the transferred status, error or OK (an
9460 'enum target_xfer_status' value). Save the number of addressable units
9461 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
9463 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
9464 exchange between gdb and the stub could look like (?? in place of the
9470 -> $M1000,3:eeeeffffeeee#??
9474 <- eeeeffffeeeedddd */
9477 remote_target::remote_write_bytes_aux (const char *header
, CORE_ADDR memaddr
,
9478 const gdb_byte
*myaddr
,
9481 ULONGEST
*xfered_len_units
,
9482 char packet_format
, int use_length
)
9484 struct remote_state
*rs
= get_remote_state ();
9490 int payload_capacity_bytes
;
9491 int payload_length_bytes
;
9493 if (packet_format
!= 'X' && packet_format
!= 'M')
9494 internal_error (_("remote_write_bytes_aux: bad packet format"));
9497 return TARGET_XFER_EOF
;
9499 payload_capacity_bytes
= get_memory_write_packet_size ();
9501 /* The packet buffer will be large enough for the payload;
9502 get_memory_packet_size ensures this. */
9505 /* Compute the size of the actual payload by subtracting out the
9506 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
9508 payload_capacity_bytes
-= strlen ("$,:#NN");
9510 /* The comma won't be used. */
9511 payload_capacity_bytes
+= 1;
9512 payload_capacity_bytes
-= strlen (header
);
9513 payload_capacity_bytes
-= hexnumlen (memaddr
);
9515 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
9517 strcat (rs
->buf
.data (), header
);
9518 p
= rs
->buf
.data () + strlen (header
);
9520 /* Compute a best guess of the number of bytes actually transferred. */
9521 if (packet_format
== 'X')
9523 /* Best guess at number of bytes that will fit. */
9524 todo_units
= std::min (len_units
,
9525 (ULONGEST
) payload_capacity_bytes
/ unit_size
);
9527 payload_capacity_bytes
-= hexnumlen (todo_units
);
9528 todo_units
= std::min (todo_units
, payload_capacity_bytes
/ unit_size
);
9532 /* Number of bytes that will fit. */
9534 = std::min (len_units
,
9535 (ULONGEST
) (payload_capacity_bytes
/ unit_size
) / 2);
9537 payload_capacity_bytes
-= hexnumlen (todo_units
);
9538 todo_units
= std::min (todo_units
,
9539 (payload_capacity_bytes
/ unit_size
) / 2);
9542 if (todo_units
<= 0)
9543 internal_error (_("minimum packet size too small to write data"));
9545 /* If we already need another packet, then try to align the end
9546 of this packet to a useful boundary. */
9547 if (todo_units
> 2 * REMOTE_ALIGN_WRITES
&& todo_units
< len_units
)
9548 todo_units
= align_for_efficient_write (todo_units
, memaddr
);
9550 /* Append "<memaddr>". */
9551 memaddr
= remote_address_masked (memaddr
);
9552 p
+= hexnumstr (p
, (ULONGEST
) memaddr
);
9559 /* Append the length and retain its location and size. It may need to be
9560 adjusted once the packet body has been created. */
9562 plenlen
= hexnumstr (p
, (ULONGEST
) todo_units
);
9570 /* Append the packet body. */
9571 if (packet_format
== 'X')
9573 /* Binary mode. Send target system values byte by byte, in
9574 increasing byte addresses. Only escape certain critical
9576 payload_length_bytes
=
9577 remote_escape_output (myaddr
, todo_units
, unit_size
, (gdb_byte
*) p
,
9578 &units_written
, payload_capacity_bytes
);
9580 /* If not all TODO units fit, then we'll need another packet. Make
9581 a second try to keep the end of the packet aligned. Don't do
9582 this if the packet is tiny. */
9583 if (units_written
< todo_units
&& units_written
> 2 * REMOTE_ALIGN_WRITES
)
9587 new_todo_units
= align_for_efficient_write (units_written
, memaddr
);
9589 if (new_todo_units
!= units_written
)
9590 payload_length_bytes
=
9591 remote_escape_output (myaddr
, new_todo_units
, unit_size
,
9592 (gdb_byte
*) p
, &units_written
,
9593 payload_capacity_bytes
);
9596 p
+= payload_length_bytes
;
9597 if (use_length
&& units_written
< todo_units
)
9599 /* Escape chars have filled up the buffer prematurely,
9600 and we have actually sent fewer units than planned.
9601 Fix-up the length field of the packet. Use the same
9602 number of characters as before. */
9603 plen
+= hexnumnstr (plen
, (ULONGEST
) units_written
,
9605 *plen
= ':'; /* overwrite \0 from hexnumnstr() */
9610 /* Normal mode: Send target system values byte by byte, in
9611 increasing byte addresses. Each byte is encoded as a two hex
9613 p
+= 2 * bin2hex (myaddr
, p
, todo_units
* unit_size
);
9614 units_written
= todo_units
;
9617 putpkt_binary (rs
->buf
.data (), (int) (p
- rs
->buf
.data ()));
9620 if (rs
->buf
[0] == 'E')
9621 return TARGET_XFER_E_IO
;
9623 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
9624 send fewer units than we'd planned. */
9625 *xfered_len_units
= (ULONGEST
) units_written
;
9626 return (*xfered_len_units
!= 0) ? TARGET_XFER_OK
: TARGET_XFER_EOF
;
9629 /* Write memory data directly to the remote machine.
9630 This does not inform the data cache; the data cache uses this.
9631 MEMADDR is the address in the remote memory space.
9632 MYADDR is the address of the buffer in our space.
9633 LEN is the number of bytes.
9635 Return the transferred status, error or OK (an
9636 'enum target_xfer_status' value). Save the number of bytes
9637 transferred in *XFERED_LEN. Only transfer a single packet. */
9640 remote_target::remote_write_bytes (CORE_ADDR memaddr
, const gdb_byte
*myaddr
,
9641 ULONGEST len
, int unit_size
,
9642 ULONGEST
*xfered_len
)
9644 const char *packet_format
= NULL
;
9646 /* Check whether the target supports binary download. */
9647 check_binary_download (memaddr
);
9649 switch (m_features
.packet_support (PACKET_X
))
9652 packet_format
= "X";
9654 case PACKET_DISABLE
:
9655 packet_format
= "M";
9657 case PACKET_SUPPORT_UNKNOWN
:
9658 internal_error (_("remote_write_bytes: bad internal state"));
9660 internal_error (_("bad switch"));
9663 return remote_write_bytes_aux (packet_format
,
9664 memaddr
, myaddr
, len
, unit_size
, xfered_len
,
9665 packet_format
[0], 1);
9668 /* Read memory data directly from the remote machine.
9669 This does not use the data cache; the data cache uses this.
9670 MEMADDR is the address in the remote memory space.
9671 MYADDR is the address of the buffer in our space.
9672 LEN_UNITS is the number of addressable memory units to read..
9673 UNIT_SIZE is the length in bytes of an addressable unit.
9675 Return the transferred status, error or OK (an
9676 'enum target_xfer_status' value). Save the number of bytes
9677 transferred in *XFERED_LEN_UNITS.
9679 See the comment of remote_write_bytes_aux for an example of
9680 memory read/write exchange between gdb and the stub. */
9683 remote_target::remote_read_bytes_1 (CORE_ADDR memaddr
, gdb_byte
*myaddr
,
9685 int unit_size
, ULONGEST
*xfered_len_units
)
9687 struct remote_state
*rs
= get_remote_state ();
9688 int buf_size_bytes
; /* Max size of packet output buffer. */
9692 buf_size_bytes
= get_memory_read_packet_size ();
9693 /* The packet buffer will be large enough for the payload;
9694 get_memory_packet_size ensures this. */
9696 /* Number of units that will fit. */
9697 todo_units
= std::min (len_units
,
9698 (ULONGEST
) (buf_size_bytes
/ unit_size
) / 2);
9700 memaddr
= remote_address_masked (memaddr
);
9702 /* Construct "m/x"<memaddr>","<len>". */
9703 auto send_request
= [this, rs
, memaddr
, todo_units
] (char format
) -> void
9705 char *buffer
= rs
->buf
.data ();
9707 buffer
+= hexnumstr (buffer
, (ULONGEST
) memaddr
);
9709 buffer
+= hexnumstr (buffer
, (ULONGEST
) todo_units
);
9714 /* Determine which packet format to use. The target's support for
9715 'x' may be unknown. We just try. If it doesn't work, we try
9718 if (m_features
.packet_support (PACKET_x
) == PACKET_DISABLE
)
9719 packet_format
= 'm';
9721 packet_format
= 'x';
9723 send_request (packet_format
);
9724 int packet_len
= getpkt (&rs
->buf
);
9726 return TARGET_XFER_E_IO
;
9728 if (m_features
.packet_support (PACKET_x
) == PACKET_SUPPORT_UNKNOWN
)
9730 if (rs
->buf
[0] == '\0')
9732 remote_debug_printf ("binary uploading NOT supported by target");
9733 m_features
.m_protocol_packets
[PACKET_x
].support
= PACKET_DISABLE
;
9735 /* Try again using 'm'. */
9736 packet_format
= 'm';
9737 send_request (packet_format
);
9738 packet_len
= getpkt (&rs
->buf
);
9740 return TARGET_XFER_E_IO
;
9744 remote_debug_printf ("binary uploading supported by target");
9745 m_features
.m_protocol_packets
[PACKET_x
].support
= PACKET_ENABLE
;
9749 packet_result result
= packet_check_result (rs
->buf
);
9750 if (result
.status () == PACKET_ERROR
)
9751 return TARGET_XFER_E_IO
;
9753 char *p
= rs
->buf
.data ();
9754 if (packet_format
== 'x')
9757 return TARGET_XFER_E_IO
;
9759 /* Adjust for 'b'. */
9762 decoded_bytes
= remote_unescape_input ((const gdb_byte
*) p
,
9764 todo_units
* unit_size
);
9768 /* Reply describes memory byte by byte, each byte encoded as two hex
9770 decoded_bytes
= hex2bin (p
, myaddr
, todo_units
* unit_size
);
9773 /* Return what we have. Let higher layers handle partial reads. */
9774 *xfered_len_units
= (ULONGEST
) (decoded_bytes
/ unit_size
);
9775 return (*xfered_len_units
!= 0) ? TARGET_XFER_OK
: TARGET_XFER_EOF
;
9778 /* Using the set of read-only target sections of remote, read live
9781 For interface/parameters/return description see target.h,
9785 remote_target::remote_xfer_live_readonly_partial (gdb_byte
*readbuf
,
9789 ULONGEST
*xfered_len
)
9791 const struct target_section
*secp
;
9793 secp
= target_section_by_addr (this, memaddr
);
9795 && (bfd_section_flags (secp
->the_bfd_section
) & SEC_READONLY
))
9797 ULONGEST memend
= memaddr
+ len
;
9799 const std::vector
<target_section
> *table
9800 = target_get_section_table (this);
9801 for (const target_section
&p
: *table
)
9803 if (memaddr
>= p
.addr
)
9805 if (memend
<= p
.endaddr
)
9807 /* Entire transfer is within this section. */
9808 return remote_read_bytes_1 (memaddr
, readbuf
, len
, unit_size
,
9811 else if (memaddr
>= p
.endaddr
)
9813 /* This section ends before the transfer starts. */
9818 /* This section overlaps the transfer. Just do half. */
9819 len
= p
.endaddr
- memaddr
;
9820 return remote_read_bytes_1 (memaddr
, readbuf
, len
, unit_size
,
9827 return TARGET_XFER_EOF
;
9830 /* Similar to remote_read_bytes_1, but it reads from the remote stub
9831 first if the requested memory is unavailable in traceframe.
9832 Otherwise, fall back to remote_read_bytes_1. */
9835 remote_target::remote_read_bytes (CORE_ADDR memaddr
,
9836 gdb_byte
*myaddr
, ULONGEST len
, int unit_size
,
9837 ULONGEST
*xfered_len
)
9840 return TARGET_XFER_EOF
;
9842 if (get_traceframe_number () != -1)
9844 std::vector
<mem_range
> available
;
9846 /* If we fail to get the set of available memory, then the
9847 target does not support querying traceframe info, and so we
9848 attempt reading from the traceframe anyway (assuming the
9849 target implements the old QTro packet then). */
9850 if (traceframe_available_memory (&available
, memaddr
, len
))
9852 if (available
.empty () || available
[0].start
!= memaddr
)
9854 enum target_xfer_status res
;
9856 /* Don't read into the traceframe's available
9858 if (!available
.empty ())
9860 LONGEST oldlen
= len
;
9862 len
= available
[0].start
- memaddr
;
9863 gdb_assert (len
<= oldlen
);
9866 /* This goes through the topmost target again. */
9867 res
= remote_xfer_live_readonly_partial (myaddr
, memaddr
,
9868 len
, unit_size
, xfered_len
);
9869 if (res
== TARGET_XFER_OK
)
9870 return TARGET_XFER_OK
;
9873 /* No use trying further, we know some memory starting
9874 at MEMADDR isn't available. */
9876 return (*xfered_len
!= 0) ?
9877 TARGET_XFER_UNAVAILABLE
: TARGET_XFER_EOF
;
9881 /* Don't try to read more than how much is available, in
9882 case the target implements the deprecated QTro packet to
9883 cater for older GDBs (the target's knowledge of read-only
9884 sections may be outdated by now). */
9885 len
= available
[0].length
;
9889 return remote_read_bytes_1 (memaddr
, myaddr
, len
, unit_size
, xfered_len
);
9894 /* Sends a packet with content determined by the printf format string
9895 FORMAT and the remaining arguments, then gets the reply. Returns
9896 whether the packet was a success, a failure, or unknown. */
9899 remote_target::remote_send_printf (const char *format
, ...)
9901 struct remote_state
*rs
= get_remote_state ();
9902 int max_size
= get_remote_packet_size ();
9905 va_start (ap
, format
);
9908 int size
= vsnprintf (rs
->buf
.data (), max_size
, format
, ap
);
9912 if (size
>= max_size
)
9913 internal_error (_("Too long remote packet."));
9915 if (putpkt (rs
->buf
) < 0)
9916 error (_("Communication problem with target."));
9921 return packet_check_result (rs
->buf
).status ();
9924 /* Flash writing can take quite some time. We'll set
9925 effectively infinite timeout for flash operations.
9926 In future, we'll need to decide on a better approach. */
9927 static const int remote_flash_timeout
= 1000;
9930 remote_target::flash_erase (ULONGEST address
, LONGEST length
)
9932 int addr_size
= gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
9933 enum packet_status ret
;
9934 scoped_restore restore_timeout
9935 = make_scoped_restore (&remote_timeout
, remote_flash_timeout
);
9937 ret
= remote_send_printf ("vFlashErase:%s,%s",
9938 phex (address
, addr_size
),
9942 case PACKET_UNKNOWN
:
9943 error (_("Remote target does not support flash erase"));
9945 error (_("Error erasing flash with vFlashErase packet"));
9952 remote_target::remote_flash_write (ULONGEST address
,
9953 ULONGEST length
, ULONGEST
*xfered_len
,
9954 const gdb_byte
*data
)
9956 scoped_restore restore_timeout
9957 = make_scoped_restore (&remote_timeout
, remote_flash_timeout
);
9958 return remote_write_bytes_aux ("vFlashWrite:", address
, data
, length
, 1,
9963 remote_target::flash_done ()
9967 scoped_restore restore_timeout
9968 = make_scoped_restore (&remote_timeout
, remote_flash_timeout
);
9970 ret
= remote_send_printf ("vFlashDone");
9974 case PACKET_UNKNOWN
:
9975 error (_("Remote target does not support vFlashDone"));
9977 error (_("Error finishing flash operation"));
9984 /* Stuff for dealing with the packets which are part of this protocol.
9985 See comment at top of file for details. */
9987 /* Read a single character from the remote end. The current quit
9988 handler is overridden to avoid quitting in the middle of packet
9989 sequence, as that would break communication with the remote server.
9990 See remote_serial_quit_handler for more detail. */
9993 remote_target::readchar (int timeout
)
9996 struct remote_state
*rs
= get_remote_state ();
10000 scoped_restore restore_quit_target
10001 = make_scoped_restore (&curr_quit_handler_target
, this);
10002 scoped_restore restore_quit
10003 = make_scoped_restore (&quit_handler
, ::remote_serial_quit_handler
);
10005 rs
->got_ctrlc_during_io
= 0;
10007 ch
= serial_readchar (rs
->remote_desc
, timeout
);
10009 if (rs
->got_ctrlc_during_io
)
10012 catch (const gdb_exception_error
&ex
)
10014 remote_unpush_target (this);
10015 throw_error (TARGET_CLOSE_ERROR
,
10016 _("Remote communication error. "
10017 "Target disconnected: %s"),
10024 if (ch
== SERIAL_EOF
)
10026 remote_unpush_target (this);
10027 throw_error (TARGET_CLOSE_ERROR
, _("Remote connection closed"));
10033 /* Wrapper for serial_write that closes the target and throws if
10034 writing fails. The current quit handler is overridden to avoid
10035 quitting in the middle of packet sequence, as that would break
10036 communication with the remote server. See
10037 remote_serial_quit_handler for more detail. */
10040 remote_target::remote_serial_write (const char *str
, int len
)
10042 struct remote_state
*rs
= get_remote_state ();
10044 scoped_restore restore_quit_target
10045 = make_scoped_restore (&curr_quit_handler_target
, this);
10046 scoped_restore restore_quit
10047 = make_scoped_restore (&quit_handler
, ::remote_serial_quit_handler
);
10049 rs
->got_ctrlc_during_io
= 0;
10053 serial_write (rs
->remote_desc
, str
, len
);
10055 catch (const gdb_exception_error
&ex
)
10057 remote_unpush_target (this);
10058 throw_error (TARGET_CLOSE_ERROR
,
10059 _("Remote communication error. "
10060 "Target disconnected: %s"),
10064 if (rs
->got_ctrlc_during_io
)
10069 remote_target::remote_serial_send_break ()
10071 struct remote_state
*rs
= get_remote_state ();
10075 serial_send_break (rs
->remote_desc
);
10077 catch (const gdb_exception_error
&ex
)
10079 remote_unpush_target (this);
10080 throw_error (TARGET_CLOSE_ERROR
,
10081 _("Remote communication error. "
10082 "Target disconnected: %s"),
10087 /* Return a string representing an escaped version of BUF, of len N.
10088 E.g. \n is converted to \\n, \t to \\t, etc. */
10091 escape_buffer (const char *buf
, int n
)
10095 stb
.putstrn (buf
, n
, '\\');
10096 return stb
.release ();
10100 remote_target::putpkt (const char *buf
)
10102 return putpkt_binary (buf
, strlen (buf
));
10105 /* Wrapper around remote_target::putpkt to avoid exporting
10109 putpkt (remote_target
*remote
, const char *buf
)
10111 return remote
->putpkt (buf
);
10114 /* Send a packet to the remote machine, with error checking. The data
10115 of the packet is in BUF. The string in BUF can be at most
10116 get_remote_packet_size () - 5 to account for the $, # and checksum,
10117 and for a possible /0 if we are debugging (remote_debug) and want
10118 to print the sent packet as a string. */
10121 remote_target::putpkt_binary (const char *buf
, int cnt
)
10123 struct remote_state
*rs
= get_remote_state ();
10125 unsigned char csum
= 0;
10126 gdb::def_vector
<char> data (cnt
+ 6);
10127 char *buf2
= data
.data ();
10133 /* Catch cases like trying to read memory or listing threads while
10134 we're waiting for a stop reply. The remote server wouldn't be
10135 ready to handle this request, so we'd hang and timeout. We don't
10136 have to worry about this in synchronous mode, because in that
10137 case it's not possible to issue a command while the target is
10138 running. This is not a problem in non-stop mode, because in that
10139 case, the stub is always ready to process serial input. */
10140 if (!target_is_non_stop_p ()
10141 && target_is_async_p ()
10142 && rs
->waiting_for_stop_reply
)
10144 error (_("Cannot execute this command while the target is running.\n"
10145 "Use the \"interrupt\" command to stop the target\n"
10146 "and then try again."));
10149 /* Copy the packet into buffer BUF2, encapsulating it
10150 and giving it a checksum. */
10155 for (i
= 0; i
< cnt
; i
++)
10161 *p
++ = tohex ((csum
>> 4) & 0xf);
10162 *p
++ = tohex (csum
& 0xf);
10164 /* Send it over and over until we get a positive ack. */
10172 int len
= (int) (p
- buf2
);
10175 if (remote_packet_max_chars
< 0)
10178 max_chars
= remote_packet_max_chars
;
10181 = escape_buffer (buf2
, std::min (len
, max_chars
));
10183 if (len
> max_chars
)
10184 remote_debug_printf_nofunc
10185 ("Sending packet: %s [%d bytes omitted]", str
.c_str (),
10188 remote_debug_printf_nofunc ("Sending packet: %s", str
.c_str ());
10190 remote_serial_write (buf2
, p
- buf2
);
10192 /* If this is a no acks version of the remote protocol, send the
10193 packet and move on. */
10194 if (rs
->noack_mode
)
10197 /* Read until either a timeout occurs (-2) or '+' is read.
10198 Handle any notification that arrives in the mean time. */
10201 ch
= readchar (remote_timeout
);
10206 remote_debug_printf_nofunc ("Received Ack");
10209 remote_debug_printf_nofunc ("Received Nak");
10211 case SERIAL_TIMEOUT
:
10215 break; /* Retransmit buffer. */
10218 remote_debug_printf ("Packet instead of Ack, ignoring it");
10219 /* It's probably an old response sent because an ACK
10220 was lost. Gobble up the packet and ack it so it
10221 doesn't get retransmitted when we resend this
10224 remote_serial_write ("+", 1);
10225 continue; /* Now, go look for +. */
10232 /* If we got a notification, handle it, and go back to looking
10234 /* We've found the start of a notification. Now
10235 collect the data. */
10236 val
= read_frame (&rs
->buf
);
10239 remote_debug_printf_nofunc
10240 (" Notification received: %s",
10241 escape_buffer (rs
->buf
.data (), val
).c_str ());
10243 handle_notification (rs
->notif_state
, rs
->buf
.data ());
10244 /* We're in sync now, rewait for the ack. */
10248 remote_debug_printf_nofunc ("Junk: %c%s", ch
& 0177,
10253 remote_debug_printf_nofunc ("Junk: %c%s", ch
& 0177,
10257 break; /* Here to retransmit. */
10261 /* This is wrong. If doing a long backtrace, the user should be
10262 able to get out next time we call QUIT, without anything as
10263 violent as interrupt_query. If we want to provide a way out of
10264 here without getting to the next QUIT, it should be based on
10265 hitting ^C twice as in remote_wait. */
10269 interrupt_query ();
10277 /* Come here after finding the start of a frame when we expected an
10278 ack. Do our best to discard the rest of this packet. */
10281 remote_target::skip_frame ()
10287 c
= readchar (remote_timeout
);
10290 case SERIAL_TIMEOUT
:
10291 /* Nothing we can do. */
10294 /* Discard the two bytes of checksum and stop. */
10295 c
= readchar (remote_timeout
);
10297 c
= readchar (remote_timeout
);
10300 case '*': /* Run length encoding. */
10301 /* Discard the repeat count. */
10302 c
= readchar (remote_timeout
);
10307 /* A regular character. */
10313 /* Come here after finding the start of the frame. Collect the rest
10314 into *BUF, verifying the checksum, length, and handling run-length
10315 compression. NUL terminate the buffer. If there is not enough room,
10318 Returns -1 on error, number of characters in buffer (ignoring the
10319 trailing NULL) on success. (could be extended to return one of the
10320 SERIAL status indications). */
10323 remote_target::read_frame (gdb::char_vector
*buf_p
)
10325 unsigned char csum
;
10328 char *buf
= buf_p
->data ();
10329 struct remote_state
*rs
= get_remote_state ();
10336 c
= readchar (remote_timeout
);
10339 case SERIAL_TIMEOUT
:
10340 remote_debug_printf ("Timeout in mid-packet, retrying");
10344 remote_debug_printf ("Saw new packet start in middle of old one");
10345 return -1; /* Start a new packet, count retries. */
10349 unsigned char pktcsum
;
10355 check_0
= readchar (remote_timeout
);
10357 check_1
= readchar (remote_timeout
);
10359 if (check_0
== SERIAL_TIMEOUT
|| check_1
== SERIAL_TIMEOUT
)
10361 remote_debug_printf ("Timeout in checksum, retrying");
10364 else if (check_0
< 0 || check_1
< 0)
10366 remote_debug_printf ("Communication error in checksum");
10370 /* Don't recompute the checksum; with no ack packets we
10371 don't have any way to indicate a packet retransmission
10373 if (rs
->noack_mode
)
10376 pktcsum
= (fromhex (check_0
) << 4) | fromhex (check_1
);
10377 if (csum
== pktcsum
)
10380 remote_debug_printf
10381 ("Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s",
10382 pktcsum
, csum
, escape_buffer (buf
, bc
).c_str ());
10384 /* Number of characters in buffer ignoring trailing
10388 case '*': /* Run length encoding. */
10393 c
= readchar (remote_timeout
);
10395 repeat
= c
- ' ' + 3; /* Compute repeat count. */
10397 /* The character before ``*'' is repeated. */
10399 if (repeat
> 0 && repeat
<= 255 && bc
> 0)
10401 if (bc
+ repeat
- 1 >= buf_p
->size () - 1)
10403 /* Make some more room in the buffer. */
10404 buf_p
->resize (buf_p
->size () + repeat
);
10405 buf
= buf_p
->data ();
10408 memset (&buf
[bc
], buf
[bc
- 1], repeat
);
10414 gdb_printf (_("Invalid run length encoding: %s\n"), buf
);
10418 if (bc
>= buf_p
->size () - 1)
10420 /* Make some more room in the buffer. */
10421 buf_p
->resize (buf_p
->size () * 2);
10422 buf
= buf_p
->data ();
10432 /* Set this to the maximum number of seconds to wait instead of waiting forever
10433 in target_wait(). If this timer times out, then it generates an error and
10434 the command is aborted. This replaces most of the need for timeouts in the
10435 GDB test suite, and makes it possible to distinguish between a hung target
10436 and one with slow communications. */
10438 static int watchdog
= 0;
10440 show_watchdog (struct ui_file
*file
, int from_tty
,
10441 struct cmd_list_element
*c
, const char *value
)
10443 gdb_printf (file
, _("Watchdog timer is %s.\n"), value
);
10446 /* Read a packet from the remote machine, with error checking, and
10447 store it in *BUF. Resize *BUF if necessary to hold the result. If
10448 FOREVER, wait forever rather than timing out; this is used (in
10449 synchronous mode) to wait for a target that is is executing user
10450 code to stop. If FOREVER == false, this function is allowed to time
10451 out gracefully and return an indication of this to the caller.
10452 Otherwise return the number of bytes read. If IS_NOTIF is not
10453 NULL, then consider receiving a notification enough reason to
10454 return to the caller. In this case, *IS_NOTIF is an output boolean
10455 that indicates whether *BUF holds a notification or not (a regular
10459 remote_target::getpkt (gdb::char_vector
*buf
, bool forever
, bool *is_notif
)
10461 struct remote_state
*rs
= get_remote_state ();
10467 strcpy (buf
->data (), "timeout");
10470 timeout
= watchdog
> 0 ? watchdog
: -1;
10471 else if (is_notif
!= nullptr)
10472 timeout
= 0; /* There should already be a char in the buffer. If
10475 timeout
= remote_timeout
;
10477 #define MAX_TRIES 3
10479 /* Process any number of notifications, and then return when
10480 we get a packet. */
10483 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
10485 for (tries
= 1; tries
<= MAX_TRIES
; tries
++)
10487 /* This can loop forever if the remote side sends us
10488 characters continuously, but if it pauses, we'll get
10489 SERIAL_TIMEOUT from readchar because of timeout. Then
10490 we'll count that as a retry.
10492 Note that even when forever is set, we will only wait
10493 forever prior to the start of a packet. After that, we
10494 expect characters to arrive at a brisk pace. They should
10495 show up within remote_timeout intervals. */
10497 c
= readchar (timeout
);
10498 while (c
!= SERIAL_TIMEOUT
&& c
!= '$' && c
!= '%');
10500 if (c
== SERIAL_TIMEOUT
)
10502 if (is_notif
!= nullptr)
10503 return -1; /* Don't complain, it's normal to not get
10504 anything in this case. */
10506 if (forever
) /* Watchdog went off? Kill the target. */
10508 remote_unpush_target (this);
10509 throw_error (TARGET_CLOSE_ERROR
,
10510 _("Watchdog timeout has expired. "
10511 "Target detached."));
10514 remote_debug_printf ("Timed out.");
10518 /* We've found the start of a packet or notification.
10519 Now collect the data. */
10520 val
= read_frame (buf
);
10525 remote_serial_write ("-", 1);
10528 if (tries
> MAX_TRIES
)
10530 /* We have tried hard enough, and just can't receive the
10531 packet/notification. Give up. */
10532 gdb_printf (_("Ignoring packet error, continuing...\n"));
10534 /* Skip the ack char if we're in no-ack mode. */
10535 if (!rs
->noack_mode
)
10536 remote_serial_write ("+", 1);
10540 /* If we got an ordinary packet, return that to our caller. */
10547 if (remote_packet_max_chars
< 0)
10550 max_chars
= remote_packet_max_chars
;
10553 = escape_buffer (buf
->data (),
10554 std::min (val
, max_chars
));
10556 if (val
> max_chars
)
10557 remote_debug_printf_nofunc
10558 ("Packet received: %s [%d of %d bytes omitted]", str
.c_str (),
10559 val
- max_chars
, val
);
10561 remote_debug_printf_nofunc ("Packet received: %s",
10565 /* Skip the ack char if we're in no-ack mode. */
10566 if (!rs
->noack_mode
)
10567 remote_serial_write ("+", 1);
10568 if (is_notif
!= NULL
)
10573 /* If we got a notification, handle it, and go back to looking
10577 gdb_assert (c
== '%');
10579 remote_debug_printf_nofunc
10580 (" Notification received: %s",
10581 escape_buffer (buf
->data (), val
).c_str ());
10583 if (is_notif
!= NULL
)
10586 handle_notification (rs
->notif_state
, buf
->data ());
10588 /* Notifications require no acknowledgement. */
10590 if (is_notif
!= nullptr)
10596 /* Kill any new fork children of inferior INF that haven't been
10597 processed by follow_fork. */
10600 remote_target::kill_new_fork_children (inferior
*inf
)
10602 remote_state
*rs
= get_remote_state ();
10603 const notif_client
*notif
= ¬if_client_stop
;
10605 /* Kill the fork child threads of any threads in inferior INF that are stopped
10606 at a fork event. */
10607 for (thread_info
*thread
: inf
->non_exited_threads ())
10609 const target_waitstatus
*ws
= thread_pending_fork_status (thread
);
10614 int child_pid
= ws
->child_ptid ().pid ();
10615 int res
= remote_vkill (child_pid
);
10618 error (_("Can't kill fork child process %d"), child_pid
);
10621 /* Check for any pending fork events (not reported or processed yet)
10622 in inferior INF and kill those fork child threads as well. */
10623 remote_notif_get_pending_events (notif
);
10624 for (auto &event
: rs
->stop_reply_queue
)
10626 if (event
->ptid
.pid () != inf
->pid
)
10629 if (!is_fork_status (event
->ws
.kind ()))
10632 int child_pid
= event
->ws
.child_ptid ().pid ();
10633 int res
= remote_vkill (child_pid
);
10636 error (_("Can't kill fork child process %d"), child_pid
);
10641 /* Target hook to kill the current inferior. */
10644 remote_target::kill ()
10647 inferior
*inf
= find_inferior_pid (this, inferior_ptid
.pid ());
10649 gdb_assert (inf
!= nullptr);
10651 if (m_features
.packet_support (PACKET_vKill
) != PACKET_DISABLE
)
10653 /* If we're stopped while forking and we haven't followed yet,
10654 kill the child task. We need to do this before killing the
10655 parent task because if this is a vfork then the parent will
10657 kill_new_fork_children (inf
);
10659 res
= remote_vkill (inf
->pid
);
10662 target_mourn_inferior (inferior_ptid
);
10667 /* If we are in 'target remote' mode and we are killing the only
10668 inferior, then we will tell gdbserver to exit and unpush the
10670 if (res
== -1 && !m_features
.remote_multi_process_p ()
10671 && number_of_live_inferiors (this) == 1)
10675 /* We've killed the remote end, we get to mourn it. If we are
10676 not in extended mode, mourning the inferior also unpushes
10677 remote_ops from the target stack, which closes the remote
10679 target_mourn_inferior (inferior_ptid
);
10684 error (_("Can't kill process"));
10687 /* Send a kill request to the target using the 'vKill' packet. */
10690 remote_target::remote_vkill (int pid
)
10692 if (m_features
.packet_support (PACKET_vKill
) == PACKET_DISABLE
)
10695 remote_state
*rs
= get_remote_state ();
10697 /* Tell the remote target to detach. */
10698 xsnprintf (rs
->buf
.data (), get_remote_packet_size (), "vKill;%x", pid
);
10702 switch ((m_features
.packet_ok (rs
->buf
, PACKET_vKill
)).status ())
10708 case PACKET_UNKNOWN
:
10711 internal_error (_("Bad result from packet_ok"));
10715 /* Send a kill request to the target using the 'k' packet. */
10718 remote_target::remote_kill_k ()
10720 /* Catch errors so the user can quit from gdb even when we
10721 aren't on speaking terms with the remote system. */
10726 catch (const gdb_exception_error
&ex
)
10728 if (ex
.error
== TARGET_CLOSE_ERROR
)
10730 /* If we got an (EOF) error that caused the target
10731 to go away, then we're done, that's what we wanted.
10732 "k" is susceptible to cause a premature EOF, given
10733 that the remote server isn't actually required to
10734 reply to "k", and it can happen that it doesn't
10735 even get to reply ACK to the "k". */
10739 /* Otherwise, something went wrong. We didn't actually kill
10740 the target. Just propagate the exception, and let the
10741 user or higher layers decide what to do. */
10747 remote_target::mourn_inferior ()
10749 struct remote_state
*rs
= get_remote_state ();
10751 /* We're no longer interested in notification events of an inferior
10752 that exited or was killed/detached. */
10753 discard_pending_stop_replies (current_inferior ());
10755 /* In 'target remote' mode with one inferior, we close the connection. */
10756 if (!rs
->extended
&& number_of_live_inferiors (this) <= 1)
10758 remote_unpush_target (this);
10762 /* In case we got here due to an error, but we're going to stay
10764 rs
->waiting_for_stop_reply
= 0;
10766 /* If the current general thread belonged to the process we just
10767 detached from or has exited, the remote side current general
10768 thread becomes undefined. Considering a case like this:
10770 - We just got here due to a detach.
10771 - The process that we're detaching from happens to immediately
10772 report a global breakpoint being hit in non-stop mode, in the
10773 same thread we had selected before.
10774 - GDB attaches to this process again.
10775 - This event happens to be the next event we handle.
10777 GDB would consider that the current general thread didn't need to
10778 be set on the stub side (with Hg), since for all it knew,
10779 GENERAL_THREAD hadn't changed.
10781 Notice that although in all-stop mode, the remote server always
10782 sets the current thread to the thread reporting the stop event,
10783 that doesn't happen in non-stop mode; in non-stop, the stub *must
10784 not* change the current thread when reporting a breakpoint hit,
10785 due to the decoupling of event reporting and event handling.
10787 To keep things simple, we always invalidate our notion of the
10789 record_currthread (rs
, minus_one_ptid
);
10791 /* Call common code to mark the inferior as not running. */
10792 generic_mourn_inferior ();
10796 extended_remote_target::supports_disable_randomization ()
10798 return (m_features
.packet_support (PACKET_QDisableRandomization
)
10803 remote_target::extended_remote_disable_randomization (int val
)
10805 struct remote_state
*rs
= get_remote_state ();
10808 xsnprintf (rs
->buf
.data (), get_remote_packet_size (),
10809 "QDisableRandomization:%x", val
);
10811 reply
= remote_get_noisy_reply ();
10812 if (*reply
== '\0')
10813 error (_("Target does not support QDisableRandomization."));
10814 if (strcmp (reply
, "OK") != 0)
10815 error (_("Bogus QDisableRandomization reply from target: %s"), reply
);
10819 remote_target::extended_remote_run (const std::string
&args
)
10821 struct remote_state
*rs
= get_remote_state ();
10823 const char *remote_exec_file
= get_remote_exec_file ();
10825 /* If the user has disabled vRun support, or we have detected that
10826 support is not available, do not try it. */
10827 if (m_features
.packet_support (PACKET_vRun
) == PACKET_DISABLE
)
10830 strcpy (rs
->buf
.data (), "vRun;");
10831 len
= strlen (rs
->buf
.data ());
10833 if (strlen (remote_exec_file
) * 2 + len
>= get_remote_packet_size ())
10834 error (_("Remote file name too long for run packet"));
10835 len
+= 2 * bin2hex ((gdb_byte
*) remote_exec_file
, rs
->buf
.data () + len
,
10836 strlen (remote_exec_file
));
10838 if (!args
.empty ())
10840 std::vector
<std::string
> split_args
= gdb::remote_args::split (args
);
10842 for (const auto &a
: split_args
)
10844 if (a
.size () * 2 + 1 + len
>= get_remote_packet_size ())
10845 error (_("Argument list too long for run packet"));
10846 rs
->buf
[len
++] = ';';
10847 len
+= 2 * bin2hex ((gdb_byte
*) a
.c_str (), rs
->buf
.data () + len
,
10852 rs
->buf
[len
++] = '\0';
10857 packet_result result
= m_features
.packet_ok (rs
->buf
, PACKET_vRun
);
10858 switch (result
.status ())
10861 /* We have a wait response. All is well. */
10863 case PACKET_UNKNOWN
:
10866 /* If we have a textual error message, print just that. This
10867 makes remote debugging output the same as native output, when
10869 if (result
.textual_err_msg ())
10870 error (("%s"), result
.err_msg ());
10871 if (remote_exec_file
[0] == '\0')
10872 error (_("Running the default executable on the remote target failed; "
10873 "try \"set remote exec-file\"?"));
10875 error (_("Running \"%s\" on the remote target failed"),
10878 gdb_assert_not_reached ("bad switch");
10882 /* Helper function to send set/unset environment packets. ACTION is
10883 either "set" or "unset". PACKET is either "QEnvironmentHexEncoded"
10884 or "QEnvironmentUnsetVariable". VALUE is the variable to be
10888 remote_target::send_environment_packet (const char *action
,
10889 const char *packet
,
10892 remote_state
*rs
= get_remote_state ();
10894 /* Convert the environment variable to an hex string, which
10895 is the best format to be transmitted over the wire. */
10896 std::string encoded_value
= bin2hex ((const gdb_byte
*) value
,
10899 xsnprintf (rs
->buf
.data (), get_remote_packet_size (),
10900 "%s:%s", packet
, encoded_value
.c_str ());
10904 if (strcmp (rs
->buf
.data (), "OK") != 0)
10905 warning (_("Unable to %s environment variable '%s' on remote."),
10909 /* Helper function to handle the QEnvironment* packets. */
10912 remote_target::extended_remote_environment_support ()
10914 remote_state
*rs
= get_remote_state ();
10916 if (m_features
.packet_support (PACKET_QEnvironmentReset
) != PACKET_DISABLE
)
10918 putpkt ("QEnvironmentReset");
10920 if (strcmp (rs
->buf
.data (), "OK") != 0)
10921 warning (_("Unable to reset environment on remote."));
10924 gdb_environ
*e
= ¤t_inferior ()->environment
;
10926 if (m_features
.packet_support (PACKET_QEnvironmentHexEncoded
)
10929 for (const std::string
&el
: e
->user_set_env ())
10930 send_environment_packet ("set", "QEnvironmentHexEncoded",
10935 if (m_features
.packet_support (PACKET_QEnvironmentUnset
) != PACKET_DISABLE
)
10936 for (const std::string
&el
: e
->user_unset_env ())
10937 send_environment_packet ("unset", "QEnvironmentUnset", el
.c_str ());
10940 /* Helper function to set the current working directory for the
10941 inferior in the remote target. */
10944 remote_target::extended_remote_set_inferior_cwd ()
10946 if (m_features
.packet_support (PACKET_QSetWorkingDir
) != PACKET_DISABLE
)
10948 const std::string
&inferior_cwd
= current_inferior ()->cwd ();
10949 remote_state
*rs
= get_remote_state ();
10951 if (!inferior_cwd
.empty ())
10953 std::string hexpath
10954 = bin2hex ((const gdb_byte
*) inferior_cwd
.data (),
10955 inferior_cwd
.size ());
10957 xsnprintf (rs
->buf
.data (), get_remote_packet_size (),
10958 "QSetWorkingDir:%s", hexpath
.c_str ());
10962 /* An empty inferior_cwd means that the user wants us to
10963 reset the remote server's inferior's cwd. */
10964 xsnprintf (rs
->buf
.data (), get_remote_packet_size (),
10965 "QSetWorkingDir:");
10970 packet_result result
= m_features
.packet_ok (rs
->buf
, PACKET_QSetWorkingDir
);
10971 if (result
.status () == PACKET_ERROR
)
10973 Remote replied unexpectedly while setting the inferior's working\n\
10975 result
.err_msg ());
10976 if (result
.status () == PACKET_UNKNOWN
)
10977 error (_("Remote target failed to process setting the inferior's working directory"));
10982 /* In the extended protocol we want to be able to do things like
10983 "run" and have them basically work as expected. So we need
10984 a special create_inferior function. We support changing the
10985 executable file and the command line arguments, but not the
10989 extended_remote_target::create_inferior (const char *exec_file
,
10990 const std::string
&args
,
10991 char **env
, int from_tty
)
10995 struct remote_state
*rs
= get_remote_state ();
10996 const char *remote_exec_file
= get_remote_exec_file ();
10998 /* If running asynchronously, register the target file descriptor
10999 with the event loop. */
11000 if (target_can_async_p ())
11001 target_async (true);
11003 /* Disable address space randomization if requested (and supported). */
11004 if (supports_disable_randomization ())
11005 extended_remote_disable_randomization (disable_randomization
);
11007 /* If startup-with-shell is on, we inform gdbserver to start the
11008 remote inferior using a shell. */
11009 if (m_features
.packet_support (PACKET_QStartupWithShell
) != PACKET_DISABLE
)
11011 xsnprintf (rs
->buf
.data (), get_remote_packet_size (),
11012 "QStartupWithShell:%d", startup_with_shell
? 1 : 0);
11015 if (strcmp (rs
->buf
.data (), "OK") != 0)
11017 Remote replied unexpectedly while setting startup-with-shell: %s"),
11021 extended_remote_environment_support ();
11023 extended_remote_set_inferior_cwd ();
11025 /* Now restart the remote server. */
11026 run_worked
= extended_remote_run (args
) != -1;
11029 /* vRun was not supported. Fail if we need it to do what the
11031 if (remote_exec_file
[0])
11032 error (_("Remote target does not support \"set remote exec-file\""));
11033 if (!args
.empty ())
11034 error (_("Remote target does not support \"set args\" or run ARGS"));
11036 /* Fall back to "R". */
11037 extended_remote_restart ();
11040 /* vRun's success return is a stop reply. */
11041 stop_reply
= run_worked
? rs
->buf
.data () : NULL
;
11042 add_current_inferior_and_thread (stop_reply
);
11044 /* Get updated offsets, if the stub uses qOffsets. */
11049 /* Given a location's target info BP_TGT and the packet buffer BUF, output
11050 the list of conditions (in agent expression bytecode format), if any, the
11051 target needs to evaluate. The output is placed into the packet buffer
11052 started from BUF and ended at BUF_END. */
11055 remote_add_target_side_condition (struct gdbarch
*gdbarch
,
11056 struct bp_target_info
*bp_tgt
, char *buf
,
11059 if (bp_tgt
->conditions
.empty ())
11062 buf
+= strlen (buf
);
11063 xsnprintf (buf
, buf_end
- buf
, "%s", ";");
11066 /* Send conditions to the target. */
11067 for (agent_expr
*aexpr
: bp_tgt
->conditions
)
11069 xsnprintf (buf
, buf_end
- buf
, "X%x,", (int) aexpr
->buf
.size ());
11070 buf
+= strlen (buf
);
11071 for (int i
= 0; i
< aexpr
->buf
.size (); ++i
)
11072 buf
= pack_hex_byte (buf
, aexpr
->buf
[i
]);
11079 remote_add_target_side_commands (struct gdbarch
*gdbarch
,
11080 struct bp_target_info
*bp_tgt
, char *buf
)
11082 if (bp_tgt
->tcommands
.empty ())
11085 buf
+= strlen (buf
);
11087 sprintf (buf
, ";cmds:%x,", bp_tgt
->persist
);
11088 buf
+= strlen (buf
);
11090 /* Concatenate all the agent expressions that are commands into the
11092 for (agent_expr
*aexpr
: bp_tgt
->tcommands
)
11094 sprintf (buf
, "X%x,", (int) aexpr
->buf
.size ());
11095 buf
+= strlen (buf
);
11096 for (int i
= 0; i
< aexpr
->buf
.size (); ++i
)
11097 buf
= pack_hex_byte (buf
, aexpr
->buf
[i
]);
11102 /* Insert a breakpoint. On targets that have software breakpoint
11103 support, we ask the remote target to do the work; on targets
11104 which don't, we insert a traditional memory breakpoint. */
11107 remote_target::insert_breakpoint (struct gdbarch
*gdbarch
,
11108 struct bp_target_info
*bp_tgt
)
11110 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
11111 If it succeeds, then set the support to PACKET_ENABLE. If it
11112 fails, and the user has explicitly requested the Z support then
11113 report an error, otherwise, mark it disabled and go on. */
11115 if (m_features
.packet_support (PACKET_Z0
) != PACKET_DISABLE
)
11117 CORE_ADDR addr
= bp_tgt
->reqstd_address
;
11118 struct remote_state
*rs
;
11121 /* Make sure the remote is pointing at the right process, if
11123 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
11124 set_general_process ();
11126 rs
= get_remote_state ();
11127 p
= rs
->buf
.data ();
11128 endbuf
= p
+ get_remote_packet_size ();
11133 addr
= (ULONGEST
) remote_address_masked (addr
);
11134 p
+= hexnumstr (p
, addr
);
11135 xsnprintf (p
, endbuf
- p
, ",%d", bp_tgt
->kind
);
11137 if (supports_evaluation_of_breakpoint_conditions ())
11138 remote_add_target_side_condition (gdbarch
, bp_tgt
, p
, endbuf
);
11140 if (can_run_breakpoint_commands ())
11141 remote_add_target_side_commands (gdbarch
, bp_tgt
, p
);
11146 switch ((m_features
.packet_ok (rs
->buf
, PACKET_Z0
)).status ())
11152 case PACKET_UNKNOWN
:
11157 /* If this breakpoint has target-side commands but this stub doesn't
11158 support Z0 packets, throw error. */
11159 if (!bp_tgt
->tcommands
.empty ())
11160 throw_error (NOT_SUPPORTED_ERROR
, _("\
11161 Target doesn't support breakpoints that have target side commands."));
11163 return memory_insert_breakpoint (this, gdbarch
, bp_tgt
);
11167 remote_target::remove_breakpoint (struct gdbarch
*gdbarch
,
11168 struct bp_target_info
*bp_tgt
,
11169 enum remove_bp_reason reason
)
11171 CORE_ADDR addr
= bp_tgt
->placed_address
;
11172 struct remote_state
*rs
= get_remote_state ();
11174 if (m_features
.packet_support (PACKET_Z0
) != PACKET_DISABLE
)
11176 char *p
= rs
->buf
.data ();
11177 char *endbuf
= p
+ get_remote_packet_size ();
11179 /* Make sure the remote is pointing at the right process, if
11181 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
11182 set_general_process ();
11188 addr
= (ULONGEST
) remote_address_masked (bp_tgt
->placed_address
);
11189 p
+= hexnumstr (p
, addr
);
11190 xsnprintf (p
, endbuf
- p
, ",%d", bp_tgt
->kind
);
11195 return (rs
->buf
[0] == 'E');
11198 return memory_remove_breakpoint (this, gdbarch
, bp_tgt
, reason
);
11201 static enum Z_packet_type
11202 watchpoint_to_Z_packet (int type
)
11207 return Z_PACKET_WRITE_WP
;
11210 return Z_PACKET_READ_WP
;
11213 return Z_PACKET_ACCESS_WP
;
11216 internal_error (_("hw_bp_to_z: bad watchpoint type %d"), type
);
11221 remote_target::insert_watchpoint (CORE_ADDR addr
, int len
,
11222 enum target_hw_bp_type type
, struct expression
*cond
)
11224 struct remote_state
*rs
= get_remote_state ();
11225 char *endbuf
= rs
->buf
.data () + get_remote_packet_size ();
11227 enum Z_packet_type packet
= watchpoint_to_Z_packet (type
);
11229 if (m_features
.packet_support ((to_underlying (PACKET_Z0
)
11230 + to_underlying (packet
))) == PACKET_DISABLE
)
11233 /* Make sure the remote is pointing at the right process, if
11235 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
11236 set_general_process ();
11238 xsnprintf (rs
->buf
.data (), endbuf
- rs
->buf
.data (), "Z%x,", packet
);
11239 p
= strchr (rs
->buf
.data (), '\0');
11240 addr
= remote_address_masked (addr
);
11241 p
+= hexnumstr (p
, (ULONGEST
) addr
);
11242 xsnprintf (p
, endbuf
- p
, ",%x", len
);
11247 switch ((m_features
.packet_ok (rs
->buf
, (to_underlying (PACKET_Z0
)
11248 + to_underlying (packet
)))).status ())
11252 case PACKET_UNKNOWN
:
11257 internal_error (_("remote_insert_watchpoint: reached end of function"));
11261 remote_target::watchpoint_addr_within_range (CORE_ADDR addr
,
11262 CORE_ADDR start
, int length
)
11264 CORE_ADDR diff
= remote_address_masked (addr
- start
);
11266 return diff
< length
;
11271 remote_target::remove_watchpoint (CORE_ADDR addr
, int len
,
11272 enum target_hw_bp_type type
, struct expression
*cond
)
11274 struct remote_state
*rs
= get_remote_state ();
11275 char *endbuf
= rs
->buf
.data () + get_remote_packet_size ();
11277 enum Z_packet_type packet
= watchpoint_to_Z_packet (type
);
11279 if (m_features
.packet_support ((to_underlying (PACKET_Z0
)
11280 + to_underlying (packet
))) == PACKET_DISABLE
)
11283 /* Make sure the remote is pointing at the right process, if
11285 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
11286 set_general_process ();
11288 xsnprintf (rs
->buf
.data (), endbuf
- rs
->buf
.data (), "z%x,", packet
);
11289 p
= strchr (rs
->buf
.data (), '\0');
11290 addr
= remote_address_masked (addr
);
11291 p
+= hexnumstr (p
, (ULONGEST
) addr
);
11292 xsnprintf (p
, endbuf
- p
, ",%x", len
);
11296 switch ((m_features
.packet_ok (rs
->buf
, (to_underlying (PACKET_Z0
)
11297 + to_underlying (packet
)))).status ())
11300 case PACKET_UNKNOWN
:
11305 internal_error (_("remote_remove_watchpoint: reached end of function"));
11309 static int remote_hw_watchpoint_limit
= -1;
11310 static int remote_hw_watchpoint_length_limit
= -1;
11311 static int remote_hw_breakpoint_limit
= -1;
11314 remote_target::region_ok_for_hw_watchpoint (CORE_ADDR addr
, int len
)
11316 if (remote_hw_watchpoint_length_limit
== 0)
11318 else if (remote_hw_watchpoint_length_limit
< 0)
11320 else if (len
<= remote_hw_watchpoint_length_limit
)
11327 remote_target::can_use_hw_breakpoint (enum bptype type
, int cnt
, int ot
)
11329 if (type
== bp_hardware_breakpoint
)
11331 if (remote_hw_breakpoint_limit
== 0)
11333 else if (remote_hw_breakpoint_limit
< 0)
11335 else if (cnt
<= remote_hw_breakpoint_limit
)
11340 if (remote_hw_watchpoint_limit
== 0)
11342 else if (remote_hw_watchpoint_limit
< 0)
11346 else if (cnt
<= remote_hw_watchpoint_limit
)
11352 /* The to_stopped_by_sw_breakpoint method of target remote. */
11355 remote_target::stopped_by_sw_breakpoint ()
11357 struct thread_info
*thread
= inferior_thread ();
11359 return (thread
->priv
!= NULL
11360 && (get_remote_thread_info (thread
)->stop_reason
11361 == TARGET_STOPPED_BY_SW_BREAKPOINT
));
11364 /* The to_supports_stopped_by_sw_breakpoint method of target
11368 remote_target::supports_stopped_by_sw_breakpoint ()
11370 return (m_features
.packet_support (PACKET_swbreak_feature
) == PACKET_ENABLE
);
11373 /* The to_stopped_by_hw_breakpoint method of target remote. */
11376 remote_target::stopped_by_hw_breakpoint ()
11378 struct thread_info
*thread
= inferior_thread ();
11380 return (thread
->priv
!= NULL
11381 && (get_remote_thread_info (thread
)->stop_reason
11382 == TARGET_STOPPED_BY_HW_BREAKPOINT
));
11385 /* The to_supports_stopped_by_hw_breakpoint method of target
11389 remote_target::supports_stopped_by_hw_breakpoint ()
11391 return (m_features
.packet_support (PACKET_hwbreak_feature
) == PACKET_ENABLE
);
11395 remote_target::stopped_by_watchpoint ()
11397 struct thread_info
*thread
= inferior_thread ();
11399 return (thread
->priv
!= NULL
11400 && (get_remote_thread_info (thread
)->stop_reason
11401 == TARGET_STOPPED_BY_WATCHPOINT
));
11405 remote_target::stopped_data_address (CORE_ADDR
*addr_p
)
11407 struct thread_info
*thread
= inferior_thread ();
11409 if (thread
->priv
!= NULL
11410 && (get_remote_thread_info (thread
)->stop_reason
11411 == TARGET_STOPPED_BY_WATCHPOINT
))
11413 *addr_p
= get_remote_thread_info (thread
)->watch_data_address
;
11422 remote_target::insert_hw_breakpoint (struct gdbarch
*gdbarch
,
11423 struct bp_target_info
*bp_tgt
)
11425 CORE_ADDR addr
= bp_tgt
->reqstd_address
;
11426 struct remote_state
*rs
;
11429 if (m_features
.packet_support (PACKET_Z1
) == PACKET_DISABLE
)
11432 /* Make sure the remote is pointing at the right process, if
11434 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
11435 set_general_process ();
11437 rs
= get_remote_state ();
11438 p
= rs
->buf
.data ();
11439 endbuf
= p
+ get_remote_packet_size ();
11445 addr
= remote_address_masked (addr
);
11446 p
+= hexnumstr (p
, (ULONGEST
) addr
);
11447 xsnprintf (p
, endbuf
- p
, ",%x", bp_tgt
->kind
);
11449 if (supports_evaluation_of_breakpoint_conditions ())
11450 remote_add_target_side_condition (gdbarch
, bp_tgt
, p
, endbuf
);
11452 if (can_run_breakpoint_commands ())
11453 remote_add_target_side_commands (gdbarch
, bp_tgt
, p
);
11458 packet_result result
= m_features
.packet_ok (rs
->buf
, PACKET_Z1
);
11459 switch (result
.status ())
11462 error (_("Remote failure reply: %s"), result
.err_msg ());
11463 case PACKET_UNKNOWN
:
11468 internal_error (_("remote_insert_hw_breakpoint: reached end of function"));
11473 remote_target::remove_hw_breakpoint (struct gdbarch
*gdbarch
,
11474 struct bp_target_info
*bp_tgt
)
11477 struct remote_state
*rs
= get_remote_state ();
11478 char *p
= rs
->buf
.data ();
11479 char *endbuf
= p
+ get_remote_packet_size ();
11481 if (m_features
.packet_support (PACKET_Z1
) == PACKET_DISABLE
)
11484 /* Make sure the remote is pointing at the right process, if
11486 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
11487 set_general_process ();
11493 addr
= remote_address_masked (bp_tgt
->placed_address
);
11494 p
+= hexnumstr (p
, (ULONGEST
) addr
);
11495 xsnprintf (p
, endbuf
- p
, ",%x", bp_tgt
->kind
);
11500 switch ((m_features
.packet_ok (rs
->buf
, PACKET_Z1
)).status ())
11503 case PACKET_UNKNOWN
:
11508 internal_error (_("remote_remove_hw_breakpoint: reached end of function"));
11511 /* Verify memory using the "qCRC:" request. */
11514 remote_target::verify_memory (const gdb_byte
*data
, CORE_ADDR lma
, ULONGEST size
)
11516 struct remote_state
*rs
= get_remote_state ();
11517 unsigned long host_crc
, target_crc
;
11520 /* It doesn't make sense to use qCRC if the remote target is
11521 connected but not running. */
11522 if (target_has_execution ()
11523 && m_features
.packet_support (PACKET_qCRC
) != PACKET_DISABLE
)
11525 enum packet_status status
;
11527 /* Make sure the remote is pointing at the right process. */
11528 set_general_process ();
11530 /* FIXME: assumes lma can fit into long. */
11531 xsnprintf (rs
->buf
.data (), get_remote_packet_size (), "qCRC:%lx,%lx",
11532 (long) lma
, (long) size
);
11535 /* Be clever; compute the host_crc before waiting for target
11537 host_crc
= xcrc32 (data
, size
, 0xffffffff);
11541 status
= (m_features
.packet_ok (rs
->buf
, PACKET_qCRC
)).status ();
11542 if (status
== PACKET_ERROR
)
11544 else if (status
== PACKET_OK
)
11546 for (target_crc
= 0, tmp
= &rs
->buf
[1]; *tmp
; tmp
++)
11547 target_crc
= target_crc
* 16 + fromhex (*tmp
);
11549 return (host_crc
== target_crc
);
11553 return simple_verify_memory (this, data
, lma
, size
);
11556 /* compare-sections command
11558 With no arguments, compares each loadable section in the exec bfd
11559 with the same memory range on the target, and reports mismatches.
11560 Useful for verifying the image on the target against the exec file. */
11563 compare_sections_command (const char *args
, int from_tty
)
11566 const char *sectname
;
11567 bfd_size_type size
;
11570 int mismatched
= 0;
11574 if (!current_program_space
->exec_bfd ())
11575 error (_("command cannot be used without an exec file"));
11577 if (args
!= NULL
&& strcmp (args
, "-r") == 0)
11583 for (s
= current_program_space
->exec_bfd ()->sections
; s
; s
= s
->next
)
11585 if (!(s
->flags
& SEC_LOAD
))
11586 continue; /* Skip non-loadable section. */
11588 if (read_only
&& (s
->flags
& SEC_READONLY
) == 0)
11589 continue; /* Skip writeable sections */
11591 size
= bfd_section_size (s
);
11593 continue; /* Skip zero-length section. */
11595 sectname
= bfd_section_name (s
);
11596 if (args
&& strcmp (args
, sectname
) != 0)
11597 continue; /* Not the section selected by user. */
11599 matched
= 1; /* Do this section. */
11602 gdb::byte_vector
sectdata (size
);
11603 bfd_get_section_contents (current_program_space
->exec_bfd (), s
,
11604 sectdata
.data (), 0, size
);
11606 res
= target_verify_memory (sectdata
.data (), lma
, size
);
11609 error (_("target memory fault, section %s, range %s -- %s"), sectname
,
11610 paddress (current_inferior ()->arch (), lma
),
11611 paddress (current_inferior ()->arch (), lma
+ size
));
11613 gdb_printf ("Section %s, range %s -- %s: ", sectname
,
11614 paddress (current_inferior ()->arch (), lma
),
11615 paddress (current_inferior ()->arch (), lma
+ size
));
11617 gdb_printf ("matched.\n");
11620 gdb_printf ("MIS-MATCHED!\n");
11624 if (mismatched
> 0)
11625 warning (_("One or more sections of the target image does "
11626 "not match the loaded file"));
11627 if (args
&& !matched
)
11628 gdb_printf (_("No loaded section named '%s'.\n"), args
);
11631 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
11632 into remote target. The number of bytes written to the remote
11633 target is returned, or -1 for error. */
11636 remote_target::remote_write_qxfer (const char *object_name
,
11637 const char *annex
, const gdb_byte
*writebuf
,
11638 ULONGEST offset
, LONGEST len
,
11639 ULONGEST
*xfered_len
,
11640 const unsigned int which_packet
)
11644 struct remote_state
*rs
= get_remote_state ();
11645 int max_size
= get_memory_write_packet_size ();
11647 if (m_features
.packet_support (which_packet
) == PACKET_DISABLE
)
11648 return TARGET_XFER_E_IO
;
11650 /* Insert header. */
11651 i
= snprintf (rs
->buf
.data (), max_size
,
11652 "qXfer:%s:write:%s:%s:",
11653 object_name
, annex
? annex
: "",
11655 max_size
-= (i
+ 1);
11657 /* Escape as much data as fits into rs->buf. */
11658 buf_len
= remote_escape_output
11659 (writebuf
, len
, 1, (gdb_byte
*) rs
->buf
.data () + i
, &max_size
, max_size
);
11661 if (putpkt_binary (rs
->buf
.data (), i
+ buf_len
) < 0
11662 || getpkt (&rs
->buf
) < 0
11663 || (m_features
.packet_ok (rs
->buf
, which_packet
)).status () != PACKET_OK
)
11664 return TARGET_XFER_E_IO
;
11666 unpack_varlen_hex (rs
->buf
.data (), &n
);
11669 return (*xfered_len
!= 0) ? TARGET_XFER_OK
: TARGET_XFER_EOF
;
11672 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
11673 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
11674 number of bytes read is returned, or 0 for EOF, or -1 for error.
11675 The number of bytes read may be less than LEN without indicating an
11676 EOF. PACKET is checked and updated to indicate whether the remote
11677 target supports this object. */
11680 remote_target::remote_read_qxfer (const char *object_name
,
11682 gdb_byte
*readbuf
, ULONGEST offset
,
11684 ULONGEST
*xfered_len
,
11685 const unsigned int which_packet
)
11687 struct remote_state
*rs
= get_remote_state ();
11688 LONGEST i
, n
, packet_len
;
11690 if (m_features
.packet_support (which_packet
) == PACKET_DISABLE
)
11691 return TARGET_XFER_E_IO
;
11693 /* Check whether we've cached an end-of-object packet that matches
11695 if (rs
->finished_object
)
11697 if (strcmp (object_name
, rs
->finished_object
) == 0
11698 && strcmp (annex
? annex
: "", rs
->finished_annex
) == 0
11699 && offset
== rs
->finished_offset
)
11700 return TARGET_XFER_EOF
;
11703 /* Otherwise, we're now reading something different. Discard
11705 xfree (rs
->finished_object
);
11706 xfree (rs
->finished_annex
);
11707 rs
->finished_object
= NULL
;
11708 rs
->finished_annex
= NULL
;
11711 /* Request only enough to fit in a single packet. The actual data
11712 may not, since we don't know how much of it will need to be escaped;
11713 the target is free to respond with slightly less data. We subtract
11714 five to account for the response type and the protocol frame. */
11715 n
= std::min
<LONGEST
> (get_remote_packet_size () - 5, len
);
11716 snprintf (rs
->buf
.data (), get_remote_packet_size () - 4,
11717 "qXfer:%s:read:%s:%s,%s",
11718 object_name
, annex
? annex
: "",
11721 i
= putpkt (rs
->buf
);
11723 return TARGET_XFER_E_IO
;
11726 packet_len
= getpkt (&rs
->buf
);
11728 || m_features
.packet_ok (rs
->buf
, which_packet
).status () != PACKET_OK
)
11729 return TARGET_XFER_E_IO
;
11731 if (rs
->buf
[0] != 'l' && rs
->buf
[0] != 'm')
11732 error (_("Unknown remote qXfer reply: %s"), rs
->buf
.data ());
11734 /* 'm' means there is (or at least might be) more data after this
11735 batch. That does not make sense unless there's at least one byte
11736 of data in this reply. */
11737 if (rs
->buf
[0] == 'm' && packet_len
== 1)
11738 error (_("Remote qXfer reply contained no data."));
11740 /* Got some data. */
11741 i
= remote_unescape_input ((gdb_byte
*) rs
->buf
.data () + 1,
11742 packet_len
- 1, readbuf
, n
);
11744 /* 'l' is an EOF marker, possibly including a final block of data,
11745 or possibly empty. If we have the final block of a non-empty
11746 object, record this fact to bypass a subsequent partial read. */
11747 if (rs
->buf
[0] == 'l' && offset
+ i
> 0)
11749 rs
->finished_object
= xstrdup (object_name
);
11750 rs
->finished_annex
= xstrdup (annex
? annex
: "");
11751 rs
->finished_offset
= offset
+ i
;
11755 return TARGET_XFER_EOF
;
11759 return TARGET_XFER_OK
;
11763 enum target_xfer_status
11764 remote_target::xfer_partial (enum target_object object
,
11765 const char *annex
, gdb_byte
*readbuf
,
11766 const gdb_byte
*writebuf
, ULONGEST offset
, ULONGEST len
,
11767 ULONGEST
*xfered_len
)
11769 struct remote_state
*rs
;
11774 = gdbarch_addressable_memory_unit_size (current_inferior ()->arch ());
11776 set_remote_traceframe ();
11777 set_general_thread (inferior_ptid
);
11779 rs
= get_remote_state ();
11781 /* Handle memory using the standard memory routines. */
11782 if (object
== TARGET_OBJECT_MEMORY
)
11784 /* If the remote target is connected but not running, we should
11785 pass this request down to a lower stratum (e.g. the executable
11787 if (!target_has_execution ())
11788 return TARGET_XFER_EOF
;
11790 if (writebuf
!= NULL
)
11791 return remote_write_bytes (offset
, writebuf
, len
, unit_size
,
11794 return remote_read_bytes (offset
, readbuf
, len
, unit_size
,
11798 /* Handle extra signal info using qxfer packets. */
11799 if (object
== TARGET_OBJECT_SIGNAL_INFO
)
11802 return remote_read_qxfer ("siginfo", annex
, readbuf
, offset
, len
,
11803 xfered_len
, PACKET_qXfer_siginfo_read
);
11805 return remote_write_qxfer ("siginfo", annex
, writebuf
, offset
, len
,
11806 xfered_len
, PACKET_qXfer_siginfo_write
);
11809 if (object
== TARGET_OBJECT_STATIC_TRACE_DATA
)
11812 return remote_read_qxfer ("statictrace", annex
,
11813 readbuf
, offset
, len
, xfered_len
,
11814 PACKET_qXfer_statictrace_read
);
11816 return TARGET_XFER_E_IO
;
11819 /* Only handle flash writes. */
11820 if (writebuf
!= NULL
)
11824 case TARGET_OBJECT_FLASH
:
11825 return remote_flash_write (offset
, len
, xfered_len
,
11829 return TARGET_XFER_E_IO
;
11833 /* Map pre-existing objects onto letters. DO NOT do this for new
11834 objects!!! Instead specify new query packets. */
11837 case TARGET_OBJECT_AVR
:
11841 case TARGET_OBJECT_AUXV
:
11842 gdb_assert (annex
== NULL
);
11843 return remote_read_qxfer
11844 ("auxv", annex
, readbuf
, offset
, len
, xfered_len
, PACKET_qXfer_auxv
);
11846 case TARGET_OBJECT_AVAILABLE_FEATURES
:
11847 return remote_read_qxfer
11848 ("features", annex
, readbuf
, offset
, len
, xfered_len
,
11849 PACKET_qXfer_features
);
11851 case TARGET_OBJECT_LIBRARIES
:
11852 return remote_read_qxfer
11853 ("libraries", annex
, readbuf
, offset
, len
, xfered_len
,
11854 PACKET_qXfer_libraries
);
11856 case TARGET_OBJECT_LIBRARIES_SVR4
:
11857 return remote_read_qxfer
11858 ("libraries-svr4", annex
, readbuf
, offset
, len
, xfered_len
,
11859 PACKET_qXfer_libraries_svr4
);
11861 case TARGET_OBJECT_MEMORY_MAP
:
11862 gdb_assert (annex
== NULL
);
11863 return remote_read_qxfer
11864 ("memory-map", annex
, readbuf
, offset
, len
, xfered_len
,
11865 PACKET_qXfer_memory_map
);
11867 case TARGET_OBJECT_OSDATA
:
11868 /* Should only get here if we're connected. */
11869 gdb_assert (rs
->remote_desc
);
11870 return remote_read_qxfer
11871 ("osdata", annex
, readbuf
, offset
, len
, xfered_len
,
11872 PACKET_qXfer_osdata
);
11874 case TARGET_OBJECT_THREADS
:
11875 gdb_assert (annex
== NULL
);
11876 return remote_read_qxfer
11877 ("threads", annex
, readbuf
, offset
, len
, xfered_len
,
11878 PACKET_qXfer_threads
);
11880 case TARGET_OBJECT_TRACEFRAME_INFO
:
11881 gdb_assert (annex
== NULL
);
11882 return remote_read_qxfer
11883 ("traceframe-info", annex
, readbuf
, offset
, len
, xfered_len
,
11884 PACKET_qXfer_traceframe_info
);
11886 case TARGET_OBJECT_FDPIC
:
11887 return remote_read_qxfer
11888 ("fdpic", annex
, readbuf
, offset
, len
, xfered_len
, PACKET_qXfer_fdpic
);
11890 case TARGET_OBJECT_OPENVMS_UIB
:
11891 return remote_read_qxfer
11892 ("uib", annex
, readbuf
, offset
, len
, xfered_len
, PACKET_qXfer_uib
);
11894 case TARGET_OBJECT_BTRACE
:
11895 return remote_read_qxfer
11896 ("btrace", annex
, readbuf
, offset
, len
, xfered_len
,
11897 PACKET_qXfer_btrace
);
11899 case TARGET_OBJECT_BTRACE_CONF
:
11900 return remote_read_qxfer
11901 ("btrace-conf", annex
, readbuf
, offset
, len
, xfered_len
,
11902 PACKET_qXfer_btrace_conf
);
11904 case TARGET_OBJECT_EXEC_FILE
:
11905 return remote_read_qxfer
11906 ("exec-file", annex
, readbuf
, offset
, len
, xfered_len
,
11907 PACKET_qXfer_exec_file
);
11910 return TARGET_XFER_E_IO
;
11913 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
11914 large enough let the caller deal with it. */
11915 if (len
< get_remote_packet_size ())
11916 return TARGET_XFER_E_IO
;
11917 len
= get_remote_packet_size ();
11919 /* Except for querying the minimum buffer size, target must be open. */
11920 if (!rs
->remote_desc
)
11921 error (_("remote query is only available after target open"));
11923 gdb_assert (annex
!= NULL
);
11924 gdb_assert (readbuf
!= NULL
);
11926 p2
= rs
->buf
.data ();
11928 *p2
++ = query_type
;
11930 /* We used one buffer char for the remote protocol q command and
11931 another for the query type. As the remote protocol encapsulation
11932 uses 4 chars plus one extra in case we are debugging
11933 (remote_debug), we have PBUFZIZ - 7 left to pack the query
11936 while (annex
[i
] && (i
< (get_remote_packet_size () - 8)))
11938 /* Bad caller may have sent forbidden characters. */
11939 gdb_assert (isprint (annex
[i
]) && annex
[i
] != '$' && annex
[i
] != '#');
11944 gdb_assert (annex
[i
] == '\0');
11946 i
= putpkt (rs
->buf
);
11948 return TARGET_XFER_E_IO
;
11951 strcpy ((char *) readbuf
, rs
->buf
.data ());
11953 *xfered_len
= strlen ((char *) readbuf
);
11954 return (*xfered_len
!= 0) ? TARGET_XFER_OK
: TARGET_XFER_EOF
;
11957 /* Implementation of to_get_memory_xfer_limit. */
11960 remote_target::get_memory_xfer_limit ()
11962 return get_memory_write_packet_size ();
11966 remote_target::search_memory (CORE_ADDR start_addr
, ULONGEST search_space_len
,
11967 const gdb_byte
*pattern
, ULONGEST pattern_len
,
11968 CORE_ADDR
*found_addrp
)
11970 int addr_size
= gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
11971 struct remote_state
*rs
= get_remote_state ();
11972 int max_size
= get_memory_write_packet_size ();
11974 /* Number of packet bytes used to encode the pattern;
11975 this could be more than PATTERN_LEN due to escape characters. */
11976 int escaped_pattern_len
;
11977 /* Amount of pattern that was encodable in the packet. */
11978 int used_pattern_len
;
11981 ULONGEST found_addr
;
11983 auto read_memory
= [this] (CORE_ADDR addr
, gdb_byte
*result
, size_t len
)
11985 return (target_read (this, TARGET_OBJECT_MEMORY
, NULL
, result
, addr
, len
)
11989 /* Don't go to the target if we don't have to. This is done before
11990 checking packet_support to avoid the possibility that a success for this
11991 edge case means the facility works in general. */
11992 if (pattern_len
> search_space_len
)
11994 if (pattern_len
== 0)
11996 *found_addrp
= start_addr
;
12000 /* If we already know the packet isn't supported, fall back to the simple
12001 way of searching memory. */
12003 if (m_features
.packet_support (PACKET_qSearch_memory
) == PACKET_DISABLE
)
12005 /* Target doesn't provided special support, fall back and use the
12006 standard support (copy memory and do the search here). */
12007 return simple_search_memory (read_memory
, start_addr
, search_space_len
,
12008 pattern
, pattern_len
, found_addrp
);
12011 /* Make sure the remote is pointing at the right process. */
12012 set_general_process ();
12014 /* Insert header. */
12015 i
= snprintf (rs
->buf
.data (), max_size
,
12016 "qSearch:memory:%s;%s;",
12017 phex_nz (start_addr
, addr_size
),
12018 phex_nz (search_space_len
));
12019 max_size
-= (i
+ 1);
12021 /* Escape as much data as fits into rs->buf. */
12022 escaped_pattern_len
=
12023 remote_escape_output (pattern
, pattern_len
, 1,
12024 (gdb_byte
*) rs
->buf
.data () + i
,
12025 &used_pattern_len
, max_size
);
12027 /* Bail if the pattern is too large. */
12028 if (used_pattern_len
!= pattern_len
)
12029 error (_("Pattern is too large to transmit to remote target."));
12031 if (putpkt_binary (rs
->buf
.data (), i
+ escaped_pattern_len
) < 0
12032 || getpkt (&rs
->buf
) < 0
12033 || m_features
.packet_ok (rs
->buf
, PACKET_qSearch_memory
).status ()
12036 /* The request may not have worked because the command is not
12037 supported. If so, fall back to the simple way. */
12038 if (m_features
.packet_support (PACKET_qSearch_memory
) == PACKET_DISABLE
)
12040 return simple_search_memory (read_memory
, start_addr
, search_space_len
,
12041 pattern
, pattern_len
, found_addrp
);
12046 if (rs
->buf
[0] == '0')
12048 else if (rs
->buf
[0] == '1')
12051 if (rs
->buf
[1] != ',')
12052 error (_("Unknown qSearch:memory reply: %s"), rs
->buf
.data ());
12053 unpack_varlen_hex (&rs
->buf
[2], &found_addr
);
12054 *found_addrp
= found_addr
;
12057 error (_("Unknown qSearch:memory reply: %s"), rs
->buf
.data ());
12063 remote_target::rcmd (const char *command
, struct ui_file
*outbuf
)
12065 struct remote_state
*rs
= get_remote_state ();
12066 char *p
= rs
->buf
.data ();
12068 if (!rs
->remote_desc
)
12069 error (_("remote rcmd is only available after target open"));
12071 /* Send a NULL command across as an empty command. */
12072 if (command
== NULL
)
12075 /* It might be important for this command to know the current thread. */
12076 set_general_thread (inferior_ptid
);
12078 /* The query prefix. */
12079 strcpy (rs
->buf
.data (), "qRcmd,");
12080 p
= strchr (rs
->buf
.data (), '\0');
12082 if ((strlen (rs
->buf
.data ()) + strlen (command
) * 2 + 8/*misc*/)
12083 > get_remote_packet_size ())
12084 error (_("\"monitor\" command ``%s'' is too long."), command
);
12086 /* Encode the actual command. */
12087 bin2hex ((const gdb_byte
*) command
, p
, strlen (command
));
12089 if (putpkt (rs
->buf
) < 0)
12090 error (_("Communication problem with target."));
12092 /* get/display the response */
12097 /* XXX - see also remote_get_noisy_reply(). */
12098 QUIT
; /* Allow user to bail out with ^C. */
12100 if (getpkt (&rs
->buf
) == -1)
12102 /* Timeout. Continue to (try to) read responses.
12103 This is better than stopping with an error, assuming the stub
12104 is still executing the (long) monitor command.
12105 If needed, the user can interrupt gdb using C-c, obtaining
12106 an effect similar to stop on timeout. */
12109 buf
= rs
->buf
.data ();
12110 if (buf
[0] == 'O' && buf
[1] != 'K')
12112 /* 'O' message from stub. */
12113 remote_console_output (buf
+ 1, outbuf
);
12116 packet_result result
= packet_check_result (buf
);
12117 switch (result
.status ())
12119 case PACKET_UNKNOWN
:
12120 error (_("Target does not support this command."));
12122 error (_("Protocol error with Rcmd: %s."), result
.err_msg ());
12127 if (strcmp (buf
, "OK") != 0)
12129 for (p
= buf
; p
[0] != '\0' && p
[1] != '\0'; p
+= 2)
12131 char c
= (fromhex (p
[0]) << 4) + fromhex (p
[1]);
12132 gdb_putc (c
, outbuf
);
12139 std::vector
<mem_region
>
12140 remote_target::memory_map ()
12142 std::vector
<mem_region
> result
;
12143 std::optional
<gdb::char_vector
> text
12144 = target_read_stralloc (current_inferior ()->top_target (),
12145 TARGET_OBJECT_MEMORY_MAP
, NULL
);
12148 result
= parse_memory_map (text
->data ());
12153 /* Set of callbacks used to implement the 'maint packet' command. */
12155 struct cli_packet_command_callbacks
: public send_remote_packet_callbacks
12157 /* Called before the packet is sent. BUF is the packet content before
12158 the protocol specific prefix, suffix, and escaping is added. */
12160 void sending (gdb::array_view
<const char> &buf
) override
12162 gdb_puts ("sending: ");
12163 print_packet (buf
);
12167 /* Called with BUF, the reply from the remote target. */
12169 void received (gdb::array_view
<const char> &buf
) override
12171 gdb_puts ("received: \"");
12172 print_packet (buf
);
12178 /* Print BUF o gdb_stdout. Any non-printable bytes in BUF are printed as
12179 '\x??' with '??' replaced by the hexadecimal value of the byte. */
12182 print_packet (gdb::array_view
<const char> &buf
)
12186 for (int i
= 0; i
< buf
.size (); ++i
)
12188 gdb_byte c
= buf
[i
];
12190 gdb_putc (c
, &stb
);
12192 gdb_printf (&stb
, "\\x%02x", (unsigned char) c
);
12195 gdb_puts (stb
.string ().c_str ());
12199 /* See remote.h. */
12202 send_remote_packet (gdb::array_view
<const char> &buf
,
12203 send_remote_packet_callbacks
*callbacks
)
12205 if (buf
.size () == 0 || buf
.data ()[0] == '\0')
12206 error (_("a remote packet must not be empty"));
12208 remote_target
*remote
= get_current_remote_target ();
12209 if (remote
== nullptr)
12210 error (_("packets can only be sent to a remote target"));
12212 callbacks
->sending (buf
);
12214 remote
->putpkt_binary (buf
.data (), buf
.size ());
12215 remote_state
*rs
= remote
->get_remote_state ();
12216 int bytes
= remote
->getpkt (&rs
->buf
);
12219 error (_("error while fetching packet from remote target"));
12221 gdb::array_view
<const char> view (&rs
->buf
[0], bytes
);
12222 callbacks
->received (view
);
12225 /* Entry point for the 'maint packet' command. */
12228 cli_packet_command (const char *args
, int from_tty
)
12230 cli_packet_command_callbacks cb
;
12231 gdb::array_view
<const char> view
12232 = gdb::make_array_view (args
, args
== nullptr ? 0 : strlen (args
));
12233 send_remote_packet (view
, &cb
);
12237 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
12239 static void display_thread_info (struct gdb_ext_thread_info
*info
);
12241 static void threadset_test_cmd (char *cmd
, int tty
);
12243 static void threadalive_test (char *cmd
, int tty
);
12245 static void threadlist_test_cmd (char *cmd
, int tty
);
12247 int get_and_display_threadinfo (threadref
*ref
);
12249 static void threadinfo_test_cmd (char *cmd
, int tty
);
12251 static int thread_display_step (threadref
*ref
, void *context
);
12253 static void threadlist_update_test_cmd (char *cmd
, int tty
);
12255 static void init_remote_threadtests (void);
12257 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
12260 threadset_test_cmd (const char *cmd
, int tty
)
12262 int sample_thread
= SAMPLE_THREAD
;
12264 gdb_printf (_("Remote threadset test\n"));
12265 set_general_thread (sample_thread
);
12270 threadalive_test (const char *cmd
, int tty
)
12272 int sample_thread
= SAMPLE_THREAD
;
12273 int pid
= inferior_ptid
.pid ();
12274 ptid_t ptid
= ptid_t (pid
, sample_thread
, 0);
12276 if (remote_thread_alive (ptid
))
12277 gdb_printf ("PASS: Thread alive test\n");
12279 gdb_printf ("FAIL: Thread alive test\n");
12282 void output_threadid (char *title
, threadref
*ref
);
12285 output_threadid (char *title
, threadref
*ref
)
12289 pack_threadid (&hexid
[0], ref
); /* Convert thread id into hex. */
12291 gdb_printf ("%s %s\n", title
, (&hexid
[0]));
12295 threadlist_test_cmd (const char *cmd
, int tty
)
12298 threadref nextthread
;
12299 int done
, result_count
;
12300 threadref threadlist
[3];
12302 gdb_printf ("Remote Threadlist test\n");
12303 if (!remote_get_threadlist (startflag
, &nextthread
, 3, &done
,
12304 &result_count
, &threadlist
[0]))
12305 gdb_printf ("FAIL: threadlist test\n");
12308 threadref
*scan
= threadlist
;
12309 threadref
*limit
= scan
+ result_count
;
12311 while (scan
< limit
)
12312 output_threadid (" thread ", scan
++);
12317 display_thread_info (struct gdb_ext_thread_info
*info
)
12319 output_threadid ("Threadid: ", &info
->threadid
);
12320 gdb_printf ("Name: %s\n ", info
->shortname
);
12321 gdb_printf ("State: %s\n", info
->display
);
12322 gdb_printf ("other: %s\n\n", info
->more_display
);
12326 get_and_display_threadinfo (threadref
*ref
)
12330 struct gdb_ext_thread_info threadinfo
;
12332 set
= TAG_THREADID
| TAG_EXISTS
| TAG_THREADNAME
12333 | TAG_MOREDISPLAY
| TAG_DISPLAY
;
12334 if (0 != (result
= remote_get_threadinfo (ref
, set
, &threadinfo
)))
12335 display_thread_info (&threadinfo
);
12340 threadinfo_test_cmd (const char *cmd
, int tty
)
12342 int athread
= SAMPLE_THREAD
;
12346 int_to_threadref (&thread
, athread
);
12347 gdb_printf ("Remote Threadinfo test\n");
12348 if (!get_and_display_threadinfo (&thread
))
12349 gdb_printf ("FAIL cannot get thread info\n");
12353 thread_display_step (threadref
*ref
, void *context
)
12355 /* output_threadid(" threadstep ",ref); *//* simple test */
12356 return get_and_display_threadinfo (ref
);
12360 threadlist_update_test_cmd (const char *cmd
, int tty
)
12362 gdb_printf ("Remote Threadlist update test\n");
12363 remote_threadlist_iterator (thread_display_step
, 0, CRAZY_MAX_THREADS
);
12367 init_remote_threadtests (void)
12369 add_com ("tlist", class_obscure
, threadlist_test_cmd
,
12370 _("Fetch and print the remote list of "
12371 "thread identifiers, one pkt only."));
12372 add_com ("tinfo", class_obscure
, threadinfo_test_cmd
,
12373 _("Fetch and display info about one thread."));
12374 add_com ("tset", class_obscure
, threadset_test_cmd
,
12375 _("Test setting to a different thread."));
12376 add_com ("tupd", class_obscure
, threadlist_update_test_cmd
,
12377 _("Iterate through updating all remote thread info."));
12378 add_com ("talive", class_obscure
, threadalive_test
,
12379 _("Remote thread alive test."));
12384 /* Convert a thread ID to a string. */
12387 remote_target::pid_to_str (ptid_t ptid
)
12389 if (ptid
== null_ptid
)
12390 return normal_pid_to_str (ptid
);
12391 else if (ptid
.is_pid ())
12393 /* Printing an inferior target id. */
12395 /* When multi-process extensions are off, there's no way in the
12396 remote protocol to know the remote process id, if there's any
12397 at all. There's one exception --- when we're connected with
12398 target extended-remote, and we manually attached to a process
12399 with "attach PID". We don't record anywhere a flag that
12400 allows us to distinguish that case from the case of
12401 connecting with extended-remote and the stub already being
12402 attached to a process, and reporting yes to qAttached, hence
12403 no smart special casing here. */
12404 if (!m_features
.remote_multi_process_p ())
12405 return "Remote target";
12407 return normal_pid_to_str (ptid
);
12411 if (magic_null_ptid
== ptid
)
12412 return "Thread <main>";
12414 thread_info
*thread
= this->find_thread (ptid
);
12415 if ((thread
!= nullptr) && (thread
->priv
!= nullptr))
12417 remote_thread_info
*priv
= get_remote_thread_info (thread
);
12418 if (!priv
->id_str
.empty ())
12419 return priv
->id_str
;
12422 if (m_features
.remote_multi_process_p ())
12423 if (ptid
.lwp () == 0)
12424 return normal_pid_to_str (ptid
);
12426 return string_printf ("Thread %d.%ld",
12427 ptid
.pid (), ptid
.lwp ());
12429 return string_printf ("Thread %ld", ptid
.lwp ());
12433 /* Get the address of the thread local variable in OBJFILE which is
12434 stored at OFFSET within the thread local storage for thread PTID. */
12437 remote_target::get_thread_local_address (ptid_t ptid
, CORE_ADDR lm
,
12440 if (m_features
.packet_support (PACKET_qGetTLSAddr
) != PACKET_DISABLE
)
12442 struct remote_state
*rs
= get_remote_state ();
12443 char *p
= rs
->buf
.data ();
12444 char *endp
= p
+ get_remote_packet_size ();
12446 strcpy (p
, "qGetTLSAddr:");
12448 p
= write_ptid (p
, endp
, ptid
);
12450 p
+= hexnumstr (p
, offset
);
12452 p
+= hexnumstr (p
, lm
);
12457 packet_result result
= m_features
.packet_ok (rs
->buf
, PACKET_qGetTLSAddr
);
12458 if (result
.status () == PACKET_OK
)
12462 unpack_varlen_hex (rs
->buf
.data (), &addr
);
12465 else if (result
.status () == PACKET_UNKNOWN
)
12466 throw_error (TLS_GENERIC_ERROR
,
12467 _("Remote target doesn't support qGetTLSAddr packet"));
12469 throw_error (TLS_GENERIC_ERROR
,
12470 _("Remote target failed to process qGetTLSAddr request"));
12473 throw_error (TLS_GENERIC_ERROR
,
12474 _("TLS not supported or disabled on this target"));
12480 remote_target::get_tib_address (ptid_t ptid
, CORE_ADDR
*addr
)
12482 if (m_features
.packet_support (PACKET_qGetTIBAddr
) != PACKET_DISABLE
)
12484 struct remote_state
*rs
= get_remote_state ();
12485 char *p
= rs
->buf
.data ();
12486 char *endp
= p
+ get_remote_packet_size ();
12488 strcpy (p
, "qGetTIBAddr:");
12490 p
= write_ptid (p
, endp
, ptid
);
12495 packet_result result
= m_features
.packet_ok (rs
->buf
, PACKET_qGetTIBAddr
);
12496 if (result
.status () == PACKET_OK
)
12499 unpack_varlen_hex (rs
->buf
.data (), &val
);
12501 *addr
= (CORE_ADDR
) val
;
12504 else if (result
.status () == PACKET_UNKNOWN
)
12507 error (_("Remote target failed to process qGetTIBAddr request, %s"),
12508 result
.err_msg ());
12514 /* Support for inferring a target description based on the current
12515 architecture and the size of a 'g' packet. While the 'g' packet
12516 can have any size (since optional registers can be left off the
12517 end), some sizes are easily recognizable given knowledge of the
12518 approximate architecture. */
12520 struct remote_g_packet_guess
12522 remote_g_packet_guess (int bytes_
, const struct target_desc
*tdesc_
)
12529 const struct target_desc
*tdesc
;
12532 struct remote_g_packet_data
12534 std::vector
<remote_g_packet_guess
> guesses
;
12537 static const registry
<gdbarch
>::key
<struct remote_g_packet_data
>
12538 remote_g_packet_data_handle
;
12540 static struct remote_g_packet_data
*
12541 get_g_packet_data (struct gdbarch
*gdbarch
)
12543 struct remote_g_packet_data
*data
12544 = remote_g_packet_data_handle
.get (gdbarch
);
12545 if (data
== nullptr)
12546 data
= remote_g_packet_data_handle
.emplace (gdbarch
);
12551 register_remote_g_packet_guess (struct gdbarch
*gdbarch
, int bytes
,
12552 const struct target_desc
*tdesc
)
12554 struct remote_g_packet_data
*data
= get_g_packet_data (gdbarch
);
12556 gdb_assert (tdesc
!= NULL
);
12558 for (const remote_g_packet_guess
&guess
: data
->guesses
)
12559 if (guess
.bytes
== bytes
)
12560 internal_error (_("Duplicate g packet description added for size %d"),
12563 data
->guesses
.emplace_back (bytes
, tdesc
);
12566 /* Return true if remote_read_description would do anything on this target
12567 and architecture, false otherwise. */
12570 remote_read_description_p (struct target_ops
*target
)
12572 remote_g_packet_data
*data
= get_g_packet_data (current_inferior ()->arch ());
12574 return !data
->guesses
.empty ();
12577 const struct target_desc
*
12578 remote_target::read_description ()
12580 remote_g_packet_data
*data
= get_g_packet_data (current_inferior ()->arch ());
12582 /* Do not try this during initial connection, when we do not know
12583 whether there is a running but stopped thread. */
12584 if (!target_has_execution () || inferior_ptid
== null_ptid
)
12585 return beneath ()->read_description ();
12587 if (!data
->guesses
.empty ())
12589 int bytes
= send_g_packet ();
12591 for (const remote_g_packet_guess
&guess
: data
->guesses
)
12592 if (guess
.bytes
== bytes
)
12593 return guess
.tdesc
;
12595 /* We discard the g packet. A minor optimization would be to
12596 hold on to it, and fill the register cache once we have selected
12597 an architecture, but it's too tricky to do safely. */
12600 return beneath ()->read_description ();
12603 /* Remote file transfer support. This is host-initiated I/O, not
12604 target-initiated; for target-initiated, see remote-fileio.c. */
12606 /* If *LEFT is at least the length of STRING, copy STRING to
12607 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12608 decrease *LEFT. Otherwise raise an error. */
12611 remote_buffer_add_string (char **buffer
, int *left
, const char *string
)
12613 int len
= strlen (string
);
12616 error (_("Packet too long for target."));
12618 memcpy (*buffer
, string
, len
);
12622 /* NUL-terminate the buffer as a convenience, if there is
12628 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
12629 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12630 decrease *LEFT. Otherwise raise an error. */
12633 remote_buffer_add_bytes (char **buffer
, int *left
, const gdb_byte
*bytes
,
12636 if (2 * len
> *left
)
12637 error (_("Packet too long for target."));
12639 bin2hex (bytes
, *buffer
, len
);
12640 *buffer
+= 2 * len
;
12643 /* NUL-terminate the buffer as a convenience, if there is
12649 /* If *LEFT is large enough, convert VALUE to hex and add it to
12650 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12651 decrease *LEFT. Otherwise raise an error. */
12654 remote_buffer_add_int (char **buffer
, int *left
, ULONGEST value
)
12656 int len
= hexnumlen (value
);
12659 error (_("Packet too long for target."));
12661 hexnumstr (*buffer
, value
);
12665 /* NUL-terminate the buffer as a convenience, if there is
12671 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
12672 value, *REMOTE_ERRNO to the remote error number or FILEIO_SUCCESS if none
12673 was included, and *ATTACHMENT to point to the start of the annex
12674 if any. The length of the packet isn't needed here; there may
12675 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
12677 Return 0 if the packet could be parsed, -1 if it could not. If
12678 -1 is returned, the other variables may not be initialized. */
12681 remote_hostio_parse_result (const char *buffer
, int *retcode
,
12682 fileio_error
*remote_errno
, const char **attachment
)
12686 *remote_errno
= FILEIO_SUCCESS
;
12687 *attachment
= NULL
;
12689 if (buffer
[0] != 'F')
12693 *retcode
= strtol (&buffer
[1], &p
, 16);
12694 if (errno
!= 0 || p
== &buffer
[1])
12697 /* Check for ",errno". */
12701 *remote_errno
= (fileio_error
) strtol (p
+ 1, &p2
, 16);
12702 if (errno
!= 0 || p
+ 1 == p2
)
12707 /* Check for ";attachment". If there is no attachment, the
12708 packet should end here. */
12711 *attachment
= p
+ 1;
12714 else if (*p
== '\0')
12720 /* Send a prepared I/O packet to the target and read its response.
12721 The prepared packet is in the global RS->BUF before this function
12722 is called, and the answer is there when we return.
12724 COMMAND_BYTES is the length of the request to send, which may include
12725 binary data. WHICH_PACKET is the packet configuration to check
12726 before attempting a packet. If an error occurs, *REMOTE_ERRNO
12727 is set to the error number and -1 is returned. Otherwise the value
12728 returned by the function is returned.
12730 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
12731 attachment is expected; an error will be reported if there's a
12732 mismatch. If one is found, *ATTACHMENT will be set to point into
12733 the packet buffer and *ATTACHMENT_LEN will be set to the
12734 attachment's length. */
12737 remote_target::remote_hostio_send_command (int command_bytes
, int which_packet
,
12738 fileio_error
*remote_errno
, const char **attachment
,
12739 int *attachment_len
)
12741 struct remote_state
*rs
= get_remote_state ();
12742 int ret
, bytes_read
;
12743 const char *attachment_tmp
;
12745 if (m_features
.packet_support (which_packet
) == PACKET_DISABLE
)
12747 *remote_errno
= FILEIO_ENOSYS
;
12751 putpkt_binary (rs
->buf
.data (), command_bytes
);
12752 bytes_read
= getpkt (&rs
->buf
);
12754 /* If it timed out, something is wrong. Don't try to parse the
12756 if (bytes_read
< 0)
12758 *remote_errno
= FILEIO_EINVAL
;
12762 switch (m_features
.packet_ok (rs
->buf
, which_packet
).status ())
12765 *remote_errno
= FILEIO_EINVAL
;
12767 case PACKET_UNKNOWN
:
12768 *remote_errno
= FILEIO_ENOSYS
;
12774 if (remote_hostio_parse_result (rs
->buf
.data (), &ret
, remote_errno
,
12777 *remote_errno
= FILEIO_EINVAL
;
12781 if (*remote_errno
!= FILEIO_SUCCESS
)
12784 /* Make sure we saw an attachment if and only if we expected one. */
12785 if ((attachment_tmp
== NULL
&& attachment
!= NULL
)
12786 || (attachment_tmp
!= NULL
&& attachment
== NULL
))
12788 *remote_errno
= FILEIO_EINVAL
;
12792 /* If an attachment was found, it must point into the packet buffer;
12793 work out how many bytes there were. */
12794 if (attachment_tmp
!= NULL
)
12796 *attachment
= attachment_tmp
;
12797 *attachment_len
= bytes_read
- (*attachment
- rs
->buf
.data ());
12803 /* See declaration.h. */
12806 readahead_cache::invalidate ()
12811 /* See declaration.h. */
12814 readahead_cache::invalidate_fd (int fd
)
12816 if (this->fd
== fd
)
12820 /* Set the filesystem remote_hostio functions that take FILENAME
12821 arguments will use. Return 0 on success, or -1 if an error
12822 occurs (and set *REMOTE_ERRNO). */
12825 remote_target::remote_hostio_set_filesystem (struct inferior
*inf
,
12826 fileio_error
*remote_errno
)
12828 struct remote_state
*rs
= get_remote_state ();
12829 int required_pid
= (inf
== NULL
|| inf
->fake_pid_p
) ? 0 : inf
->pid
;
12830 char *p
= rs
->buf
.data ();
12831 int left
= get_remote_packet_size () - 1;
12835 if (m_features
.packet_support (PACKET_vFile_setfs
) == PACKET_DISABLE
)
12838 if (rs
->fs_pid
!= -1 && required_pid
== rs
->fs_pid
)
12841 remote_buffer_add_string (&p
, &left
, "vFile:setfs:");
12843 xsnprintf (arg
, sizeof (arg
), "%x", required_pid
);
12844 remote_buffer_add_string (&p
, &left
, arg
);
12846 ret
= remote_hostio_send_command (p
- rs
->buf
.data (), PACKET_vFile_setfs
,
12847 remote_errno
, NULL
, NULL
);
12849 if (m_features
.packet_support (PACKET_vFile_setfs
) == PACKET_DISABLE
)
12853 rs
->fs_pid
= required_pid
;
12858 /* Implementation of to_fileio_open. */
12861 remote_target::remote_hostio_open (inferior
*inf
, const char *filename
,
12862 int flags
, int mode
, int warn_if_slow
,
12863 fileio_error
*remote_errno
)
12865 struct remote_state
*rs
= get_remote_state ();
12866 char *p
= rs
->buf
.data ();
12867 int left
= get_remote_packet_size () - 1;
12869 if (remote_hostio_set_filesystem (inf
, remote_errno
) != 0)
12872 remote_buffer_add_string (&p
, &left
, "vFile:open:");
12874 remote_buffer_add_bytes (&p
, &left
, (const gdb_byte
*) filename
,
12875 strlen (filename
));
12876 remote_buffer_add_string (&p
, &left
, ",");
12878 remote_buffer_add_int (&p
, &left
, flags
);
12879 remote_buffer_add_string (&p
, &left
, ",");
12881 remote_buffer_add_int (&p
, &left
, mode
);
12883 int res
= remote_hostio_send_command (p
- rs
->buf
.data (), PACKET_vFile_open
,
12884 remote_errno
, nullptr, nullptr);
12886 if (warn_if_slow
&& res
!= -1)
12888 static int warning_issued
= 0;
12890 gdb_printf (_("Reading %ps from remote target...\n"),
12891 styled_string (file_name_style
.style (), filename
));
12893 if (!warning_issued
)
12895 warning (_("File transfers from remote targets can be slow."
12896 " Use \"%ps\" to access files locally"
12898 styled_string (command_style
.style (), "set sysroot"));
12899 warning_issued
= 1;
12907 remote_target::fileio_open (struct inferior
*inf
, const char *filename
,
12908 int flags
, int mode
, int warn_if_slow
,
12909 fileio_error
*remote_errno
)
12911 return remote_hostio_open (inf
, filename
, flags
, mode
, warn_if_slow
,
12915 /* Implementation of to_fileio_pwrite. */
12918 remote_target::remote_hostio_pwrite (int fd
, const gdb_byte
*write_buf
, int len
,
12919 ULONGEST offset
, fileio_error
*remote_errno
)
12921 struct remote_state
*rs
= get_remote_state ();
12922 char *p
= rs
->buf
.data ();
12923 int left
= get_remote_packet_size ();
12926 rs
->readahead_cache
.invalidate_fd (fd
);
12928 remote_buffer_add_string (&p
, &left
, "vFile:pwrite:");
12930 remote_buffer_add_int (&p
, &left
, fd
);
12931 remote_buffer_add_string (&p
, &left
, ",");
12933 remote_buffer_add_int (&p
, &left
, offset
);
12934 remote_buffer_add_string (&p
, &left
, ",");
12936 p
+= remote_escape_output (write_buf
, len
, 1, (gdb_byte
*) p
, &out_len
,
12937 (get_remote_packet_size ()
12938 - (p
- rs
->buf
.data ())));
12940 return remote_hostio_send_command (p
- rs
->buf
.data (), PACKET_vFile_pwrite
,
12941 remote_errno
, NULL
, NULL
);
12945 remote_target::fileio_pwrite (int fd
, const gdb_byte
*write_buf
, int len
,
12946 ULONGEST offset
, fileio_error
*remote_errno
)
12948 return remote_hostio_pwrite (fd
, write_buf
, len
, offset
, remote_errno
);
12951 /* Helper for the implementation of to_fileio_pread. Read the file
12952 from the remote side with vFile:pread. */
12955 remote_target::remote_hostio_pread_vFile (int fd
, gdb_byte
*read_buf
, int len
,
12956 ULONGEST offset
, fileio_error
*remote_errno
)
12958 struct remote_state
*rs
= get_remote_state ();
12959 char *p
= rs
->buf
.data ();
12960 const char *attachment
;
12961 int left
= get_remote_packet_size ();
12962 int ret
, attachment_len
;
12965 remote_buffer_add_string (&p
, &left
, "vFile:pread:");
12967 remote_buffer_add_int (&p
, &left
, fd
);
12968 remote_buffer_add_string (&p
, &left
, ",");
12970 remote_buffer_add_int (&p
, &left
, len
);
12971 remote_buffer_add_string (&p
, &left
, ",");
12973 remote_buffer_add_int (&p
, &left
, offset
);
12975 ret
= remote_hostio_send_command (p
- rs
->buf
.data (), PACKET_vFile_pread
,
12976 remote_errno
, &attachment
,
12982 read_len
= remote_unescape_input ((gdb_byte
*) attachment
, attachment_len
,
12984 if (read_len
!= ret
)
12985 error (_("Read returned %d, but %d bytes."), ret
, (int) read_len
);
12990 /* See declaration.h. */
12993 readahead_cache::pread (int fd
, gdb_byte
*read_buf
, size_t len
,
12997 && this->offset
<= offset
12998 && offset
< this->offset
+ this->buf
.size ())
13000 ULONGEST max
= this->offset
+ this->buf
.size ();
13002 if (offset
+ len
> max
)
13003 len
= max
- offset
;
13005 memcpy (read_buf
, &this->buf
[offset
- this->offset
], len
);
13012 /* Implementation of to_fileio_pread. */
13015 remote_target::remote_hostio_pread (int fd
, gdb_byte
*read_buf
, int len
,
13016 ULONGEST offset
, fileio_error
*remote_errno
)
13019 struct remote_state
*rs
= get_remote_state ();
13020 readahead_cache
*cache
= &rs
->readahead_cache
;
13022 ret
= cache
->pread (fd
, read_buf
, len
, offset
);
13025 cache
->hit_count
++;
13027 remote_debug_printf ("readahead cache hit %s",
13028 pulongest (cache
->hit_count
));
13032 cache
->miss_count
++;
13034 remote_debug_printf ("readahead cache miss %s",
13035 pulongest (cache
->miss_count
));
13038 cache
->offset
= offset
;
13039 cache
->buf
.resize (get_remote_packet_size ());
13041 ret
= remote_hostio_pread_vFile (cache
->fd
, &cache
->buf
[0],
13042 cache
->buf
.size (),
13043 cache
->offset
, remote_errno
);
13046 cache
->invalidate_fd (fd
);
13050 cache
->buf
.resize (ret
);
13051 return cache
->pread (fd
, read_buf
, len
, offset
);
13055 remote_target::fileio_pread (int fd
, gdb_byte
*read_buf
, int len
,
13056 ULONGEST offset
, fileio_error
*remote_errno
)
13058 return remote_hostio_pread (fd
, read_buf
, len
, offset
, remote_errno
);
13061 /* Implementation of to_fileio_close. */
13064 remote_target::remote_hostio_close (int fd
, fileio_error
*remote_errno
)
13066 struct remote_state
*rs
= get_remote_state ();
13067 char *p
= rs
->buf
.data ();
13068 int left
= get_remote_packet_size () - 1;
13070 rs
->readahead_cache
.invalidate_fd (fd
);
13072 remote_buffer_add_string (&p
, &left
, "vFile:close:");
13074 remote_buffer_add_int (&p
, &left
, fd
);
13076 return remote_hostio_send_command (p
- rs
->buf
.data (), PACKET_vFile_close
,
13077 remote_errno
, NULL
, NULL
);
13081 remote_target::fileio_close (int fd
, fileio_error
*remote_errno
)
13083 return remote_hostio_close (fd
, remote_errno
);
13086 /* Implementation of to_fileio_unlink. */
13089 remote_target::remote_hostio_unlink (inferior
*inf
, const char *filename
,
13090 fileio_error
*remote_errno
)
13092 struct remote_state
*rs
= get_remote_state ();
13093 char *p
= rs
->buf
.data ();
13094 int left
= get_remote_packet_size () - 1;
13096 if (remote_hostio_set_filesystem (inf
, remote_errno
) != 0)
13099 remote_buffer_add_string (&p
, &left
, "vFile:unlink:");
13101 remote_buffer_add_bytes (&p
, &left
, (const gdb_byte
*) filename
,
13102 strlen (filename
));
13104 return remote_hostio_send_command (p
- rs
->buf
.data (), PACKET_vFile_unlink
,
13105 remote_errno
, NULL
, NULL
);
13109 remote_target::fileio_unlink (struct inferior
*inf
, const char *filename
,
13110 fileio_error
*remote_errno
)
13112 return remote_hostio_unlink (inf
, filename
, remote_errno
);
13115 /* Implementation of to_fileio_readlink. */
13117 std::optional
<std::string
>
13118 remote_target::fileio_readlink (struct inferior
*inf
, const char *filename
,
13119 fileio_error
*remote_errno
)
13121 struct remote_state
*rs
= get_remote_state ();
13122 char *p
= rs
->buf
.data ();
13123 const char *attachment
;
13124 int left
= get_remote_packet_size ();
13125 int len
, attachment_len
;
13128 if (remote_hostio_set_filesystem (inf
, remote_errno
) != 0)
13131 remote_buffer_add_string (&p
, &left
, "vFile:readlink:");
13133 remote_buffer_add_bytes (&p
, &left
, (const gdb_byte
*) filename
,
13134 strlen (filename
));
13136 len
= remote_hostio_send_command (p
- rs
->buf
.data (), PACKET_vFile_readlink
,
13137 remote_errno
, &attachment
,
13143 std::string
ret (len
, '\0');
13145 read_len
= remote_unescape_input ((gdb_byte
*) attachment
, attachment_len
,
13146 (gdb_byte
*) &ret
[0], len
);
13147 if (read_len
!= len
)
13148 error (_("Readlink returned %d, but %d bytes."), len
, read_len
);
13153 /* Helper function to handle ::fileio_fstat and ::fileio_lstat result
13154 processing. When this function is called the remote syscall has been
13155 performed and we know we didn't get an error back.
13157 ATTACHMENT and ATTACHMENT_LEN are the attachment data extracted from the
13158 remote syscall reply. EXPECTED_LEN is the length returned from the
13159 fstat or stat call, this the length of the returned data (in ATTACHMENT)
13160 once it has been decoded. The fstat/stat result (from the ATTACHMENT
13161 data) is to be placed in ST. */
13164 fileio_process_fstat_and_lstat_reply (const char *attachment
,
13165 int attachment_len
,
13169 struct fio_stat fst
;
13172 = remote_unescape_input ((gdb_byte
*) attachment
, attachment_len
,
13173 (gdb_byte
*) &fst
, sizeof (fst
));
13175 if (read_len
!= expected_len
)
13176 error (_("vFile:fstat returned %d, but %d bytes."),
13177 expected_len
, read_len
);
13179 if (read_len
!= sizeof (fst
))
13180 error (_("vFile:fstat returned %d bytes, but expecting %d."),
13181 read_len
, (int) sizeof (fst
));
13183 remote_fileio_to_host_stat (&fst
, st
);
13188 /* Implementation of to_fileio_fstat. */
13191 remote_target::fileio_fstat (int fd
, struct stat
*st
, fileio_error
*remote_errno
)
13193 struct remote_state
*rs
= get_remote_state ();
13194 char *p
= rs
->buf
.data ();
13195 int left
= get_remote_packet_size ();
13196 int attachment_len
, ret
;
13197 const char *attachment
;
13199 remote_buffer_add_string (&p
, &left
, "vFile:fstat:");
13201 remote_buffer_add_int (&p
, &left
, fd
);
13203 ret
= remote_hostio_send_command (p
- rs
->buf
.data (), PACKET_vFile_fstat
,
13204 remote_errno
, &attachment
,
13208 if (*remote_errno
!= FILEIO_ENOSYS
)
13211 /* Strictly we should return -1, ENOSYS here, but when
13212 "set sysroot remote:" was implemented in August 2008
13213 BFD's need for a stat function was sidestepped with
13214 this hack. This was not remedied until March 2015
13215 so we retain the previous behavior to avoid breaking
13218 Note that the memset is a March 2015 addition; older
13219 GDBs set st_size *and nothing else* so the structure
13220 would have garbage in all other fields. This might
13221 break something but retaining the previous behavior
13222 here would be just too wrong. */
13224 memset (st
, 0, sizeof (struct stat
));
13225 st
->st_size
= INT_MAX
;
13229 return fileio_process_fstat_and_lstat_reply (attachment
, attachment_len
,
13233 /* Implementation of to_fileio_lstat. */
13236 remote_target::fileio_lstat (struct inferior
*inf
, const char *filename
,
13237 struct stat
*st
, fileio_error
*remote_errno
)
13239 struct remote_state
*rs
= get_remote_state ();
13240 char *p
= rs
->buf
.data ();
13241 int left
= get_remote_packet_size () - 1;
13243 if (remote_hostio_set_filesystem (inf
, remote_errno
) != 0)
13246 remote_buffer_add_string (&p
, &left
, "vFile:lstat:");
13248 remote_buffer_add_bytes (&p
, &left
, (const gdb_byte
*) filename
,
13249 strlen (filename
));
13251 int attachment_len
;
13252 const char *attachment
;
13253 int ret
= remote_hostio_send_command (p
- rs
->buf
.data (), PACKET_vFile_lstat
,
13254 remote_errno
, &attachment
,
13257 /* Unlike ::fileio_fstat, the stat fileio call was added later on, and
13258 has none of the legacy bfd issues, so we can just return the error. */
13262 return fileio_process_fstat_and_lstat_reply (attachment
, attachment_len
,
13266 /* Implementation of to_filesystem_is_local. */
13269 remote_target::filesystem_is_local ()
13271 /* Valgrind GDB presents itself as a remote target but works
13272 on the local filesystem: it does not implement remote get
13273 and users are not expected to set a sysroot. To handle
13274 this case we treat the remote filesystem as local if the
13275 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
13276 does not support vFile:open. */
13277 if (gdb_sysroot
== TARGET_SYSROOT_PREFIX
)
13279 packet_support ps
= m_features
.packet_support (PACKET_vFile_open
);
13281 if (ps
== PACKET_SUPPORT_UNKNOWN
)
13284 fileio_error remote_errno
;
13286 /* Try opening a file to probe support. The supplied
13287 filename is irrelevant, we only care about whether
13288 the stub recognizes the packet or not. */
13289 fd
= remote_hostio_open (NULL
, "just probing",
13290 FILEIO_O_RDONLY
, 0700, 0,
13294 remote_hostio_close (fd
, &remote_errno
);
13296 ps
= m_features
.packet_support (PACKET_vFile_open
);
13299 if (ps
== PACKET_DISABLE
)
13301 static int warning_issued
= 0;
13303 if (!warning_issued
)
13305 warning (_("remote target does not support file"
13306 " transfer, attempting to access files"
13307 " from local filesystem."));
13308 warning_issued
= 1;
13319 remote_hostio_error (fileio_error errnum
)
13321 int host_error
= fileio_error_to_host (errnum
);
13323 if (host_error
== -1)
13324 error (_("Unknown remote I/O error %d"), errnum
);
13326 error (_("Remote I/O error: %s"), safe_strerror (host_error
));
13329 /* A RAII wrapper around a remote file descriptor. */
13331 class scoped_remote_fd
13334 scoped_remote_fd (remote_target
*remote
, int fd
)
13335 : m_remote (remote
), m_fd (fd
)
13339 ~scoped_remote_fd ()
13345 fileio_error remote_errno
;
13346 m_remote
->remote_hostio_close (m_fd
, &remote_errno
);
13348 catch (const gdb_exception_quit
&ex
)
13350 /* We can't throw from a destructor, so re-set the quit flag
13351 for later QUIT checking. */
13354 catch (const gdb_exception_forced_quit
&ex
)
13356 /* Like above, but (eventually) cause GDB to terminate by
13357 setting sync_quit_force_run. */
13358 set_force_quit_flag ();
13362 /* Swallow exception before it escapes the dtor. If
13363 something goes wrong, likely the connection is gone,
13364 and there's nothing else that can be done. */
13369 DISABLE_COPY_AND_ASSIGN (scoped_remote_fd
);
13371 /* Release ownership of the file descriptor, and return it. */
13372 ATTRIBUTE_UNUSED_RESULT
int release () noexcept
13379 /* Return the owned file descriptor. */
13380 int get () const noexcept
13386 /* The remote target. */
13387 remote_target
*m_remote
;
13389 /* The owned remote I/O file descriptor. */
13394 remote_file_put (const char *local_file
, const char *remote_file
, int from_tty
)
13396 remote_target
*remote
= get_current_remote_target ();
13398 if (remote
== nullptr)
13399 error (_("command can only be used with remote target"));
13401 remote
->remote_file_put (local_file
, remote_file
, from_tty
);
13405 remote_target::remote_file_put (const char *local_file
, const char *remote_file
,
13408 int retcode
, bytes
, io_size
;
13409 fileio_error remote_errno
;
13410 int bytes_in_buffer
;
13414 gdb_file_up file
= gdb_fopen_cloexec (local_file
, "rb");
13416 perror_with_name (local_file
);
13418 scoped_remote_fd fd
13419 (this, remote_hostio_open (NULL
,
13420 remote_file
, (FILEIO_O_WRONLY
| FILEIO_O_CREAT
13422 0700, 0, &remote_errno
));
13423 if (fd
.get () == -1)
13424 remote_hostio_error (remote_errno
);
13426 /* Send up to this many bytes at once. They won't all fit in the
13427 remote packet limit, so we'll transfer slightly fewer. */
13428 io_size
= get_remote_packet_size ();
13429 gdb::byte_vector
buffer (io_size
);
13431 bytes_in_buffer
= 0;
13434 while (bytes_in_buffer
|| !saw_eof
)
13438 bytes
= fread (buffer
.data () + bytes_in_buffer
, 1,
13439 io_size
- bytes_in_buffer
,
13443 if (ferror (file
.get ()))
13444 error (_("Error reading %s."), local_file
);
13447 /* EOF. Unless there is something still in the
13448 buffer from the last iteration, we are done. */
13450 if (bytes_in_buffer
== 0)
13458 bytes
+= bytes_in_buffer
;
13459 bytes_in_buffer
= 0;
13461 retcode
= remote_hostio_pwrite (fd
.get (), buffer
.data (), bytes
,
13462 offset
, &remote_errno
);
13465 remote_hostio_error (remote_errno
);
13466 else if (retcode
== 0)
13467 error (_("Remote write of %d bytes returned 0!"), bytes
);
13468 else if (retcode
< bytes
)
13470 /* Short write. Save the rest of the read data for the next
13472 bytes_in_buffer
= bytes
- retcode
;
13473 memmove (buffer
.data (), buffer
.data () + retcode
, bytes_in_buffer
);
13479 if (remote_hostio_close (fd
.release (), &remote_errno
))
13480 remote_hostio_error (remote_errno
);
13483 gdb_printf (_("Successfully sent file \"%ps\".\n"),
13484 styled_string (file_name_style
.style (), local_file
));
13488 remote_file_get (const char *remote_file
, const char *local_file
, int from_tty
)
13490 remote_target
*remote
= get_current_remote_target ();
13492 if (remote
== nullptr)
13493 error (_("command can only be used with remote target"));
13495 remote
->remote_file_get (remote_file
, local_file
, from_tty
);
13499 remote_target::remote_file_get (const char *remote_file
, const char *local_file
,
13502 fileio_error remote_errno
;
13503 int bytes
, io_size
;
13506 scoped_remote_fd fd
13507 (this, remote_hostio_open (NULL
,
13508 remote_file
, FILEIO_O_RDONLY
, 0, 0,
13510 if (fd
.get () == -1)
13511 remote_hostio_error (remote_errno
);
13513 gdb_file_up file
= gdb_fopen_cloexec (local_file
, "wb");
13515 perror_with_name (local_file
);
13517 /* Send up to this many bytes at once. They won't all fit in the
13518 remote packet limit, so we'll transfer slightly fewer. */
13519 io_size
= get_remote_packet_size ();
13520 gdb::byte_vector
buffer (io_size
);
13525 bytes
= remote_hostio_pread (fd
.get (), buffer
.data (), io_size
, offset
,
13528 /* Success, but no bytes, means end-of-file. */
13531 remote_hostio_error (remote_errno
);
13535 bytes
= fwrite (buffer
.data (), 1, bytes
, file
.get ());
13537 perror_with_name (local_file
);
13540 if (remote_hostio_close (fd
.release (), &remote_errno
))
13541 remote_hostio_error (remote_errno
);
13544 gdb_printf (_("Successfully fetched file \"%ps\".\n"),
13545 styled_string (file_name_style
.style (), remote_file
));
13549 remote_file_delete (const char *remote_file
, int from_tty
)
13551 remote_target
*remote
= get_current_remote_target ();
13553 if (remote
== nullptr)
13554 error (_("command can only be used with remote target"));
13556 remote
->remote_file_delete (remote_file
, from_tty
);
13560 remote_target::remote_file_delete (const char *remote_file
, int from_tty
)
13563 fileio_error remote_errno
;
13565 retcode
= remote_hostio_unlink (NULL
, remote_file
, &remote_errno
);
13567 remote_hostio_error (remote_errno
);
13570 gdb_printf (_("Successfully deleted file \"%ps\".\n"),
13571 styled_string (file_name_style
.style (), remote_file
));
13575 remote_put_command (const char *args
, int from_tty
)
13578 error_no_arg (_("file to put"));
13580 gdb_argv
argv (args
);
13581 if (argv
[0] == NULL
|| argv
[1] == NULL
|| argv
[2] != NULL
)
13582 error (_("Invalid parameters to remote put"));
13584 remote_file_put (argv
[0], argv
[1], from_tty
);
13588 remote_get_command (const char *args
, int from_tty
)
13591 error_no_arg (_("file to get"));
13593 gdb_argv
argv (args
);
13594 if (argv
[0] == NULL
|| argv
[1] == NULL
|| argv
[2] != NULL
)
13595 error (_("Invalid parameters to remote get"));
13597 remote_file_get (argv
[0], argv
[1], from_tty
);
13601 remote_delete_command (const char *args
, int from_tty
)
13604 error_no_arg (_("file to delete"));
13606 gdb_argv
argv (args
);
13607 if (argv
[0] == NULL
|| argv
[1] != NULL
)
13608 error (_("Invalid parameters to remote delete"));
13610 remote_file_delete (argv
[0], from_tty
);
13614 remote_target::can_execute_reverse ()
13616 if (m_features
.packet_support (PACKET_bs
) == PACKET_ENABLE
13617 || m_features
.packet_support (PACKET_bc
) == PACKET_ENABLE
)
13624 remote_target::supports_non_stop ()
13630 remote_target::supports_disable_randomization ()
13632 /* Only supported in extended mode. */
13637 remote_target::supports_multi_process ()
13639 return m_features
.remote_multi_process_p ();
13643 remote_target::remote_supports_cond_tracepoints ()
13645 return (m_features
.packet_support (PACKET_ConditionalTracepoints
)
13650 remote_target::supports_evaluation_of_breakpoint_conditions ()
13652 return (m_features
.packet_support (PACKET_ConditionalBreakpoints
)
13657 remote_target::remote_supports_fast_tracepoints ()
13659 return m_features
.packet_support (PACKET_FastTracepoints
) == PACKET_ENABLE
;
13663 remote_target::remote_supports_static_tracepoints ()
13665 return m_features
.packet_support (PACKET_StaticTracepoints
) == PACKET_ENABLE
;
13669 remote_target::remote_supports_install_in_trace ()
13671 return m_features
.packet_support (PACKET_InstallInTrace
) == PACKET_ENABLE
;
13675 remote_target::supports_enable_disable_tracepoint ()
13677 return (m_features
.packet_support (PACKET_EnableDisableTracepoints_feature
)
13682 remote_target::supports_string_tracing ()
13684 return m_features
.packet_support (PACKET_tracenz_feature
) == PACKET_ENABLE
;
13688 remote_target::can_run_breakpoint_commands ()
13690 return m_features
.packet_support (PACKET_BreakpointCommands
) == PACKET_ENABLE
;
13694 remote_target::trace_init ()
13696 struct remote_state
*rs
= get_remote_state ();
13699 remote_get_noisy_reply ();
13700 if (strcmp (rs
->buf
.data (), "OK") != 0)
13701 error (_("Target does not support this command."));
13704 /* Recursive routine to walk through command list including loops, and
13705 download packets for each command. */
13708 remote_target::remote_download_command_source (int num
, ULONGEST addr
,
13709 struct command_line
*cmds
)
13711 struct remote_state
*rs
= get_remote_state ();
13712 struct command_line
*cmd
;
13714 for (cmd
= cmds
; cmd
; cmd
= cmd
->next
)
13716 QUIT
; /* Allow user to bail out with ^C. */
13717 strcpy (rs
->buf
.data (), "QTDPsrc:");
13718 encode_source_string (num
, addr
, "cmd", cmd
->line
,
13719 rs
->buf
.data () + strlen (rs
->buf
.data ()),
13720 rs
->buf
.size () - strlen (rs
->buf
.data ()));
13722 remote_get_noisy_reply ();
13723 if (strcmp (rs
->buf
.data (), "OK"))
13724 warning (_("Target does not support source download."));
13726 if (cmd
->control_type
== while_control
13727 || cmd
->control_type
== while_stepping_control
)
13729 remote_download_command_source (num
, addr
, cmd
->body_list_0
.get ());
13731 QUIT
; /* Allow user to bail out with ^C. */
13732 strcpy (rs
->buf
.data (), "QTDPsrc:");
13733 encode_source_string (num
, addr
, "cmd", "end",
13734 rs
->buf
.data () + strlen (rs
->buf
.data ()),
13735 rs
->buf
.size () - strlen (rs
->buf
.data ()));
13737 remote_get_noisy_reply ();
13738 if (strcmp (rs
->buf
.data (), "OK"))
13739 warning (_("Target does not support source download."));
13745 remote_target::download_tracepoint (struct bp_location
*loc
)
13749 std::vector
<std::string
> tdp_actions
;
13750 std::vector
<std::string
> stepping_actions
;
13752 struct breakpoint
*b
= loc
->owner
;
13753 tracepoint
*t
= gdb::checked_static_cast
<tracepoint
*> (b
);
13754 struct remote_state
*rs
= get_remote_state ();
13756 const char *err_msg
= _("Tracepoint packet too large for target.");
13759 /* We use a buffer other than rs->buf because we'll build strings
13760 across multiple statements, and other statements in between could
13762 gdb::char_vector
buf (get_remote_packet_size ());
13764 encode_actions_rsp (loc
, &tdp_actions
, &stepping_actions
);
13766 tpaddr
= loc
->address
;
13767 strcpy (addrbuf
, phex (tpaddr
));
13768 ret
= snprintf (buf
.data (), buf
.size (), "QTDP:%x:%s:%c:%lx:%x",
13769 b
->number
, addrbuf
, /* address */
13770 (b
->enable_state
== bp_enabled
? 'E' : 'D'),
13771 t
->step_count
, t
->pass_count
);
13773 if (ret
< 0 || ret
>= buf
.size ())
13774 error ("%s", err_msg
);
13776 /* Fast tracepoints are mostly handled by the target, but we can
13777 tell the target how big of an instruction block should be moved
13779 if (b
->type
== bp_fast_tracepoint
)
13781 /* Only test for support at download time; we may not know
13782 target capabilities at definition time. */
13783 if (remote_supports_fast_tracepoints ())
13785 if (gdbarch_fast_tracepoint_valid_at (loc
->gdbarch
, tpaddr
,
13788 size_left
= buf
.size () - strlen (buf
.data ());
13789 ret
= snprintf (buf
.data () + strlen (buf
.data ()),
13791 gdb_insn_length (loc
->gdbarch
, tpaddr
));
13793 if (ret
< 0 || ret
>= size_left
)
13794 error ("%s", err_msg
);
13797 /* If it passed validation at definition but fails now,
13798 something is very wrong. */
13799 internal_error (_("Fast tracepoint not valid during download"));
13802 /* Fast tracepoints are functionally identical to regular
13803 tracepoints, so don't take lack of support as a reason to
13804 give up on the trace run. */
13805 warning (_("Target does not support fast tracepoints, "
13806 "downloading %d as regular tracepoint"), b
->number
);
13808 else if (b
->type
== bp_static_tracepoint
13809 || b
->type
== bp_static_marker_tracepoint
)
13811 /* Only test for support at download time; we may not know
13812 target capabilities at definition time. */
13813 if (remote_supports_static_tracepoints ())
13815 struct static_tracepoint_marker marker
;
13817 if (target_static_tracepoint_marker_at (tpaddr
, &marker
))
13819 size_left
= buf
.size () - strlen (buf
.data ());
13820 ret
= snprintf (buf
.data () + strlen (buf
.data ()),
13823 if (ret
< 0 || ret
>= size_left
)
13824 error ("%s", err_msg
);
13827 error (_("Static tracepoint not valid during download"));
13830 /* Fast tracepoints are functionally identical to regular
13831 tracepoints, so don't take lack of support as a reason
13832 to give up on the trace run. */
13833 error (_("Target does not support static tracepoints"));
13835 /* If the tracepoint has a conditional, make it into an agent
13836 expression and append to the definition. */
13839 /* Only test support at download time, we may not know target
13840 capabilities at definition time. */
13841 if (remote_supports_cond_tracepoints ())
13843 agent_expr_up aexpr
= gen_eval_for_expr (tpaddr
,
13846 size_left
= buf
.size () - strlen (buf
.data ());
13848 ret
= snprintf (buf
.data () + strlen (buf
.data ()),
13849 size_left
, ":X%x,", (int) aexpr
->buf
.size ());
13851 if (ret
< 0 || ret
>= size_left
)
13852 error ("%s", err_msg
);
13854 size_left
= buf
.size () - strlen (buf
.data ());
13856 /* Two bytes to encode each aexpr byte, plus the terminating
13858 if (aexpr
->buf
.size () * 2 + 1 > size_left
)
13859 error ("%s", err_msg
);
13861 pkt
= buf
.data () + strlen (buf
.data ());
13863 for (int ndx
= 0; ndx
< aexpr
->buf
.size (); ++ndx
)
13864 pkt
= pack_hex_byte (pkt
, aexpr
->buf
[ndx
]);
13868 warning (_("Target does not support conditional tracepoints, "
13869 "ignoring tp %d cond"), b
->number
);
13872 if (b
->commands
|| !default_collect
.empty ())
13874 size_left
= buf
.size () - strlen (buf
.data ());
13876 ret
= snprintf (buf
.data () + strlen (buf
.data ()),
13879 if (ret
< 0 || ret
>= size_left
)
13880 error ("%s", err_msg
);
13883 putpkt (buf
.data ());
13884 remote_get_noisy_reply ();
13885 if (strcmp (rs
->buf
.data (), "OK"))
13886 error (_("Target does not support tracepoints."));
13888 /* do_single_steps (t); */
13889 for (auto action_it
= tdp_actions
.begin ();
13890 action_it
!= tdp_actions
.end (); action_it
++)
13892 QUIT
; /* Allow user to bail out with ^C. */
13894 bool has_more
= ((action_it
+ 1) != tdp_actions
.end ()
13895 || !stepping_actions
.empty ());
13897 ret
= snprintf (buf
.data (), buf
.size (), "QTDP:-%x:%s:%s%c",
13898 b
->number
, addrbuf
, /* address */
13899 action_it
->c_str (),
13900 has_more
? '-' : 0);
13902 if (ret
< 0 || ret
>= buf
.size ())
13903 error ("%s", err_msg
);
13905 putpkt (buf
.data ());
13906 remote_get_noisy_reply ();
13907 if (strcmp (rs
->buf
.data (), "OK"))
13908 error (_("Error on target while setting tracepoints."));
13911 for (auto action_it
= stepping_actions
.begin ();
13912 action_it
!= stepping_actions
.end (); action_it
++)
13914 QUIT
; /* Allow user to bail out with ^C. */
13916 bool is_first
= action_it
== stepping_actions
.begin ();
13917 bool has_more
= (action_it
+ 1) != stepping_actions
.end ();
13919 ret
= snprintf (buf
.data (), buf
.size (), "QTDP:-%x:%s:%s%s%s",
13920 b
->number
, addrbuf
, /* address */
13921 is_first
? "S" : "",
13922 action_it
->c_str (),
13923 has_more
? "-" : "");
13925 if (ret
< 0 || ret
>= buf
.size ())
13926 error ("%s", err_msg
);
13928 putpkt (buf
.data ());
13929 remote_get_noisy_reply ();
13930 if (strcmp (rs
->buf
.data (), "OK"))
13931 error (_("Error on target while setting tracepoints."));
13934 if (m_features
.packet_support (PACKET_TracepointSource
) == PACKET_ENABLE
)
13936 if (b
->locspec
!= nullptr)
13938 ret
= snprintf (buf
.data (), buf
.size (), "QTDPsrc:");
13940 if (ret
< 0 || ret
>= buf
.size ())
13941 error ("%s", err_msg
);
13943 const char *str
= b
->locspec
->to_string ();
13944 encode_source_string (b
->number
, loc
->address
, "at", str
,
13945 buf
.data () + strlen (buf
.data ()),
13946 buf
.size () - strlen (buf
.data ()));
13947 putpkt (buf
.data ());
13948 remote_get_noisy_reply ();
13949 if (strcmp (rs
->buf
.data (), "OK"))
13950 warning (_("Target does not support source download."));
13952 if (b
->cond_string
)
13954 ret
= snprintf (buf
.data (), buf
.size (), "QTDPsrc:");
13956 if (ret
< 0 || ret
>= buf
.size ())
13957 error ("%s", err_msg
);
13959 encode_source_string (b
->number
, loc
->address
,
13960 "cond", b
->cond_string
.get (),
13961 buf
.data () + strlen (buf
.data ()),
13962 buf
.size () - strlen (buf
.data ()));
13963 putpkt (buf
.data ());
13964 remote_get_noisy_reply ();
13965 if (strcmp (rs
->buf
.data (), "OK"))
13966 warning (_("Target does not support source download."));
13968 remote_download_command_source (b
->number
, loc
->address
,
13969 breakpoint_commands (b
));
13974 remote_target::can_download_tracepoint ()
13976 struct remote_state
*rs
= get_remote_state ();
13977 struct trace_status
*ts
;
13980 /* Don't try to install tracepoints until we've relocated our
13981 symbols, and fetched and merged the target's tracepoint list with
13983 if (rs
->starting_up
)
13986 ts
= current_trace_status ();
13987 status
= get_trace_status (ts
);
13989 if (status
== -1 || !ts
->running_known
|| !ts
->running
)
13992 /* If we are in a tracing experiment, but remote stub doesn't support
13993 installing tracepoint in trace, we have to return. */
13994 if (!remote_supports_install_in_trace ())
14002 remote_target::download_trace_state_variable (const trace_state_variable
&tsv
)
14004 struct remote_state
*rs
= get_remote_state ();
14007 xsnprintf (rs
->buf
.data (), get_remote_packet_size (), "QTDV:%x:%s:%x:",
14008 tsv
.number
, phex ((ULONGEST
) tsv
.initial_value
, 8),
14010 p
= rs
->buf
.data () + strlen (rs
->buf
.data ());
14011 if ((p
- rs
->buf
.data ()) + tsv
.name
.length () * 2
14012 >= get_remote_packet_size ())
14013 error (_("Trace state variable name too long for tsv definition packet"));
14014 p
+= 2 * bin2hex ((gdb_byte
*) (tsv
.name
.data ()), p
, tsv
.name
.length ());
14017 remote_get_noisy_reply ();
14018 if (rs
->buf
[0] == '\0')
14019 error (_("Target does not support this command."));
14020 if (strcmp (rs
->buf
.data (), "OK") != 0)
14021 error (_("Error on target while downloading trace state variable."));
14025 remote_target::enable_tracepoint (struct bp_location
*location
)
14027 struct remote_state
*rs
= get_remote_state ();
14029 xsnprintf (rs
->buf
.data (), get_remote_packet_size (), "QTEnable:%x:%s",
14030 location
->owner
->number
,
14031 phex (location
->address
));
14033 remote_get_noisy_reply ();
14034 if (rs
->buf
[0] == '\0')
14035 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
14036 if (strcmp (rs
->buf
.data (), "OK") != 0)
14037 error (_("Error on target while enabling tracepoint."));
14041 remote_target::disable_tracepoint (struct bp_location
*location
)
14043 struct remote_state
*rs
= get_remote_state ();
14045 xsnprintf (rs
->buf
.data (), get_remote_packet_size (), "QTDisable:%x:%s",
14046 location
->owner
->number
,
14047 phex (location
->address
));
14049 remote_get_noisy_reply ();
14050 if (rs
->buf
[0] == '\0')
14051 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
14052 if (strcmp (rs
->buf
.data (), "OK") != 0)
14053 error (_("Error on target while disabling tracepoint."));
14057 remote_target::trace_set_readonly_regions ()
14060 bfd_size_type size
;
14064 bfd
*abfd
= current_program_space
->exec_bfd ();
14067 return; /* No information to give. */
14069 struct remote_state
*rs
= get_remote_state ();
14071 strcpy (rs
->buf
.data (), "QTro");
14072 offset
= strlen (rs
->buf
.data ());
14073 for (s
= abfd
->sections
; s
; s
= s
->next
)
14075 char tmp1
[40], tmp2
[40];
14078 if ((s
->flags
& SEC_LOAD
) == 0
14079 /* || (s->flags & SEC_CODE) == 0 */
14080 || (s
->flags
& SEC_READONLY
) == 0)
14084 vma
= bfd_section_vma (s
);
14085 size
= bfd_section_size (s
);
14086 bfd_sprintf_vma (abfd
, tmp1
, vma
);
14087 bfd_sprintf_vma (abfd
, tmp2
, vma
+ size
);
14088 sec_length
= 1 + strlen (tmp1
) + 1 + strlen (tmp2
);
14089 if (offset
+ sec_length
+ 1 > rs
->buf
.size ())
14091 if (m_features
.packet_support (PACKET_qXfer_traceframe_info
)
14094 Too many sections for read-only sections definition packet."));
14097 xsnprintf (rs
->buf
.data () + offset
, rs
->buf
.size () - offset
, ":%s,%s",
14099 offset
+= sec_length
;
14109 remote_target::trace_start ()
14111 struct remote_state
*rs
= get_remote_state ();
14113 putpkt ("QTStart");
14114 remote_get_noisy_reply ();
14115 if (rs
->buf
[0] == '\0')
14116 error (_("Target does not support this command."));
14117 if (strcmp (rs
->buf
.data (), "OK") != 0)
14118 error (_("Bogus reply from target: %s"), rs
->buf
.data ());
14122 remote_target::get_trace_status (struct trace_status
*ts
)
14124 /* Initialize it just to avoid a GCC false warning. */
14126 struct remote_state
*rs
= get_remote_state ();
14128 if (m_features
.packet_support (PACKET_qTStatus
) == PACKET_DISABLE
)
14131 /* FIXME we need to get register block size some other way. */
14132 trace_regblock_size
14133 = rs
->get_remote_arch_state (current_inferior ()->arch ())->sizeof_g_packet
;
14135 putpkt ("qTStatus");
14139 p
= remote_get_noisy_reply ();
14141 catch (const gdb_exception_error
&ex
)
14143 if (ex
.error
!= TARGET_CLOSE_ERROR
)
14145 exception_fprintf (gdb_stderr
, ex
, "qTStatus: ");
14151 packet_result result
= m_features
.packet_ok (p
, PACKET_qTStatus
);
14153 switch (result
.status ())
14156 error (_("Remote failure reply: %s"), result
.err_msg ());
14157 /* If the remote target doesn't do tracing, flag it. */
14158 case PACKET_UNKNOWN
:
14162 /* We're working with a live target. */
14163 ts
->filename
= NULL
;
14166 error (_("Bogus trace status reply from target: %s"), rs
->buf
.data ());
14168 /* Function 'parse_trace_status' sets default value of each field of
14169 'ts' at first, so we don't have to do it here. */
14170 parse_trace_status (p
, ts
);
14172 return ts
->running
;
14176 remote_target::get_tracepoint_status (tracepoint
*tp
,
14177 struct uploaded_tp
*utp
)
14179 struct remote_state
*rs
= get_remote_state ();
14181 size_t size
= get_remote_packet_size ();
14186 tp
->traceframe_usage
= 0;
14187 for (bp_location
&loc
: tp
->locations ())
14189 /* If the tracepoint was never downloaded, don't go asking for
14191 if (tp
->number_on_target
== 0)
14193 xsnprintf (rs
->buf
.data (), size
, "qTP:%x:%s", tp
->number_on_target
,
14194 phex_nz (loc
.address
, 0));
14196 reply
= remote_get_noisy_reply ();
14197 if (reply
&& *reply
)
14200 parse_tracepoint_status (reply
+ 1, tp
, utp
);
14206 utp
->hit_count
= 0;
14207 utp
->traceframe_usage
= 0;
14208 xsnprintf (rs
->buf
.data (), size
, "qTP:%x:%s", utp
->number
,
14209 phex_nz (utp
->addr
, 0));
14211 reply
= remote_get_noisy_reply ();
14212 if (reply
&& *reply
)
14215 parse_tracepoint_status (reply
+ 1, tp
, utp
);
14221 remote_target::trace_stop ()
14223 struct remote_state
*rs
= get_remote_state ();
14226 remote_get_noisy_reply ();
14227 if (rs
->buf
[0] == '\0')
14228 error (_("Target does not support this command."));
14229 if (strcmp (rs
->buf
.data (), "OK") != 0)
14230 error (_("Bogus reply from target: %s"), rs
->buf
.data ());
14234 remote_target::trace_find (enum trace_find_type type
, int num
,
14235 CORE_ADDR addr1
, CORE_ADDR addr2
,
14238 struct remote_state
*rs
= get_remote_state ();
14239 char *endbuf
= rs
->buf
.data () + get_remote_packet_size ();
14241 int target_frameno
= -1, target_tracept
= -1;
14243 /* Lookups other than by absolute frame number depend on the current
14244 trace selected, so make sure it is correct on the remote end
14246 if (type
!= tfind_number
)
14247 set_remote_traceframe ();
14249 p
= rs
->buf
.data ();
14250 strcpy (p
, "QTFrame:");
14251 p
= strchr (p
, '\0');
14255 xsnprintf (p
, endbuf
- p
, "%x", num
);
14258 xsnprintf (p
, endbuf
- p
, "pc:%s", phex_nz (addr1
, 0));
14261 xsnprintf (p
, endbuf
- p
, "tdp:%x", num
);
14264 xsnprintf (p
, endbuf
- p
, "range:%s:%s", phex_nz (addr1
, 0),
14265 phex_nz (addr2
, 0));
14267 case tfind_outside
:
14268 xsnprintf (p
, endbuf
- p
, "outside:%s:%s", phex_nz (addr1
, 0),
14269 phex_nz (addr2
, 0));
14272 error (_("Unknown trace find type %d"), type
);
14276 reply
= remote_get_noisy_reply ();
14277 if (*reply
== '\0')
14278 error (_("Target does not support this command."));
14280 while (reply
&& *reply
)
14285 target_frameno
= (int) strtol (p
, &reply
, 16);
14287 error (_("Unable to parse trace frame number"));
14288 /* Don't update our remote traceframe number cache on failure
14289 to select a remote traceframe. */
14290 if (target_frameno
== -1)
14295 target_tracept
= (int) strtol (p
, &reply
, 16);
14297 error (_("Unable to parse tracepoint number"));
14299 case 'O': /* "OK"? */
14300 if (reply
[1] == 'K' && reply
[2] == '\0')
14303 error (_("Bogus reply from target: %s"), reply
);
14306 error (_("Bogus reply from target: %s"), reply
);
14309 *tpp
= target_tracept
;
14311 rs
->remote_traceframe_number
= target_frameno
;
14312 return target_frameno
;
14316 remote_target::get_trace_state_variable_value (int tsvnum
, LONGEST
*val
)
14318 struct remote_state
*rs
= get_remote_state ();
14322 set_remote_traceframe ();
14324 xsnprintf (rs
->buf
.data (), get_remote_packet_size (), "qTV:%x", tsvnum
);
14326 reply
= remote_get_noisy_reply ();
14327 if (reply
&& *reply
)
14331 unpack_varlen_hex (reply
+ 1, &uval
);
14332 *val
= (LONGEST
) uval
;
14340 remote_target::save_trace_data (const char *filename
)
14342 struct remote_state
*rs
= get_remote_state ();
14345 p
= rs
->buf
.data ();
14346 strcpy (p
, "QTSave:");
14348 if ((p
- rs
->buf
.data ()) + strlen (filename
) * 2
14349 >= get_remote_packet_size ())
14350 error (_("Remote file name too long for trace save packet"));
14351 p
+= 2 * bin2hex ((gdb_byte
*) filename
, p
, strlen (filename
));
14354 reply
= remote_get_noisy_reply ();
14355 if (*reply
== '\0')
14356 error (_("Target does not support this command."));
14357 if (strcmp (reply
, "OK") != 0)
14358 error (_("Bogus reply from target: %s"), reply
);
14362 /* This is basically a memory transfer, but needs to be its own packet
14363 because we don't know how the target actually organizes its trace
14364 memory, plus we want to be able to ask for as much as possible, but
14365 not be unhappy if we don't get as much as we ask for. */
14368 remote_target::get_raw_trace_data (gdb_byte
*buf
, ULONGEST offset
, LONGEST len
)
14370 struct remote_state
*rs
= get_remote_state ();
14375 p
= rs
->buf
.data ();
14376 strcpy (p
, "qTBuffer:");
14378 p
+= hexnumstr (p
, offset
);
14380 p
+= hexnumstr (p
, len
);
14384 reply
= remote_get_noisy_reply ();
14385 if (reply
&& *reply
)
14387 /* 'l' by itself means we're at the end of the buffer and
14388 there is nothing more to get. */
14392 /* Convert the reply into binary. Limit the number of bytes to
14393 convert according to our passed-in buffer size, rather than
14394 what was returned in the packet; if the target is
14395 unexpectedly generous and gives us a bigger reply than we
14396 asked for, we don't want to crash. */
14397 rslt
= hex2bin (reply
, buf
, len
);
14401 /* Something went wrong, flag as an error. */
14406 remote_target::set_disconnected_tracing (int val
)
14408 struct remote_state
*rs
= get_remote_state ();
14410 if (m_features
.packet_support (PACKET_DisconnectedTracing_feature
)
14415 xsnprintf (rs
->buf
.data (), get_remote_packet_size (),
14416 "QTDisconnected:%x", val
);
14418 reply
= remote_get_noisy_reply ();
14419 if (*reply
== '\0')
14420 error (_("Target does not support this command."));
14421 if (strcmp (reply
, "OK") != 0)
14422 error (_("Bogus reply from target: %s"), reply
);
14425 warning (_("Target does not support disconnected tracing."));
14429 remote_target::core_of_thread (ptid_t ptid
)
14431 thread_info
*info
= this->find_thread (ptid
);
14433 if (info
!= NULL
&& info
->priv
!= NULL
)
14434 return get_remote_thread_info (info
)->core
;
14440 remote_target::set_circular_trace_buffer (int val
)
14442 struct remote_state
*rs
= get_remote_state ();
14445 xsnprintf (rs
->buf
.data (), get_remote_packet_size (),
14446 "QTBuffer:circular:%x", val
);
14448 reply
= remote_get_noisy_reply ();
14449 if (*reply
== '\0')
14450 error (_("Target does not support this command."));
14451 if (strcmp (reply
, "OK") != 0)
14452 error (_("Bogus reply from target: %s"), reply
);
14456 remote_target::traceframe_info ()
14458 std::optional
<gdb::char_vector
> text
14459 = target_read_stralloc (current_inferior ()->top_target (),
14460 TARGET_OBJECT_TRACEFRAME_INFO
,
14463 return parse_traceframe_info (text
->data ());
14468 /* Handle the qTMinFTPILen packet. Returns the minimum length of
14469 instruction on which a fast tracepoint may be placed. Returns -1
14470 if the packet is not supported, and 0 if the minimum instruction
14471 length is unknown. */
14474 remote_target::get_min_fast_tracepoint_insn_len ()
14476 struct remote_state
*rs
= get_remote_state ();
14479 /* If we're not debugging a process yet, the IPA can't be
14481 if (!target_has_execution ())
14484 /* Make sure the remote is pointing at the right process. */
14485 set_general_process ();
14487 xsnprintf (rs
->buf
.data (), get_remote_packet_size (), "qTMinFTPILen");
14489 reply
= remote_get_noisy_reply ();
14490 if (*reply
== '\0')
14494 ULONGEST min_insn_len
;
14496 unpack_varlen_hex (reply
, &min_insn_len
);
14498 return (int) min_insn_len
;
14503 remote_target::set_trace_buffer_size (LONGEST val
)
14505 if (m_features
.packet_support (PACKET_QTBuffer_size
) != PACKET_DISABLE
)
14507 struct remote_state
*rs
= get_remote_state ();
14508 char *buf
= rs
->buf
.data ();
14509 char *endbuf
= buf
+ get_remote_packet_size ();
14511 gdb_assert (val
>= 0 || val
== -1);
14512 buf
+= xsnprintf (buf
, endbuf
- buf
, "QTBuffer:size:");
14513 /* Send -1 as literal "-1" to avoid host size dependency. */
14517 buf
+= hexnumstr (buf
, (ULONGEST
) -val
);
14520 buf
+= hexnumstr (buf
, (ULONGEST
) val
);
14523 remote_get_noisy_reply ();
14524 packet_result result
= m_features
.packet_ok (rs
->buf
, PACKET_QTBuffer_size
);
14525 switch (result
.status ())
14528 warning (_("Error reply from target: %s"), result
.err_msg ());
14530 case PACKET_UNKNOWN
:
14531 warning (_("Remote target failed to process the request "));
14537 remote_target::set_trace_notes (const char *user
, const char *notes
,
14538 const char *stop_notes
)
14540 struct remote_state
*rs
= get_remote_state ();
14542 char *buf
= rs
->buf
.data ();
14543 char *endbuf
= buf
+ get_remote_packet_size ();
14546 buf
+= xsnprintf (buf
, endbuf
- buf
, "QTNotes:");
14549 buf
+= xsnprintf (buf
, endbuf
- buf
, "user:");
14550 nbytes
= bin2hex ((gdb_byte
*) user
, buf
, strlen (user
));
14556 buf
+= xsnprintf (buf
, endbuf
- buf
, "notes:");
14557 nbytes
= bin2hex ((gdb_byte
*) notes
, buf
, strlen (notes
));
14563 buf
+= xsnprintf (buf
, endbuf
- buf
, "tstop:");
14564 nbytes
= bin2hex ((gdb_byte
*) stop_notes
, buf
, strlen (stop_notes
));
14568 /* Ensure the buffer is terminated. */
14572 reply
= remote_get_noisy_reply ();
14573 if (*reply
== '\0')
14576 if (strcmp (reply
, "OK") != 0)
14577 error (_("Bogus reply from target: %s"), reply
);
14583 remote_target::use_agent (bool use
)
14585 if (m_features
.packet_support (PACKET_QAgent
) != PACKET_DISABLE
)
14587 struct remote_state
*rs
= get_remote_state ();
14589 /* If the stub supports QAgent. */
14590 xsnprintf (rs
->buf
.data (), get_remote_packet_size (), "QAgent:%d", use
);
14594 if (strcmp (rs
->buf
.data (), "OK") == 0)
14605 remote_target::can_use_agent ()
14607 return (m_features
.packet_support (PACKET_QAgent
) != PACKET_DISABLE
);
14610 #if defined (HAVE_LIBEXPAT)
14612 /* Check the btrace document version. */
14615 check_xml_btrace_version (struct gdb_xml_parser
*parser
,
14616 const struct gdb_xml_element
*element
,
14618 std::vector
<gdb_xml_value
> &attributes
)
14620 const char *version
14621 = (const char *) xml_find_attribute (attributes
, "version")->value
.get ();
14623 if (strcmp (version
, "1.0") != 0)
14624 gdb_xml_error (parser
, _("Unsupported btrace version: \"%s\""), version
);
14627 /* Parse a btrace "block" xml record. */
14630 parse_xml_btrace_block (struct gdb_xml_parser
*parser
,
14631 const struct gdb_xml_element
*element
,
14633 std::vector
<gdb_xml_value
> &attributes
)
14635 struct btrace_data
*btrace
;
14636 ULONGEST
*begin
, *end
;
14638 btrace
= (struct btrace_data
*) user_data
;
14640 switch (btrace
->format
)
14642 case BTRACE_FORMAT_BTS
:
14645 case BTRACE_FORMAT_NONE
:
14646 btrace
->format
= BTRACE_FORMAT_BTS
;
14647 btrace
->variant
.bts
.blocks
= new std::vector
<btrace_block
>;
14651 gdb_xml_error (parser
, _("Btrace format error."));
14654 begin
= (ULONGEST
*) xml_find_attribute (attributes
, "begin")->value
.get ();
14655 end
= (ULONGEST
*) xml_find_attribute (attributes
, "end")->value
.get ();
14656 btrace
->variant
.bts
.blocks
->emplace_back (*begin
, *end
);
14659 /* Parse a "raw" xml record. */
14662 parse_xml_raw (struct gdb_xml_parser
*parser
, const char *body_text
,
14663 gdb_byte
**pdata
, size_t *psize
)
14668 len
= strlen (body_text
);
14670 gdb_xml_error (parser
, _("Bad raw data size."));
14674 gdb::unique_xmalloc_ptr
<gdb_byte
> data ((gdb_byte
*) xmalloc (size
));
14677 /* We use hex encoding - see gdbsupport/rsp-low.h. */
14685 if (hi
== 0 || lo
== 0)
14686 gdb_xml_error (parser
, _("Bad hex encoding."));
14688 *bin
++ = fromhex (hi
) * 16 + fromhex (lo
);
14692 *pdata
= data
.release ();
14696 /* Parse a btrace pt-config "cpu" xml record. */
14699 parse_xml_btrace_pt_config_cpu (struct gdb_xml_parser
*parser
,
14700 const struct gdb_xml_element
*element
,
14702 std::vector
<gdb_xml_value
> &attributes
)
14704 struct btrace_data
*btrace
;
14705 const char *vendor
;
14706 ULONGEST
*family
, *model
, *stepping
;
14709 = (const char *) xml_find_attribute (attributes
, "vendor")->value
.get ();
14711 = (ULONGEST
*) xml_find_attribute (attributes
, "family")->value
.get ();
14713 = (ULONGEST
*) xml_find_attribute (attributes
, "model")->value
.get ();
14715 = (ULONGEST
*) xml_find_attribute (attributes
, "stepping")->value
.get ();
14717 btrace
= (struct btrace_data
*) user_data
;
14719 if (strcmp (vendor
, "GenuineIntel") == 0)
14720 btrace
->variant
.pt
.config
.cpu
.vendor
= CV_INTEL
;
14722 btrace
->variant
.pt
.config
.cpu
.family
= *family
;
14723 btrace
->variant
.pt
.config
.cpu
.model
= *model
;
14724 btrace
->variant
.pt
.config
.cpu
.stepping
= *stepping
;
14727 /* Parse a btrace pt "raw" xml record. */
14730 parse_xml_btrace_pt_raw (struct gdb_xml_parser
*parser
,
14731 const struct gdb_xml_element
*element
,
14732 void *user_data
, const char *body_text
)
14734 struct btrace_data
*btrace
;
14736 btrace
= (struct btrace_data
*) user_data
;
14737 parse_xml_raw (parser
, body_text
, &btrace
->variant
.pt
.data
,
14738 &btrace
->variant
.pt
.size
);
14741 /* Parse a btrace "pt" xml record. */
14744 parse_xml_btrace_pt (struct gdb_xml_parser
*parser
,
14745 const struct gdb_xml_element
*element
,
14747 std::vector
<gdb_xml_value
> &attributes
)
14749 struct btrace_data
*btrace
;
14751 btrace
= (struct btrace_data
*) user_data
;
14752 btrace
->format
= BTRACE_FORMAT_PT
;
14753 btrace
->variant
.pt
.config
.cpu
.vendor
= CV_UNKNOWN
;
14754 btrace
->variant
.pt
.data
= NULL
;
14755 btrace
->variant
.pt
.size
= 0;
14758 static const struct gdb_xml_attribute block_attributes
[] = {
14759 { "begin", GDB_XML_AF_NONE
, gdb_xml_parse_attr_ulongest
, NULL
},
14760 { "end", GDB_XML_AF_NONE
, gdb_xml_parse_attr_ulongest
, NULL
},
14761 { NULL
, GDB_XML_AF_NONE
, NULL
, NULL
}
14764 static const struct gdb_xml_attribute btrace_pt_config_cpu_attributes
[] = {
14765 { "vendor", GDB_XML_AF_NONE
, NULL
, NULL
},
14766 { "family", GDB_XML_AF_NONE
, gdb_xml_parse_attr_ulongest
, NULL
},
14767 { "model", GDB_XML_AF_NONE
, gdb_xml_parse_attr_ulongest
, NULL
},
14768 { "stepping", GDB_XML_AF_NONE
, gdb_xml_parse_attr_ulongest
, NULL
},
14769 { NULL
, GDB_XML_AF_NONE
, NULL
, NULL
}
14772 static const struct gdb_xml_element btrace_pt_config_children
[] = {
14773 { "cpu", btrace_pt_config_cpu_attributes
, NULL
, GDB_XML_EF_OPTIONAL
,
14774 parse_xml_btrace_pt_config_cpu
, NULL
},
14775 { NULL
, NULL
, NULL
, GDB_XML_EF_NONE
, NULL
, NULL
}
14778 static const struct gdb_xml_element btrace_pt_children
[] = {
14779 { "pt-config", NULL
, btrace_pt_config_children
, GDB_XML_EF_OPTIONAL
, NULL
,
14781 { "raw", NULL
, NULL
, GDB_XML_EF_OPTIONAL
, NULL
, parse_xml_btrace_pt_raw
},
14782 { NULL
, NULL
, NULL
, GDB_XML_EF_NONE
, NULL
, NULL
}
14785 static const struct gdb_xml_attribute btrace_attributes
[] = {
14786 { "version", GDB_XML_AF_NONE
, NULL
, NULL
},
14787 { NULL
, GDB_XML_AF_NONE
, NULL
, NULL
}
14790 static const struct gdb_xml_element btrace_children
[] = {
14791 { "block", block_attributes
, NULL
,
14792 GDB_XML_EF_REPEATABLE
| GDB_XML_EF_OPTIONAL
, parse_xml_btrace_block
, NULL
},
14793 { "pt", NULL
, btrace_pt_children
, GDB_XML_EF_OPTIONAL
, parse_xml_btrace_pt
,
14795 { NULL
, NULL
, NULL
, GDB_XML_EF_NONE
, NULL
, NULL
}
14798 static const struct gdb_xml_element btrace_elements
[] = {
14799 { "btrace", btrace_attributes
, btrace_children
, GDB_XML_EF_NONE
,
14800 check_xml_btrace_version
, NULL
},
14801 { NULL
, NULL
, NULL
, GDB_XML_EF_NONE
, NULL
, NULL
}
14804 #endif /* defined (HAVE_LIBEXPAT) */
14806 /* Parse a branch trace xml document XML into DATA. */
14809 parse_xml_btrace (struct btrace_data
*btrace
, const char *buffer
)
14811 #if defined (HAVE_LIBEXPAT)
14814 btrace_data result
;
14815 result
.format
= BTRACE_FORMAT_NONE
;
14817 errcode
= gdb_xml_parse_quick (_("btrace"), "btrace.dtd", btrace_elements
,
14820 error (_("Error parsing branch trace."));
14822 /* Keep parse results. */
14823 *btrace
= std::move (result
);
14825 #else /* !defined (HAVE_LIBEXPAT) */
14827 error (_("Cannot process branch trace. XML support was disabled at "
14830 #endif /* !defined (HAVE_LIBEXPAT) */
14833 #if defined (HAVE_LIBEXPAT)
14835 /* Parse a btrace-conf "bts" xml record. */
14838 parse_xml_btrace_conf_bts (struct gdb_xml_parser
*parser
,
14839 const struct gdb_xml_element
*element
,
14841 std::vector
<gdb_xml_value
> &attributes
)
14843 struct btrace_config
*conf
;
14844 struct gdb_xml_value
*size
;
14846 conf
= (struct btrace_config
*) user_data
;
14847 conf
->format
= BTRACE_FORMAT_BTS
;
14848 conf
->bts
.size
= 0;
14850 size
= xml_find_attribute (attributes
, "size");
14852 conf
->bts
.size
= (unsigned int) *(ULONGEST
*) size
->value
.get ();
14855 /* Parse a btrace-conf "pt" xml record. */
14858 parse_xml_btrace_conf_pt (struct gdb_xml_parser
*parser
,
14859 const struct gdb_xml_element
*element
,
14861 std::vector
<gdb_xml_value
> &attributes
)
14863 struct btrace_config
*conf
;
14864 struct gdb_xml_value
*size
, *ptwrite
, *event_tracing
;
14866 conf
= (struct btrace_config
*) user_data
;
14867 conf
->format
= BTRACE_FORMAT_PT
;
14870 size
= xml_find_attribute (attributes
, "size");
14872 conf
->pt
.size
= (unsigned int) *(ULONGEST
*) size
->value
.get ();
14874 ptwrite
= xml_find_attribute (attributes
, "ptwrite");
14875 if (ptwrite
!= nullptr)
14876 conf
->pt
.ptwrite
= (bool) *(ULONGEST
*) ptwrite
->value
.get ();
14878 event_tracing
= xml_find_attribute (attributes
, "event-tracing");
14879 if (event_tracing
!= nullptr)
14880 conf
->pt
.event_tracing
= (bool) *(ULONGEST
*) event_tracing
->value
.get ();
14883 static const struct gdb_xml_attribute btrace_conf_pt_attributes
[] = {
14884 { "size", GDB_XML_AF_OPTIONAL
, gdb_xml_parse_attr_ulongest
, NULL
},
14885 { "ptwrite", GDB_XML_AF_OPTIONAL
, gdb_xml_parse_attr_enum
,
14886 gdb_xml_enums_boolean
},
14887 { "event-tracing", GDB_XML_AF_OPTIONAL
, gdb_xml_parse_attr_enum
,
14888 gdb_xml_enums_boolean
},
14889 { NULL
, GDB_XML_AF_NONE
, NULL
, NULL
}
14892 static const struct gdb_xml_attribute btrace_conf_bts_attributes
[] = {
14893 { "size", GDB_XML_AF_OPTIONAL
, gdb_xml_parse_attr_ulongest
, NULL
},
14894 { NULL
, GDB_XML_AF_NONE
, NULL
, NULL
}
14897 static const struct gdb_xml_element btrace_conf_children
[] = {
14898 { "bts", btrace_conf_bts_attributes
, NULL
, GDB_XML_EF_OPTIONAL
,
14899 parse_xml_btrace_conf_bts
, NULL
},
14900 { "pt", btrace_conf_pt_attributes
, NULL
, GDB_XML_EF_OPTIONAL
,
14901 parse_xml_btrace_conf_pt
, NULL
},
14902 { NULL
, NULL
, NULL
, GDB_XML_EF_NONE
, NULL
, NULL
}
14905 static const struct gdb_xml_attribute btrace_conf_attributes
[] = {
14906 { "version", GDB_XML_AF_NONE
, NULL
, NULL
},
14907 { NULL
, GDB_XML_AF_NONE
, NULL
, NULL
}
14910 static const struct gdb_xml_element btrace_conf_elements
[] = {
14911 { "btrace-conf", btrace_conf_attributes
, btrace_conf_children
,
14912 GDB_XML_EF_NONE
, NULL
, NULL
},
14913 { NULL
, NULL
, NULL
, GDB_XML_EF_NONE
, NULL
, NULL
}
14916 #endif /* defined (HAVE_LIBEXPAT) */
14918 /* Parse a branch trace configuration xml document XML into CONF. */
14921 parse_xml_btrace_conf (struct btrace_config
*conf
, const char *xml
)
14923 #if defined (HAVE_LIBEXPAT)
14926 errcode
= gdb_xml_parse_quick (_("btrace-conf"), "btrace-conf.dtd",
14927 btrace_conf_elements
, xml
, conf
);
14929 error (_("Error parsing branch trace configuration."));
14931 #else /* !defined (HAVE_LIBEXPAT) */
14933 error (_("Cannot process the branch trace configuration. XML support "
14934 "was disabled at compile time."));
14936 #endif /* !defined (HAVE_LIBEXPAT) */
14939 /* Reset our idea of our target's btrace configuration. */
14942 remote_btrace_reset (remote_state
*rs
)
14944 memset (&rs
->btrace_config
, 0, sizeof (rs
->btrace_config
));
14947 /* Synchronize the configuration with the target. */
14950 remote_target::btrace_sync_conf (const btrace_config
*conf
)
14952 struct remote_state
*rs
;
14953 char *buf
, *pos
, *endbuf
;
14955 rs
= get_remote_state ();
14956 buf
= rs
->buf
.data ();
14957 endbuf
= buf
+ get_remote_packet_size ();
14959 if (m_features
.packet_support (PACKET_Qbtrace_conf_bts_size
) == PACKET_ENABLE
14960 && conf
->bts
.size
!= rs
->btrace_config
.bts
.size
)
14963 pos
+= xsnprintf (pos
, endbuf
- pos
, "%s=0x%x",
14964 packets_descriptions
[PACKET_Qbtrace_conf_bts_size
].name
,
14970 packet_result result
= m_features
.packet_ok (buf
, PACKET_Qbtrace_conf_bts_size
);
14971 if (result
.status () == PACKET_ERROR
)
14972 error (_("Failed to configure the BTS buffer size: %s"), result
.err_msg ());
14974 rs
->btrace_config
.bts
.size
= conf
->bts
.size
;
14977 if (m_features
.packet_support (PACKET_Qbtrace_conf_pt_size
) == PACKET_ENABLE
14978 && conf
->pt
.size
!= rs
->btrace_config
.pt
.size
)
14981 pos
+= xsnprintf (pos
, endbuf
- pos
, "%s=0x%x",
14982 packets_descriptions
[PACKET_Qbtrace_conf_pt_size
].name
,
14988 packet_result result
= m_features
.packet_ok (buf
, PACKET_Qbtrace_conf_pt_size
);
14989 if (result
.status () == PACKET_ERROR
)
14990 error (_("Failed to configure the trace buffer size: %s"), result
.err_msg ());
14992 rs
->btrace_config
.pt
.size
= conf
->pt
.size
;
14995 if ((m_features
.packet_support (PACKET_Qbtrace_conf_pt_ptwrite
)
14997 && conf
->pt
.ptwrite
!= rs
->btrace_config
.pt
.ptwrite
)
15000 const char *ptw
= conf
->pt
.ptwrite
? "yes" : "no";
15002 = packets_descriptions
[PACKET_Qbtrace_conf_pt_ptwrite
].name
;
15003 pos
+= xsnprintf (pos
, endbuf
- pos
, "%s=\"%s\"", name
, ptw
);
15006 getpkt (&rs
->buf
, 0);
15008 packet_result result
15009 = m_features
.packet_ok (buf
, PACKET_Qbtrace_conf_pt_ptwrite
);
15010 if (result
.status () == PACKET_ERROR
)
15012 if (buf
[0] == 'E' && buf
[1] == '.')
15013 error (_("Failed to sync ptwrite config: %s"), buf
+ 2);
15015 error (_("Failed to sync ptwrite config."));
15018 rs
->btrace_config
.pt
.ptwrite
= conf
->pt
.ptwrite
;
15021 /* Event tracing is a user setting, warn if it is set but the target
15022 doesn't support it. */
15023 if ((m_features
.packet_support (PACKET_Qbtrace_conf_pt_event_tracing
)
15025 && conf
->pt
.event_tracing
)
15026 warning (_("Target does not support event-tracing."));
15028 if ((m_features
.packet_support (PACKET_Qbtrace_conf_pt_event_tracing
)
15030 && conf
->pt
.event_tracing
!= rs
->btrace_config
.pt
.event_tracing
)
15033 const char *event_tracing
= conf
->pt
.event_tracing
? "yes" : "no";
15035 = packets_descriptions
[PACKET_Qbtrace_conf_pt_event_tracing
].name
;
15036 pos
+= xsnprintf (pos
, endbuf
- pos
, "%s=\"%s\"", name
, event_tracing
);
15039 getpkt (&rs
->buf
, 0);
15041 packet_result result
15042 = m_features
.packet_ok (buf
, PACKET_Qbtrace_conf_pt_event_tracing
);
15043 if (result
.status () == PACKET_ERROR
)
15045 if (buf
[0] == 'E' && buf
[1] == '.')
15046 error (_("Failed to sync event-tracing config: %s"), buf
+ 2);
15048 error (_("Failed to sync event-tracing config."));
15051 rs
->btrace_config
.pt
.event_tracing
= conf
->pt
.event_tracing
;
15055 /* Read TP's btrace configuration from the target and store it into CONF. */
15058 btrace_read_config (thread_info
*tp
, btrace_config
*conf
)
15060 /* target_read_stralloc relies on INFERIOR_PTID. */
15061 scoped_restore_current_thread restore_thread
;
15062 switch_to_thread (tp
);
15064 std::optional
<gdb::char_vector
> xml
15065 = target_read_stralloc (current_inferior ()->top_target (),
15066 TARGET_OBJECT_BTRACE_CONF
, "");
15068 parse_xml_btrace_conf (conf
, xml
->data ());
15071 /* Maybe reopen target btrace. */
15074 remote_target::remote_btrace_maybe_reopen ()
15076 struct remote_state
*rs
= get_remote_state ();
15077 int btrace_target_pushed
= 0;
15078 #if !defined (HAVE_LIBIPT)
15082 /* Don't bother walking the entirety of the remote thread list when
15083 we know the feature isn't supported by the remote. */
15084 if (m_features
.packet_support (PACKET_qXfer_btrace_conf
) != PACKET_ENABLE
)
15087 for (thread_info
*tp
: all_non_exited_threads (this))
15089 memset (&rs
->btrace_config
, 0x00, sizeof (struct btrace_config
));
15090 btrace_read_config (tp
, &rs
->btrace_config
);
15092 if (rs
->btrace_config
.format
== BTRACE_FORMAT_NONE
)
15095 #if !defined (HAVE_LIBIPT)
15096 if (rs
->btrace_config
.format
== BTRACE_FORMAT_PT
)
15101 warning (_("Target is recording using Intel Processor Trace "
15102 "but support was disabled at compile time."));
15107 #endif /* !defined (HAVE_LIBIPT) */
15109 /* Push target, once, but before anything else happens. This way our
15110 changes to the threads will be cleaned up by unpushing the target
15111 in case btrace_read_config () throws. */
15112 if (!btrace_target_pushed
)
15114 btrace_target_pushed
= 1;
15115 record_btrace_push_target ();
15116 gdb_printf (_("Target is recording using %s.\n"),
15117 btrace_format_string (rs
->btrace_config
.format
));
15121 = new btrace_target_info
{ tp
->ptid
, rs
->btrace_config
};
15125 /* Enable branch tracing. */
15127 struct btrace_target_info
*
15128 remote_target::enable_btrace (thread_info
*tp
,
15129 const struct btrace_config
*conf
)
15131 struct packet_config
*packet
= NULL
;
15132 struct remote_state
*rs
= get_remote_state ();
15133 char *buf
= rs
->buf
.data ();
15134 char *endbuf
= buf
+ get_remote_packet_size ();
15136 unsigned int which_packet
;
15137 switch (conf
->format
)
15139 case BTRACE_FORMAT_BTS
:
15140 which_packet
= PACKET_Qbtrace_bts
;
15142 case BTRACE_FORMAT_PT
:
15143 which_packet
= PACKET_Qbtrace_pt
;
15146 internal_error (_("Bad branch btrace format: %u."),
15147 (unsigned int) conf
->format
);
15150 packet
= &m_features
.m_protocol_packets
[which_packet
];
15151 if (packet
== NULL
|| packet_config_support (packet
) != PACKET_ENABLE
)
15152 error (_("Target does not support branch tracing."));
15154 btrace_sync_conf (conf
);
15156 ptid_t ptid
= tp
->ptid
;
15157 set_general_thread (ptid
);
15159 buf
+= xsnprintf (buf
, endbuf
- buf
, "%s",
15160 packets_descriptions
[which_packet
].name
);
15164 packet_result result
= m_features
.packet_ok (rs
->buf
, which_packet
);
15165 if (result
.status () == PACKET_ERROR
)
15166 error (_("Could not enable branch tracing for %s: %s"),
15167 target_pid_to_str (ptid
).c_str (), result
.err_msg ());
15169 btrace_target_info
*tinfo
= new btrace_target_info
{ ptid
};
15171 /* If we fail to read the configuration, we lose some information, but the
15172 tracing itself is not impacted. */
15175 btrace_read_config (tp
, &tinfo
->conf
);
15177 catch (const gdb_exception_error
&err
)
15179 if (err
.message
!= NULL
)
15180 warning ("%s", err
.what ());
15186 /* Disable branch tracing. */
15189 remote_target::disable_btrace (struct btrace_target_info
*tinfo
)
15191 struct remote_state
*rs
= get_remote_state ();
15192 char *buf
= rs
->buf
.data ();
15193 char *endbuf
= buf
+ get_remote_packet_size ();
15195 if (m_features
.packet_support (PACKET_Qbtrace_off
) != PACKET_ENABLE
)
15196 error (_("Target does not support branch tracing."));
15198 set_general_thread (tinfo
->ptid
);
15200 buf
+= xsnprintf (buf
, endbuf
- buf
, "%s",
15201 packets_descriptions
[PACKET_Qbtrace_off
].name
);
15205 packet_result result
= m_features
.packet_ok (rs
->buf
, PACKET_Qbtrace_off
);
15206 if (result
.status () == PACKET_ERROR
)
15207 error (_("Could not disable branch tracing for %s: %s"),
15208 target_pid_to_str (tinfo
->ptid
).c_str (), result
.err_msg ());
15213 /* Teardown branch tracing. */
15216 remote_target::teardown_btrace (struct btrace_target_info
*tinfo
)
15218 /* We must not talk to the target during teardown. */
15222 /* Read the branch trace. */
15225 remote_target::read_btrace (struct btrace_data
*btrace
,
15226 struct btrace_target_info
*tinfo
,
15227 enum btrace_read_type type
)
15231 if (m_features
.packet_support (PACKET_qXfer_btrace
) != PACKET_ENABLE
)
15232 error (_("Target does not support branch tracing."));
15234 #if !defined(HAVE_LIBEXPAT)
15235 error (_("Cannot process branch tracing result. XML parsing not supported."));
15240 case BTRACE_READ_ALL
:
15243 case BTRACE_READ_NEW
:
15246 case BTRACE_READ_DELTA
:
15250 internal_error (_("Bad branch tracing read type: %u."),
15251 (unsigned int) type
);
15254 std::optional
<gdb::char_vector
> xml
15255 = target_read_stralloc (current_inferior ()->top_target (),
15256 TARGET_OBJECT_BTRACE
, annex
);
15258 return BTRACE_ERR_UNKNOWN
;
15260 parse_xml_btrace (btrace
, xml
->data ());
15262 return BTRACE_ERR_NONE
;
15265 const struct btrace_config
*
15266 remote_target::btrace_conf (const struct btrace_target_info
*tinfo
)
15268 return &tinfo
->conf
;
15272 remote_target::augmented_libraries_svr4_read ()
15275 (m_features
.packet_support (PACKET_augmented_libraries_svr4_read_feature
)
15279 /* Implementation of to_load. */
15282 remote_target::load (const char *name
, int from_tty
)
15284 generic_load (name
, from_tty
);
15287 /* Accepts an integer PID; returns a string representing a file that
15288 can be opened on the remote side to get the symbols for the child
15289 process. Returns NULL if the operation is not supported. */
15292 remote_target::pid_to_exec_file (int pid
)
15294 static std::optional
<gdb::char_vector
> filename
;
15295 char *annex
= NULL
;
15297 if (m_features
.packet_support (PACKET_qXfer_exec_file
) != PACKET_ENABLE
)
15300 inferior
*inf
= find_inferior_pid (this, pid
);
15302 internal_error (_("not currently attached to process %d"), pid
);
15304 if (!inf
->fake_pid_p
)
15306 const int annex_size
= 9;
15308 annex
= (char *) alloca (annex_size
);
15309 xsnprintf (annex
, annex_size
, "%x", pid
);
15312 filename
= target_read_stralloc (current_inferior ()->top_target (),
15313 TARGET_OBJECT_EXEC_FILE
, annex
);
15315 return filename
? filename
->data () : nullptr;
15318 /* Implement the to_can_do_single_step target_ops method. */
15321 remote_target::can_do_single_step ()
15323 /* We can only tell whether target supports single step or not by
15324 supported s and S vCont actions if the stub supports vContSupported
15325 feature. If the stub doesn't support vContSupported feature,
15326 we have conservatively to think target doesn't supports single
15328 if (m_features
.packet_support (PACKET_vContSupported
) == PACKET_ENABLE
)
15330 struct remote_state
*rs
= get_remote_state ();
15332 return rs
->supports_vCont
.s
&& rs
->supports_vCont
.S
;
15338 /* Implementation of the to_execution_direction method for the remote
15341 enum exec_direction_kind
15342 remote_target::execution_direction ()
15344 struct remote_state
*rs
= get_remote_state ();
15346 return rs
->last_resume_exec_dir
;
15349 /* Return pointer to the thread_info struct which corresponds to
15350 THREAD_HANDLE (having length HANDLE_LEN). */
15353 remote_target::thread_handle_to_thread_info (const gdb_byte
*thread_handle
,
15357 for (thread_info
*tp
: all_non_exited_threads (this))
15359 remote_thread_info
*priv
= get_remote_thread_info (tp
);
15361 if (tp
->inf
== inf
&& priv
!= NULL
)
15363 if (handle_len
!= priv
->thread_handle
.size ())
15364 error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
15365 handle_len
, priv
->thread_handle
.size ());
15366 if (memcmp (thread_handle
, priv
->thread_handle
.data (),
15375 gdb::array_view
<const gdb_byte
>
15376 remote_target::thread_info_to_thread_handle (struct thread_info
*tp
)
15378 remote_thread_info
*priv
= get_remote_thread_info (tp
);
15379 return priv
->thread_handle
;
15383 remote_target::can_async_p ()
15385 /* This flag should be checked in the common target.c code. */
15386 gdb_assert (target_async_permitted
);
15388 /* We're async whenever the serial device can. */
15389 return get_remote_state ()->can_async_p ();
15393 remote_target::is_async_p ()
15395 /* We're async whenever the serial device is. */
15396 return get_remote_state ()->is_async_p ();
15399 /* Pass the SERIAL event on and up to the client. One day this code
15400 will be able to delay notifying the client of an event until the
15401 point where an entire packet has been received. */
15403 static serial_event_ftype remote_async_serial_handler
;
15406 remote_async_serial_handler (struct serial
*scb
, void *context
)
15408 /* Don't propagate error information up to the client. Instead let
15409 the client find out about the error by querying the target. */
15410 inferior_event_handler (INF_REG_EVENT
);
15414 remote_target::async_wait_fd ()
15416 struct remote_state
*rs
= get_remote_state ();
15417 return rs
->remote_desc
->fd
;
15421 remote_target::async (bool enable
)
15423 struct remote_state
*rs
= get_remote_state ();
15427 serial_async (rs
->remote_desc
, remote_async_serial_handler
, rs
);
15429 /* If there are pending events in the stop reply queue tell the
15430 event loop to process them. */
15431 if (!rs
->stop_reply_queue
.empty ())
15432 rs
->mark_async_event_handler ();
15434 /* For simplicity, below we clear the pending events token
15435 without remembering whether it is marked, so here we always
15436 mark it. If there's actually no pending notification to
15437 process, this ends up being a no-op (other than a spurious
15438 event-loop wakeup). */
15439 if (target_is_non_stop_p ())
15440 mark_async_event_handler (rs
->notif_state
->get_pending_events_token
);
15444 serial_async (rs
->remote_desc
, NULL
, NULL
);
15445 /* If the core is disabling async, it doesn't want to be
15446 disturbed with target events. Clear all async event sources
15448 rs
->clear_async_event_handler ();
15450 if (target_is_non_stop_p ())
15451 clear_async_event_handler (rs
->notif_state
->get_pending_events_token
);
15455 /* Implementation of the to_thread_events method. */
15458 remote_target::thread_events (bool enable
)
15460 struct remote_state
*rs
= get_remote_state ();
15461 size_t size
= get_remote_packet_size ();
15463 if (m_features
.packet_support (PACKET_QThreadEvents
) == PACKET_DISABLE
)
15466 if (rs
->last_thread_events
== enable
)
15469 xsnprintf (rs
->buf
.data (), size
, "QThreadEvents:%x", enable
? 1 : 0);
15473 packet_result result
= m_features
.packet_ok (rs
->buf
, PACKET_QThreadEvents
);
15474 switch (result
.status ())
15477 if (strcmp (rs
->buf
.data (), "OK") != 0)
15478 error (_("Remote refused setting thread events: %s"), rs
->buf
.data ());
15479 rs
->last_thread_events
= enable
;
15482 warning (_("Remote failure reply: %s"), result
.err_msg ());
15484 case PACKET_UNKNOWN
:
15489 /* Implementation of the supports_set_thread_options target
15493 remote_target::supports_set_thread_options (gdb_thread_options options
)
15495 remote_state
*rs
= get_remote_state ();
15496 return (m_features
.packet_support (PACKET_QThreadOptions
) == PACKET_ENABLE
15497 && (rs
->supported_thread_options
& options
) == options
);
15500 /* For coalescing reasons, actually sending the options to the target
15501 happens at resume time, via this function. See target_resume for
15502 all-stop, and target_commit_resumed for non-stop. */
15505 remote_target::commit_requested_thread_options ()
15507 struct remote_state
*rs
= get_remote_state ();
15509 if (m_features
.packet_support (PACKET_QThreadOptions
) != PACKET_ENABLE
)
15512 char *p
= rs
->buf
.data ();
15513 char *endp
= p
+ get_remote_packet_size ();
15515 /* Clear options for all threads by default. Note that unlike
15516 vCont, the rightmost options that match a thread apply, so we
15517 don't have to worry about whether we can use wildcard ptids. */
15518 strcpy (p
, "QThreadOptions;0");
15521 /* Send the QThreadOptions packet stored in P. */
15522 auto flush
= [&] ()
15527 getpkt (&rs
->buf
, 0);
15529 packet_result result
= m_features
.packet_ok (rs
->buf
, PACKET_QThreadOptions
);
15530 switch (result
.status ())
15533 if (strcmp (rs
->buf
.data (), "OK") != 0)
15534 error (_("Remote refused setting thread options: %s"), rs
->buf
.data ());
15537 error (_("Remote failure reply: %s"), result
.err_msg ());
15538 case PACKET_UNKNOWN
:
15539 gdb_assert_not_reached ("PACKET_UNKNOWN");
15544 /* Prepare P for another QThreadOptions packet. */
15545 auto restart
= [&] ()
15547 p
= rs
->buf
.data ();
15548 strcpy (p
, "QThreadOptions");
15552 /* Now set non-zero options for threads that need them. We don't
15553 bother with the case of all threads of a process wanting the same
15554 non-zero options as that's not an expected scenario. */
15555 for (thread_info
*tp
: all_non_exited_threads (this))
15557 gdb_thread_options options
= tp
->thread_options ();
15562 /* It might be possible to we have more threads with options
15563 than can fit a single QThreadOptions packet. So build each
15564 options/thread pair in this separate buffer to make sure it
15566 constexpr size_t max_options_size
= 100;
15567 char obuf
[max_options_size
];
15568 char *obuf_p
= obuf
;
15569 char *obuf_endp
= obuf
+ max_options_size
;
15572 obuf_p
+= xsnprintf (obuf_p
, obuf_endp
- obuf_p
, "%s",
15573 phex_nz (options
));
15574 if (tp
->ptid
!= magic_null_ptid
)
15577 obuf_p
= write_ptid (obuf_p
, obuf_endp
, tp
->ptid
);
15580 size_t osize
= obuf_p
- obuf
;
15581 if (osize
> endp
- p
)
15583 /* This new options/thread pair doesn't fit the packet
15584 buffer. Send what we have already. */
15588 /* Should now fit. */
15589 gdb_assert (osize
<= endp
- p
);
15592 memcpy (p
, obuf
, osize
);
15600 show_remote_cmd (const char *args
, int from_tty
)
15602 /* We can't just use cmd_show_list here, because we want to skip
15603 the redundant "show remote Z-packet" and the legacy aliases. */
15604 struct cmd_list_element
*list
= remote_show_cmdlist
;
15605 struct ui_out
*uiout
= current_uiout
;
15607 ui_out_emit_tuple
tuple_emitter (uiout
, "showlist");
15608 const ui_file_style cmd_style
= command_style
.style ();
15609 for (; list
!= NULL
; list
= list
->next
)
15610 if (strcmp (list
->name
, "Z-packet") == 0)
15612 else if (list
->type
== not_set_cmd
)
15613 /* Alias commands are exactly like the original, except they
15614 don't have the normal type. */
15618 ui_out_emit_tuple
option_emitter (uiout
, "option");
15620 uiout
->field_string ("name", list
->name
, cmd_style
);
15621 uiout
->text (": ");
15622 if (list
->type
== show_cmd
)
15623 do_show_command (NULL
, from_tty
, list
);
15625 cmd_func (list
, NULL
, from_tty
);
15629 /* Some change happened in PSPACE's objfile list (obfiles added or removed),
15630 offer all inferiors using that program space a change to look up symbols. */
15633 remote_objfile_changed_check_symbols (program_space
*pspace
)
15635 /* The affected program space is possibly shared by multiple inferiors.
15636 Consider sending a qSymbol packet for each of the inferiors using that
15638 for (inferior
*inf
: all_inferiors ())
15640 if (inf
->pspace
!= pspace
)
15643 /* Check whether the inferior's process target is a remote target. */
15644 remote_target
*remote
= as_remote_target (inf
->process_target ());
15645 if (remote
== nullptr)
15648 /* When we are attaching or handling a fork child and the shared library
15649 subsystem reads the list of loaded libraries, we receive new objfile
15650 events in between each found library. The libraries are read in an
15651 undefined order, so if we gave the remote side a chance to look up
15652 symbols between each objfile, we might give it an inconsistent picture
15653 of the inferior. It could appear that a library A appears loaded but
15654 a library B does not, even though library A requires library B. That
15655 would present a state that couldn't normally exist in the inferior.
15657 So, skip these events, we'll give the remote a chance to look up
15658 symbols once all the loaded libraries and their symbols are known to
15660 if (inf
->in_initial_library_scan
)
15663 if (!remote
->has_execution (inf
))
15666 /* Need to switch to a specific thread, because remote_check_symbols will
15667 set the general thread using INFERIOR_PTID.
15669 It's possible to have inferiors with no thread here, because we are
15670 called very early in the connection process, while the inferior is
15671 being set up, before threads are added. Just skip it, start_remote_1
15672 also calls remote_check_symbols when it's done setting things up. */
15673 thread_info
*thread
= any_thread_of_inferior (inf
);
15674 if (thread
!= nullptr)
15676 scoped_restore_current_thread restore_thread
;
15677 switch_to_thread (thread
);
15678 remote
->remote_check_symbols ();
15683 /* Function to be called whenever a new objfile (shlib) is detected. */
15686 remote_new_objfile (struct objfile
*objfile
)
15688 remote_objfile_changed_check_symbols (objfile
->pspace ());
15691 /* Pull all the tracepoints defined on the target and create local
15692 data structures representing them. We don't want to create real
15693 tracepoints yet, we don't want to mess up the user's existing
15697 remote_target::upload_tracepoints (struct uploaded_tp
**utpp
)
15699 struct remote_state
*rs
= get_remote_state ();
15702 /* Ask for a first packet of tracepoint definition. */
15705 p
= rs
->buf
.data ();
15706 while (*p
&& *p
!= 'l')
15708 parse_tracepoint_definition (p
, utpp
);
15709 /* Ask for another packet of tracepoint definition. */
15712 p
= rs
->buf
.data ();
15718 remote_target::upload_trace_state_variables (struct uploaded_tsv
**utsvp
)
15720 struct remote_state
*rs
= get_remote_state ();
15723 /* Ask for a first packet of variable definition. */
15726 p
= rs
->buf
.data ();
15727 while (*p
&& *p
!= 'l')
15729 parse_tsv_definition (p
, utsvp
);
15730 /* Ask for another packet of variable definition. */
15733 p
= rs
->buf
.data ();
15738 /* The "set/show range-stepping" show hook. */
15741 show_range_stepping (struct ui_file
*file
, int from_tty
,
15742 struct cmd_list_element
*c
,
15746 _("Debugger's willingness to use range stepping "
15747 "is %s.\n"), value
);
15750 /* Return true if the vCont;r action is supported by the remote
15754 remote_target::vcont_r_supported ()
15756 return (m_features
.packet_support (PACKET_vCont
) == PACKET_ENABLE
15757 && get_remote_state ()->supports_vCont
.r
);
15760 /* The "set/show range-stepping" set hook. */
15763 set_range_stepping (const char *ignore_args
, int from_tty
,
15764 struct cmd_list_element
*c
)
15766 /* When enabling, check whether range stepping is actually supported
15767 by the target, and warn if not. */
15768 if (use_range_stepping
)
15770 remote_target
*remote
= get_current_remote_target ();
15772 || !remote
->vcont_r_supported ())
15773 warning (_("Range stepping is not supported by the current target"));
15778 show_remote_debug (struct ui_file
*file
, int from_tty
,
15779 struct cmd_list_element
*c
, const char *value
)
15781 gdb_printf (file
, _("Debugging of remote protocol is %s.\n"),
15786 show_remote_timeout (struct ui_file
*file
, int from_tty
,
15787 struct cmd_list_element
*c
, const char *value
)
15790 _("Timeout limit to wait for target to respond is %s.\n"),
15794 /* Implement the "supports_memory_tagging" target_ops method. */
15797 remote_target::supports_memory_tagging ()
15799 return m_features
.remote_memory_tagging_p ();
15802 /* Create the qMemTags packet given ADDRESS, LEN and TYPE. */
15805 create_fetch_memtags_request (gdb::char_vector
&packet
, CORE_ADDR address
,
15806 size_t len
, int type
)
15808 int addr_size
= gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
15810 std::string request
= string_printf ("qMemTags:%s,%s:%s",
15811 phex_nz (address
, addr_size
),
15815 strcpy (packet
.data (), request
.c_str ());
15818 /* Parse the qMemTags packet reply into TAGS.
15820 Return true if successful, false otherwise. */
15823 parse_fetch_memtags_reply (const gdb::char_vector
&reply
,
15824 gdb::byte_vector
&tags
)
15826 if (reply
.empty () || reply
[0] == 'E' || reply
[0] != 'm')
15829 /* Copy the tag data. */
15830 tags
= hex2bin (reply
.data () + 1);
15835 /* Create the QMemTags packet given ADDRESS, LEN, TYPE and TAGS. */
15838 create_store_memtags_request (gdb::char_vector
&packet
, CORE_ADDR address
,
15839 size_t len
, int type
,
15840 const gdb::byte_vector
&tags
)
15842 int addr_size
= gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
15844 /* Put together the main packet, address and length. */
15845 std::string request
= string_printf ("QMemTags:%s,%s:%s:",
15846 phex_nz (address
, addr_size
),
15849 request
+= bin2hex (tags
.data (), tags
.size ());
15851 /* Check if we have exceeded the maximum packet size. */
15852 if (packet
.size () < request
.length ())
15853 error (_("Contents too big for packet QMemTags."));
15855 strcpy (packet
.data (), request
.c_str ());
15859 create_is_address_tagged_request (gdbarch
*gdbarch
, gdb::char_vector
&packet
,
15863 std::string request
;
15865 addr_size
= gdbarch_addr_bit (gdbarch
) / 8;
15866 request
= string_printf ("qIsAddressTagged:%s", phex_nz (address
, addr_size
));
15868 if (packet
.size () < request
.length () + 1)
15869 error (_("Contents too big for packet qIsAddressTagged."));
15871 strcpy (packet
.data (), request
.c_str ());
15875 check_is_address_tagged_reply (remote_target
*remote
, gdb::char_vector
&packet
,
15878 gdb_assert (remote
!= nullptr);
15879 /* Check reply and disable qIsAddressTagged usage if it's not supported. */
15880 packet_result result
= remote
->m_features
.packet_ok (packet
,
15881 PACKET_qIsAddressTagged
);
15883 /* Return false on error (Exx), empty reply (packet not supported), or reply
15884 size doesn't match 2 hex digits. */
15885 if ((result
.status () != PACKET_OK
) || (strlen (packet
.data ()) != 2))
15889 /* Convert only 2 hex digits, i.e. 1 byte in hex format. */
15890 hex2bin (packet
.data (), &reply
, 1);
15892 if (reply
== 0x00 || reply
== 0x01)
15898 /* Invalid reply. */
15902 /* Implement the "fetch_memtags" target_ops method. */
15905 remote_target::fetch_memtags (CORE_ADDR address
, size_t len
,
15906 gdb::byte_vector
&tags
, int type
)
15908 /* Make sure the qMemTags packet is supported. */
15909 if (!m_features
.remote_memory_tagging_p ())
15910 gdb_assert_not_reached ("remote fetch_memtags called with packet disabled");
15912 struct remote_state
*rs
= get_remote_state ();
15914 create_fetch_memtags_request (rs
->buf
, address
, len
, type
);
15919 return parse_fetch_memtags_reply (rs
->buf
, tags
);
15922 /* Implement the "store_memtags" target_ops method. */
15925 remote_target::store_memtags (CORE_ADDR address
, size_t len
,
15926 const gdb::byte_vector
&tags
, int type
)
15928 /* Make sure the QMemTags packet is supported. */
15929 if (!m_features
.remote_memory_tagging_p ())
15930 gdb_assert_not_reached ("remote store_memtags called with packet disabled");
15932 struct remote_state
*rs
= get_remote_state ();
15934 create_store_memtags_request (rs
->buf
, address
, len
, type
, tags
);
15939 /* Verify if the request was successful. */
15940 return packet_check_result (rs
->buf
).status () == PACKET_OK
;
15943 /* Implement the "is_address_tagged" target_ops method. */
15946 remote_target::is_address_tagged (gdbarch
*gdbarch
, CORE_ADDR address
)
15948 /* Firstly, attempt to check the address using the qIsAddressTagged
15950 if (m_features
.packet_support (PACKET_qIsAddressTagged
) != PACKET_DISABLE
)
15952 remote_target
*remote
= get_current_remote_target ();
15953 struct remote_state
*rs
= get_remote_state ();
15954 bool is_addr_tagged
;
15956 create_is_address_tagged_request (gdbarch
, rs
->buf
, address
);
15961 /* If qIsAddressTagged is not supported PACKET_qIsAddressTagged will be
15962 set to PACKET_DISABLE so no further attempt is made to check addresses
15963 using this packet and the fallback mechanism below will be used
15964 instead. Also, if the check fails due to an error (Exx reply) the
15965 fallback is used too. Otherwise, the qIsAddressTagged query succeeded
15966 and is_addr_tagged is valid. */
15967 if (check_is_address_tagged_reply (remote
, rs
->buf
, is_addr_tagged
))
15968 return is_addr_tagged
;
15971 /* Fallback to arch-specific method of checking whether an address is tagged
15972 in case check via qIsAddressTagged fails. */
15973 return gdbarch_tagged_address_p (gdbarch
, address
);
15976 /* Return true if remote target T is non-stop. */
15979 remote_target_is_non_stop_p (remote_target
*t
)
15981 scoped_restore_current_thread restore_thread
;
15982 switch_to_target_no_thread (t
);
15984 return target_is_non_stop_p ();
15989 namespace selftests
{
15992 test_memory_tagging_functions ()
15994 remote_target remote
;
15996 struct packet_config
*config
15997 = &remote
.m_features
.m_protocol_packets
[PACKET_memory_tagging_feature
];
15999 scoped_restore restore_memtag_support_
16000 = make_scoped_restore (&config
->support
);
16002 struct gdbarch
*gdbarch
= current_inferior ()->arch ();
16004 /* Test memory tagging packet support. */
16005 config
->support
= PACKET_SUPPORT_UNKNOWN
;
16006 SELF_CHECK (remote
.supports_memory_tagging () == false);
16007 config
->support
= PACKET_DISABLE
;
16008 SELF_CHECK (remote
.supports_memory_tagging () == false);
16009 config
->support
= PACKET_ENABLE
;
16010 SELF_CHECK (remote
.supports_memory_tagging () == true);
16012 /* Setup testing. */
16013 gdb::char_vector packet
;
16014 gdb::byte_vector tags
, bv
;
16015 std::string expected
, reply
;
16016 packet
.resize (32000);
16018 /* Test creating a qMemTags request. */
16020 expected
= "qMemTags:0,0:0";
16021 create_fetch_memtags_request (packet
, 0x0, 0x0, 0);
16022 SELF_CHECK (strcmp (packet
.data (), expected
.c_str ()) == 0);
16024 expected
= "qMemTags:deadbeef,10:1";
16025 create_fetch_memtags_request (packet
, 0xdeadbeef, 16, 1);
16026 SELF_CHECK (strcmp (packet
.data (), expected
.c_str ()) == 0);
16028 /* Test parsing a qMemTags reply. */
16030 /* Error reply, tags vector unmodified. */
16032 strcpy (packet
.data (), reply
.c_str ());
16034 SELF_CHECK (parse_fetch_memtags_reply (packet
, tags
) == false);
16035 SELF_CHECK (tags
.size () == 0);
16037 /* Valid reply, tags vector updated. */
16041 for (int i
= 0; i
< 5; i
++)
16044 reply
= "m" + bin2hex (bv
.data (), bv
.size ());
16045 strcpy (packet
.data (), reply
.c_str ());
16047 SELF_CHECK (parse_fetch_memtags_reply (packet
, tags
) == true);
16048 SELF_CHECK (tags
.size () == 5);
16050 for (int i
= 0; i
< 5; i
++)
16051 SELF_CHECK (tags
[i
] == i
);
16053 /* Test creating a QMemTags request. */
16055 /* Empty tag data. */
16057 expected
= "QMemTags:0,0:0:";
16058 create_store_memtags_request (packet
, 0x0, 0x0, 0, tags
);
16059 SELF_CHECK (memcmp (packet
.data (), expected
.c_str (),
16060 expected
.length ()) == 0);
16062 /* Non-empty tag data. */
16064 for (int i
= 0; i
< 5; i
++)
16065 tags
.push_back (i
);
16066 expected
= "QMemTags:deadbeef,ff:1:0001020304";
16067 create_store_memtags_request (packet
, 0xdeadbeef, 255, 1, tags
);
16068 SELF_CHECK (memcmp (packet
.data (), expected
.c_str (),
16069 expected
.length ()) == 0);
16071 /* Test creating a qIsAddressTagged request. */
16072 expected
= "qIsAddressTagged:deadbeef";
16073 create_is_address_tagged_request (gdbarch
, packet
, 0xdeadbeef);
16074 SELF_CHECK (strcmp (packet
.data (), expected
.c_str ()) == 0);
16076 /* Test error reply on qIsAddressTagged request. */
16078 strcpy (packet
.data (), reply
.c_str ());
16079 /* is_tagged must not change, hence it's tested too. */
16080 bool is_tagged
= false;
16081 SELF_CHECK (check_is_address_tagged_reply (&remote
, packet
, is_tagged
) ==
16083 SELF_CHECK (is_tagged
== false);
16085 /* Test 'tagged' as reply. */
16087 strcpy (packet
.data (), reply
.c_str ());
16088 /* Because the byte is 01, is_tagged should be set to true. */
16090 SELF_CHECK (check_is_address_tagged_reply (&remote
, packet
, is_tagged
) ==
16092 SELF_CHECK (is_tagged
== true);
16094 /* Test 'not tagged' as reply. */
16096 strcpy (packet
.data (), reply
.c_str ());
16097 /* Because the byte is 00, is_tagged should be set to false. */
16099 SELF_CHECK (check_is_address_tagged_reply (&remote
, packet
, is_tagged
) ==
16101 SELF_CHECK (is_tagged
== false);
16103 /* Test an invalid reply (neither 00 nor 01). */
16105 strcpy (packet
.data (), reply
.c_str ());
16106 /* Because the byte is invalid is_tagged must not change. */
16108 SELF_CHECK (check_is_address_tagged_reply (&remote
, packet
, is_tagged
) ==
16110 SELF_CHECK (is_tagged
== false);
16112 /* Test malformed reply of incorrect length. */
16113 reply
= "0104A590001234006";
16114 strcpy (packet
.data (), reply
.c_str ());
16115 /* Because this is a malformed reply is_tagged must not change. */
16117 SELF_CHECK (check_is_address_tagged_reply (&remote
, packet
, is_tagged
) ==
16119 SELF_CHECK (is_tagged
== false);
16121 /* Test empty reply. */
16123 strcpy (packet
.data (), reply
.c_str ());
16124 /* is_tagged must not change, hence it's tested too. */
16126 /* On the previous tests, qIsAddressTagged packet was auto detected and set
16127 as supported. But an empty reply means the packet is unsupported, so for
16128 testing the empty reply the support is reset to unknown state, otherwise
16129 packet_ok will complain. */
16130 remote
.m_features
.m_protocol_packets
[PACKET_qIsAddressTagged
].support
=
16131 PACKET_SUPPORT_UNKNOWN
;
16132 SELF_CHECK (check_is_address_tagged_reply (&remote
, packet
, is_tagged
) ==
16134 SELF_CHECK (is_tagged
== true);
16138 test_packet_check_result ()
16140 std::string buf
= "E.msg";
16141 packet_result result
= packet_check_result (buf
.data ());
16143 SELF_CHECK (result
.status () == PACKET_ERROR
);
16144 SELF_CHECK (strcmp(result
.err_msg (), "msg") == 0);
16146 result
= packet_check_result ("E01");
16147 SELF_CHECK (result
.status () == PACKET_ERROR
);
16148 SELF_CHECK (strcmp(result
.err_msg (), "01") == 0);
16150 SELF_CHECK (packet_check_result ("E1").status () == PACKET_OK
);
16152 SELF_CHECK (packet_check_result ("E000").status () == PACKET_OK
);
16154 result
= packet_check_result ("E.");
16155 SELF_CHECK (result
.status () == PACKET_ERROR
);
16156 SELF_CHECK (strcmp(result
.err_msg (), "no error provided") == 0);
16158 SELF_CHECK (packet_check_result ("some response").status () == PACKET_OK
);
16160 SELF_CHECK (packet_check_result ("").status () == PACKET_UNKNOWN
);
16162 } /* namespace selftests */
16163 #endif /* GDB_SELF_TEST */
16165 INIT_GDB_FILE (remote
)
16167 add_target (remote_target_info
, remote_target::open
);
16168 add_target (extended_remote_target_info
, extended_remote_target::open
);
16170 /* Hook into new objfile notification. */
16171 gdb::observers::new_objfile
.attach (remote_new_objfile
, "remote");
16172 gdb::observers::all_objfiles_removed
.attach
16173 (remote_objfile_changed_check_symbols
, "remote");
16176 init_remote_threadtests ();
16179 /* set/show remote ... */
16181 add_basic_prefix_cmd ("remote", class_maintenance
, _("\
16182 Remote protocol specific variables.\n\
16183 Configure various remote-protocol specific variables such as\n\
16184 the packets being used."),
16185 &remote_set_cmdlist
,
16186 0 /* allow-unknown */, &setlist
);
16187 add_prefix_cmd ("remote", class_maintenance
, show_remote_cmd
, _("\
16188 Remote protocol specific variables.\n\
16189 Configure various remote-protocol specific variables such as\n\
16190 the packets being used."),
16191 &remote_show_cmdlist
,
16192 0 /* allow-unknown */, &showlist
);
16194 add_cmd ("compare-sections", class_obscure
, compare_sections_command
, _("\
16195 Compare section data on target to the exec file.\n\
16196 Argument is a single section name (default: all loaded sections).\n\
16197 To compare only read-only loaded sections, specify the -r option."),
16200 add_cmd ("packet", class_maintenance
, cli_packet_command
, _("\
16201 Send an arbitrary packet to a remote target.\n\
16202 maintenance packet TEXT\n\
16203 If GDB is talking to an inferior via the GDB serial protocol, then\n\
16204 this command sends the string TEXT to the inferior, and displays the\n\
16205 response packet. GDB supplies the initial `$' character, and the\n\
16206 terminating `#' character and checksum."),
16209 set_show_commands remotebreak_cmds
16210 = add_setshow_boolean_cmd ("remotebreak", no_class
, &remote_break
, _("\
16211 Set whether to send break if interrupted."), _("\
16212 Show whether to send break if interrupted."), _("\
16213 If set, a break, instead of a cntrl-c, is sent to the remote target."),
16214 set_remotebreak
, show_remotebreak
,
16215 &setlist
, &showlist
);
16216 deprecate_cmd (remotebreak_cmds
.set
, "set remote interrupt-sequence");
16217 deprecate_cmd (remotebreak_cmds
.show
, "show remote interrupt-sequence");
16219 add_setshow_enum_cmd ("interrupt-sequence", class_support
,
16220 interrupt_sequence_modes
, &interrupt_sequence_mode
,
16222 Set interrupt sequence to remote target."), _("\
16223 Show interrupt sequence to remote target."), _("\
16224 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
16225 NULL
, show_interrupt_sequence
,
16226 &remote_set_cmdlist
,
16227 &remote_show_cmdlist
);
16229 add_setshow_boolean_cmd ("interrupt-on-connect", class_support
,
16230 &interrupt_on_connect
, _("\
16231 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
16232 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
16233 If set, interrupt sequence is sent to remote target."),
16235 &remote_set_cmdlist
, &remote_show_cmdlist
);
16237 /* Install commands for configuring memory read/write packets. */
16239 add_cmd ("remotewritesize", no_class
, set_memory_write_packet_size
, _("\
16240 Set the maximum number of bytes per memory write packet (deprecated)."),
16242 add_cmd ("remotewritesize", no_class
, show_memory_write_packet_size
, _("\
16243 Show the maximum number of bytes per memory write packet (deprecated)."),
16245 add_cmd ("memory-write-packet-size", no_class
,
16246 set_memory_write_packet_size
, _("\
16247 Set the maximum number of bytes per memory-write packet.\n\
16248 Specify the number of bytes in a packet or 0 (zero) for the\n\
16249 default packet size. The actual limit is further reduced\n\
16250 dependent on the target. Specify \"fixed\" to disable the\n\
16251 further restriction and \"limit\" to enable that restriction."),
16252 &remote_set_cmdlist
);
16253 add_cmd ("memory-read-packet-size", no_class
,
16254 set_memory_read_packet_size
, _("\
16255 Set the maximum number of bytes per memory-read packet.\n\
16256 Specify the number of bytes in a packet or 0 (zero) for the\n\
16257 default packet size. The actual limit is further reduced\n\
16258 dependent on the target. Specify \"fixed\" to disable the\n\
16259 further restriction and \"limit\" to enable that restriction."),
16260 &remote_set_cmdlist
);
16261 add_cmd ("memory-write-packet-size", no_class
,
16262 show_memory_write_packet_size
,
16263 _("Show the maximum number of bytes per memory-write packet."),
16264 &remote_show_cmdlist
);
16265 add_cmd ("memory-read-packet-size", no_class
,
16266 show_memory_read_packet_size
,
16267 _("Show the maximum number of bytes per memory-read packet."),
16268 &remote_show_cmdlist
);
16270 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-limit", no_class
,
16271 &remote_hw_watchpoint_limit
, _("\
16272 Set the maximum number of target hardware watchpoints."), _("\
16273 Show the maximum number of target hardware watchpoints."), _("\
16274 Specify \"unlimited\" for unlimited hardware watchpoints."),
16275 NULL
, show_hardware_watchpoint_limit
,
16276 &remote_set_cmdlist
,
16277 &remote_show_cmdlist
);
16278 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-length-limit",
16280 &remote_hw_watchpoint_length_limit
, _("\
16281 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
16282 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
16283 Specify \"unlimited\" to allow watchpoints of unlimited size."),
16284 NULL
, show_hardware_watchpoint_length_limit
,
16285 &remote_set_cmdlist
, &remote_show_cmdlist
);
16286 add_setshow_zuinteger_unlimited_cmd ("hardware-breakpoint-limit", no_class
,
16287 &remote_hw_breakpoint_limit
, _("\
16288 Set the maximum number of target hardware breakpoints."), _("\
16289 Show the maximum number of target hardware breakpoints."), _("\
16290 Specify \"unlimited\" for unlimited hardware breakpoints."),
16291 NULL
, show_hardware_breakpoint_limit
,
16292 &remote_set_cmdlist
, &remote_show_cmdlist
);
16294 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure
,
16295 &remote_address_size
, _("\
16296 Set the maximum size of the address (in bits) in a memory packet."), _("\
16297 Show the maximum size of the address (in bits) in a memory packet."), NULL
,
16299 NULL
, /* FIXME: i18n: */
16300 &setlist
, &showlist
);
16302 init_all_packet_configs ();
16304 add_packet_config_cmd (PACKET_X
, "X", "binary-download", 1);
16306 add_packet_config_cmd (PACKET_x
, "x", "binary-upload", 0);
16308 add_packet_config_cmd (PACKET_vCont
, "vCont", "verbose-resume", 0);
16310 add_packet_config_cmd (PACKET_QPassSignals
, "QPassSignals", "pass-signals",
16313 add_packet_config_cmd (PACKET_QCatchSyscalls
, "QCatchSyscalls",
16314 "catch-syscalls", 0);
16316 add_packet_config_cmd (PACKET_QProgramSignals
, "QProgramSignals",
16317 "program-signals", 0);
16319 add_packet_config_cmd (PACKET_QSetWorkingDir
, "QSetWorkingDir",
16320 "set-working-dir", 0);
16322 add_packet_config_cmd (PACKET_QStartupWithShell
, "QStartupWithShell",
16323 "startup-with-shell", 0);
16325 add_packet_config_cmd (PACKET_QEnvironmentHexEncoded
,"QEnvironmentHexEncoded",
16326 "environment-hex-encoded", 0);
16328 add_packet_config_cmd (PACKET_QEnvironmentReset
, "QEnvironmentReset",
16329 "environment-reset", 0);
16331 add_packet_config_cmd (PACKET_QEnvironmentUnset
, "QEnvironmentUnset",
16332 "environment-unset", 0);
16334 add_packet_config_cmd (PACKET_qSymbol
, "qSymbol", "symbol-lookup", 0);
16336 add_packet_config_cmd (PACKET_P
, "P", "set-register", 1);
16338 add_packet_config_cmd (PACKET_p
, "p", "fetch-register", 1);
16340 add_packet_config_cmd (PACKET_Z0
, "Z0", "software-breakpoint", 0);
16342 add_packet_config_cmd (PACKET_Z1
, "Z1", "hardware-breakpoint", 0);
16344 add_packet_config_cmd (PACKET_Z2
, "Z2", "write-watchpoint", 0);
16346 add_packet_config_cmd (PACKET_Z3
, "Z3", "read-watchpoint", 0);
16348 add_packet_config_cmd (PACKET_Z4
, "Z4", "access-watchpoint", 0);
16350 add_packet_config_cmd (PACKET_qXfer_auxv
, "qXfer:auxv:read",
16351 "read-aux-vector", 0);
16353 add_packet_config_cmd (PACKET_qXfer_exec_file
, "qXfer:exec-file:read",
16354 "pid-to-exec-file", 0);
16356 add_packet_config_cmd (PACKET_qXfer_features
,
16357 "qXfer:features:read", "target-features", 0);
16359 add_packet_config_cmd (PACKET_qXfer_libraries
, "qXfer:libraries:read",
16360 "library-info", 0);
16362 add_packet_config_cmd (PACKET_qXfer_libraries_svr4
,
16363 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
16365 add_packet_config_cmd (PACKET_qXfer_memory_map
, "qXfer:memory-map:read",
16368 add_packet_config_cmd (PACKET_qXfer_osdata
, "qXfer:osdata:read", "osdata", 0);
16370 add_packet_config_cmd (PACKET_qXfer_threads
, "qXfer:threads:read", "threads",
16373 add_packet_config_cmd (PACKET_qXfer_siginfo_read
, "qXfer:siginfo:read",
16374 "read-siginfo-object", 0);
16376 add_packet_config_cmd (PACKET_qXfer_siginfo_write
, "qXfer:siginfo:write",
16377 "write-siginfo-object", 0);
16379 add_packet_config_cmd (PACKET_qXfer_traceframe_info
,
16380 "qXfer:traceframe-info:read", "traceframe-info", 0);
16382 add_packet_config_cmd (PACKET_qXfer_uib
, "qXfer:uib:read",
16383 "unwind-info-block", 0);
16385 add_packet_config_cmd (PACKET_qGetTLSAddr
, "qGetTLSAddr",
16386 "get-thread-local-storage-address", 0);
16388 add_packet_config_cmd (PACKET_qGetTIBAddr
, "qGetTIBAddr",
16389 "get-thread-information-block-address", 0);
16391 add_packet_config_cmd (PACKET_bc
, "bc", "reverse-continue", 0);
16393 add_packet_config_cmd (PACKET_bs
, "bs", "reverse-step", 0);
16395 add_packet_config_cmd (PACKET_qSupported
, "qSupported", "supported-packets",
16398 add_packet_config_cmd (PACKET_qSearch_memory
, "qSearch:memory",
16399 "search-memory", 0);
16401 add_packet_config_cmd (PACKET_qTStatus
, "qTStatus", "trace-status", 0);
16403 add_packet_config_cmd (PACKET_vFile_setfs
, "vFile:setfs", "hostio-setfs", 0);
16405 add_packet_config_cmd (PACKET_vFile_open
, "vFile:open", "hostio-open", 0);
16407 add_packet_config_cmd (PACKET_vFile_pread
, "vFile:pread", "hostio-pread", 0);
16409 add_packet_config_cmd (PACKET_vFile_pwrite
, "vFile:pwrite", "hostio-pwrite",
16412 add_packet_config_cmd (PACKET_vFile_close
, "vFile:close", "hostio-close", 0);
16414 add_packet_config_cmd (PACKET_vFile_unlink
, "vFile:unlink", "hostio-unlink",
16417 add_packet_config_cmd (PACKET_vFile_readlink
, "vFile:readlink",
16418 "hostio-readlink", 0);
16420 add_packet_config_cmd (PACKET_vFile_fstat
, "vFile:fstat", "hostio-fstat", 0);
16422 add_packet_config_cmd (PACKET_vFile_stat
, "vFile:stat", "hostio-stat", 0);
16424 add_packet_config_cmd (PACKET_vFile_lstat
, "vFile:lstat", "hostio-lstat", 0);
16426 add_packet_config_cmd (PACKET_vAttach
, "vAttach", "attach", 0);
16428 add_packet_config_cmd (PACKET_vRun
, "vRun", "run", 0);
16430 add_packet_config_cmd (PACKET_QStartNoAckMode
, "QStartNoAckMode", "noack", 0);
16432 add_packet_config_cmd (PACKET_vKill
, "vKill", "kill", 0);
16434 add_packet_config_cmd (PACKET_qAttached
, "qAttached", "query-attached", 0);
16436 add_packet_config_cmd (PACKET_ConditionalTracepoints
,
16437 "ConditionalTracepoints", "conditional-tracepoints",
16440 add_packet_config_cmd (PACKET_ConditionalBreakpoints
,
16441 "ConditionalBreakpoints", "conditional-breakpoints",
16444 add_packet_config_cmd (PACKET_BreakpointCommands
, "BreakpointCommands",
16445 "breakpoint-commands", 0);
16447 add_packet_config_cmd (PACKET_FastTracepoints
, "FastTracepoints",
16448 "fast-tracepoints", 0);
16450 add_packet_config_cmd (PACKET_TracepointSource
, "TracepointSource",
16451 "TracepointSource", 0);
16453 add_packet_config_cmd (PACKET_QAllow
, "QAllow", "allow", 0);
16455 add_packet_config_cmd (PACKET_StaticTracepoints
, "StaticTracepoints",
16456 "static-tracepoints", 0);
16458 add_packet_config_cmd (PACKET_InstallInTrace
, "InstallInTrace",
16459 "install-in-trace", 0);
16461 add_packet_config_cmd (PACKET_qXfer_statictrace_read
,
16462 "qXfer:statictrace:read", "read-sdata-object", 0);
16464 add_packet_config_cmd (PACKET_qXfer_fdpic
, "qXfer:fdpic:read",
16465 "read-fdpic-loadmap", 0);
16467 add_packet_config_cmd (PACKET_QDisableRandomization
, "QDisableRandomization",
16468 "disable-randomization", 0);
16470 add_packet_config_cmd (PACKET_QAgent
, "QAgent", "agent", 0);
16472 add_packet_config_cmd (PACKET_QTBuffer_size
, "QTBuffer:size",
16473 "trace-buffer-size", 0);
16475 add_packet_config_cmd (PACKET_Qbtrace_off
, "Qbtrace:off", "disable-btrace",
16478 add_packet_config_cmd (PACKET_Qbtrace_bts
, "Qbtrace:bts", "enable-btrace-bts",
16481 add_packet_config_cmd (PACKET_Qbtrace_pt
, "Qbtrace:pt", "enable-btrace-pt",
16484 add_packet_config_cmd (PACKET_qXfer_btrace
, "qXfer:btrace", "read-btrace", 0);
16486 add_packet_config_cmd (PACKET_qXfer_btrace_conf
, "qXfer:btrace-conf",
16487 "read-btrace-conf", 0);
16489 add_packet_config_cmd (PACKET_Qbtrace_conf_bts_size
, "Qbtrace-conf:bts:size",
16490 "btrace-conf-bts-size", 0);
16492 add_packet_config_cmd (PACKET_multiprocess_feature
, "multiprocess-feature",
16493 "multiprocess-feature", 0);
16495 add_packet_config_cmd (PACKET_swbreak_feature
, "swbreak-feature",
16496 "swbreak-feature", 0);
16498 add_packet_config_cmd (PACKET_hwbreak_feature
, "hwbreak-feature",
16499 "hwbreak-feature", 0);
16501 add_packet_config_cmd (PACKET_fork_event_feature
, "fork-event-feature",
16502 "fork-event-feature", 0);
16504 add_packet_config_cmd (PACKET_vfork_event_feature
, "vfork-event-feature",
16505 "vfork-event-feature", 0);
16507 add_packet_config_cmd (PACKET_Qbtrace_conf_pt_size
, "Qbtrace-conf:pt:size",
16508 "btrace-conf-pt-size", 0);
16510 add_packet_config_cmd (PACKET_Qbtrace_conf_pt_ptwrite
, "Qbtrace-conf:pt:ptwrite",
16511 "btrace-conf-pt-ptwrite", 0);
16513 add_packet_config_cmd (PACKET_Qbtrace_conf_pt_event_tracing
,
16514 "Qbtrace-conf:pt:event-tracing",
16515 "btrace-conf-pt-event-tracing", 0);
16517 add_packet_config_cmd (PACKET_vContSupported
, "vContSupported",
16518 "verbose-resume-supported", 0);
16520 add_packet_config_cmd (PACKET_exec_event_feature
, "exec-event-feature",
16521 "exec-event-feature", 0);
16523 add_packet_config_cmd (PACKET_vCtrlC
, "vCtrlC", "ctrl-c", 0);
16525 add_packet_config_cmd (PACKET_QThreadEvents
, "QThreadEvents", "thread-events",
16528 add_packet_config_cmd (PACKET_QThreadOptions
, "QThreadOptions",
16529 "thread-options", 0);
16531 add_packet_config_cmd (PACKET_no_resumed
, "N stop reply",
16532 "no-resumed-stop-reply", 0);
16534 add_packet_config_cmd (PACKET_memory_tagging_feature
,
16535 "memory-tagging-feature", "memory-tagging-feature", 0);
16537 add_packet_config_cmd (PACKET_qIsAddressTagged
,
16538 "qIsAddressTagged", "memory-tagging-address-check", 0);
16540 add_packet_config_cmd (PACKET_accept_error_message
,
16541 "error-message", "error-message", 0);
16543 /* Assert that we've registered "set remote foo-packet" commands
16544 for all packet configs. */
16548 for (i
= 0; i
< PACKET_MAX
; i
++)
16550 /* Ideally all configs would have a command associated. Some
16551 still don't though. */
16556 case PACKET_QNonStop
:
16557 case PACKET_EnableDisableTracepoints_feature
:
16558 case PACKET_tracenz_feature
:
16559 case PACKET_DisconnectedTracing_feature
:
16560 case PACKET_augmented_libraries_svr4_read_feature
:
16562 /* Additions to this list need to be well justified:
16563 pre-existing packets are OK; new packets are not. */
16571 /* This catches both forgetting to add a config command, and
16572 forgetting to remove a packet from the exception list. */
16573 gdb_assert (excepted
== (packets_descriptions
[i
].name
== NULL
));
16577 /* Keep the old ``set remote Z-packet ...'' working. Each individual
16578 Z sub-packet has its own set and show commands, but users may
16579 have sets to this variable in their .gdbinit files (or in their
16581 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure
,
16582 &remote_Z_packet_detect
, _("\
16583 Set use of remote protocol `Z' packets."), _("\
16584 Show use of remote protocol `Z' packets."), _("\
16585 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
16587 set_remote_protocol_Z_packet_cmd
,
16588 show_remote_protocol_Z_packet_cmd
,
16589 /* FIXME: i18n: Use of remote protocol
16590 `Z' packets is %s. */
16591 &remote_set_cmdlist
, &remote_show_cmdlist
);
16593 add_basic_prefix_cmd ("remote", class_files
, _("\
16594 Manipulate files on the remote system.\n\
16595 Transfer files to and from the remote target system."),
16597 0 /* allow-unknown */, &cmdlist
);
16599 add_cmd ("put", class_files
, remote_put_command
,
16600 _("Copy a local file to the remote system."),
16603 add_cmd ("get", class_files
, remote_get_command
,
16604 _("Copy a remote file to the local system."),
16607 add_cmd ("delete", class_files
, remote_delete_command
,
16608 _("Delete a remote file."),
16611 add_setshow_string_noescape_cmd ("exec-file", class_files
,
16612 &remote_exec_file_var
, _("\
16613 Set the remote pathname for \"run\"."), _("\
16614 Show the remote pathname for \"run\"."), NULL
,
16615 set_remote_exec_file
,
16616 show_remote_exec_file
,
16617 &remote_set_cmdlist
,
16618 &remote_show_cmdlist
);
16620 add_setshow_boolean_cmd ("range-stepping", class_run
,
16621 &use_range_stepping
, _("\
16622 Enable or disable range stepping."), _("\
16623 Show whether target-assisted range stepping is enabled."), _("\
16624 If on, and the target supports it, when stepping a source line, GDB\n\
16625 tells the target to step the corresponding range of addresses itself instead\n\
16626 of issuing multiple single-steps. This speeds up source level\n\
16627 stepping. If off, GDB always issues single-steps, even if range\n\
16628 stepping is supported by the target. The default is on."),
16629 set_range_stepping
,
16630 show_range_stepping
,
16634 add_setshow_zinteger_cmd ("watchdog", class_maintenance
, &watchdog
, _("\
16635 Set watchdog timer."), _("\
16636 Show watchdog timer."), _("\
16637 When non-zero, this timeout is used instead of waiting forever for a target\n\
16638 to finish a low-level step or continue operation. If the specified amount\n\
16639 of time passes without a response from the target, an error occurs."),
16642 &setlist
, &showlist
);
16644 add_setshow_zuinteger_unlimited_cmd ("remote-packet-max-chars", no_class
,
16645 &remote_packet_max_chars
, _("\
16646 Set the maximum number of characters to display for each remote packet."), _("\
16647 Show the maximum number of characters to display for each remote packet."), _("\
16648 Specify \"unlimited\" to display all the characters."),
16649 NULL
, show_remote_packet_max_chars
,
16650 &setdebuglist
, &showdebuglist
);
16652 add_setshow_boolean_cmd ("remote", no_class
, &remote_debug
,
16653 _("Set debugging of remote protocol."),
16654 _("Show debugging of remote protocol."),
16656 When enabled, each packet sent or received with the remote target\n\
16660 &setdebuglist
, &showdebuglist
);
16662 add_setshow_zuinteger_unlimited_cmd ("remotetimeout", no_class
,
16663 &remote_timeout
, _("\
16664 Set timeout limit to wait for target to respond."), _("\
16665 Show timeout limit to wait for target to respond."), _("\
16666 This value is used to set the time limit for gdb to wait for a response\n\
16667 from the target."),
16669 show_remote_timeout
,
16670 &setlist
, &showlist
);
16672 /* Eventually initialize fileio. See fileio.c */
16673 initialize_remote_fileio (&remote_set_cmdlist
, &remote_show_cmdlist
);
16676 selftests::register_test ("remote_memory_tagging",
16677 selftests::test_memory_tagging_functions
);
16678 selftests::register_test ("packet_check_result",
16679 selftests::test_packet_check_result
);