1 /* Remote target communications for serial-line targets in custom GDB protocol
3 Copyright (C) 1988-2023 Free Software Foundation, Inc.
5 This file is part of GDB.
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
20 /* See the GDB User Guide for details of the GDB remote protocol. */
30 #include "process-stratum-target.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 "target-descriptions.h"
44 #include "gdbsupport/filestuff.h"
45 #include "gdbsupport/rsp-low.h"
49 #include "gdbsupport/gdb_sys_time.h"
51 #include "gdbsupport/event-loop.h"
52 #include "event-top.h"
60 #include "remote-fileio.h"
61 #include "gdbsupport/fileio.h"
63 #include "xml-support.h"
65 #include "memory-map.h"
67 #include "tracepoint.h"
70 #include "gdbsupport/agent.h"
72 #include "record-btrace.h"
73 #include "gdbsupport/scoped_restore.h"
74 #include "gdbsupport/environ.h"
75 #include "gdbsupport/byte-vector.h"
76 #include "gdbsupport/search.h"
79 #include <unordered_map>
80 #include "async-event.h"
81 #include "gdbsupport/selftest.h"
83 /* The remote target. */
85 static const char remote_doc
[] = N_("\
86 Use a remote computer via a serial line, using a gdb-specific protocol.\n\
87 Specify the serial device it is connected to\n\
88 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).");
92 bool remote_debug
= false;
94 #define OPAQUETHREADBYTES 8
96 /* a 64 bit opaque identifier */
97 typedef unsigned char threadref
[OPAQUETHREADBYTES
];
99 struct gdb_ext_thread_info
;
100 struct threads_listing_context
;
101 typedef int (*rmt_thread_action
) (threadref
*ref
, void *context
);
102 struct protocol_feature
;
106 typedef std::unique_ptr
<stop_reply
> stop_reply_up
;
108 /* Generic configuration support for packets the stub optionally
109 supports. Allows the user to specify the use of the packet as well
110 as allowing GDB to auto-detect support in the remote stub. */
114 PACKET_SUPPORT_UNKNOWN
= 0,
119 /* Convert the packet support auto_boolean to a name used for gdb printing. */
122 get_packet_support_name (auto_boolean support
)
126 case AUTO_BOOLEAN_TRUE
:
128 case AUTO_BOOLEAN_FALSE
:
130 case AUTO_BOOLEAN_AUTO
:
133 gdb_assert_not_reached ("invalid var_auto_boolean");
137 /* Convert the target type (future remote target or currently connected target)
138 to a name used for gdb printing. */
141 get_target_type_name (bool target_connected
)
143 if (target_connected
)
144 return _("on the current remote target");
146 return _("on future remote targets");
149 /* Analyze a packet's return value and update the packet config
159 /* Enumeration of packets for a remote target. */
178 PACKET_vFile_readlink
,
181 PACKET_qXfer_features
,
182 PACKET_qXfer_exec_file
,
183 PACKET_qXfer_libraries
,
184 PACKET_qXfer_libraries_svr4
,
185 PACKET_qXfer_memory_map
,
187 PACKET_qXfer_threads
,
188 PACKET_qXfer_statictrace_read
,
189 PACKET_qXfer_traceframe_info
,
196 PACKET_QCatchSyscalls
,
197 PACKET_QProgramSignals
,
198 PACKET_QSetWorkingDir
,
199 PACKET_QStartupWithShell
,
200 PACKET_QEnvironmentHexEncoded
,
201 PACKET_QEnvironmentReset
,
202 PACKET_QEnvironmentUnset
,
204 PACKET_qSearch_memory
,
207 PACKET_QStartNoAckMode
,
209 PACKET_qXfer_siginfo_read
,
210 PACKET_qXfer_siginfo_write
,
213 /* Support for conditional tracepoints. */
214 PACKET_ConditionalTracepoints
,
216 /* Support for target-side breakpoint conditions. */
217 PACKET_ConditionalBreakpoints
,
219 /* Support for target-side breakpoint commands. */
220 PACKET_BreakpointCommands
,
222 /* Support for fast tracepoints. */
223 PACKET_FastTracepoints
,
225 /* Support for static tracepoints. */
226 PACKET_StaticTracepoints
,
228 /* Support for installing tracepoints while a trace experiment is
230 PACKET_InstallInTrace
,
234 PACKET_TracepointSource
,
237 PACKET_QDisableRandomization
,
239 PACKET_QTBuffer_size
,
245 /* Support for the QNonStop packet. */
248 /* Support for the QThreadEvents packet. */
249 PACKET_QThreadEvents
,
251 /* Support for the QThreadOptions packet. */
252 PACKET_QThreadOptions
,
254 /* Support for multi-process extensions. */
255 PACKET_multiprocess_feature
,
257 /* Support for enabling and disabling tracepoints while a trace
258 experiment is running. */
259 PACKET_EnableDisableTracepoints_feature
,
261 /* Support for collecting strings using the tracenz bytecode. */
262 PACKET_tracenz_feature
,
264 /* Support for continuing to run a trace experiment while GDB is
266 PACKET_DisconnectedTracing_feature
,
268 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
269 PACKET_augmented_libraries_svr4_read_feature
,
271 /* Support for the qXfer:btrace-conf:read packet. */
272 PACKET_qXfer_btrace_conf
,
274 /* Support for the Qbtrace-conf:bts:size packet. */
275 PACKET_Qbtrace_conf_bts_size
,
277 /* Support for swbreak+ feature. */
278 PACKET_swbreak_feature
,
280 /* Support for hwbreak+ feature. */
281 PACKET_hwbreak_feature
,
283 /* Support for fork events. */
284 PACKET_fork_event_feature
,
286 /* Support for vfork events. */
287 PACKET_vfork_event_feature
,
289 /* Support for the Qbtrace-conf:pt:size packet. */
290 PACKET_Qbtrace_conf_pt_size
,
292 /* Support for exec events. */
293 PACKET_exec_event_feature
,
295 /* Support for query supported vCont actions. */
296 PACKET_vContSupported
,
298 /* Support remote CTRL-C. */
301 /* Support TARGET_WAITKIND_NO_RESUMED. */
304 /* Support for memory tagging, allocation tag fetch/store
305 packets and the tag violation stop replies. */
306 PACKET_memory_tagging_feature
,
311 struct threads_listing_context
;
313 /* Stub vCont actions support.
315 Each field is a boolean flag indicating whether the stub reports
316 support for the corresponding action. */
318 struct vCont_action_support
333 /* About this many threadids fit in a packet. */
335 #define MAXTHREADLISTRESULTS 32
337 /* Data for the vFile:pread readahead cache. */
339 struct readahead_cache
341 /* Invalidate the readahead cache. */
344 /* Invalidate the readahead cache if it is holding data for FD. */
345 void invalidate_fd (int fd
);
347 /* Serve pread from the readahead cache. Returns number of bytes
348 read, or 0 if the request can't be served from the cache. */
349 int pread (int fd
, gdb_byte
*read_buf
, size_t len
, ULONGEST offset
);
351 /* The file descriptor for the file that is being cached. -1 if the
355 /* The offset into the file that the cache buffer corresponds
359 /* The buffer holding the cache contents. */
360 gdb::byte_vector buf
;
362 /* Cache hit and miss counters. */
363 ULONGEST hit_count
= 0;
364 ULONGEST miss_count
= 0;
367 /* Description of the remote protocol for a given architecture. */
371 long offset
; /* Offset into G packet. */
372 long regnum
; /* GDB's internal register number. */
373 LONGEST pnum
; /* Remote protocol register number. */
374 int in_g_packet
; /* Always part of G packet. */
375 /* long size in bytes; == register_size (arch, regnum);
377 /* char *name; == gdbarch_register_name (arch, regnum);
381 struct remote_arch_state
383 explicit remote_arch_state (struct gdbarch
*gdbarch
);
385 /* Description of the remote protocol registers. */
386 long sizeof_g_packet
;
388 /* Description of the remote protocol registers indexed by REGNUM
389 (making an array gdbarch_num_regs in size). */
390 std::unique_ptr
<packet_reg
[]> regs
;
392 /* This is the size (in chars) of the first response to the ``g''
393 packet. It is used as a heuristic when determining the maximum
394 size of memory-read and memory-write packets. A target will
395 typically only reserve a buffer large enough to hold the ``g''
396 packet. The size does not include packet overhead (headers and
398 long actual_register_packet_size
;
400 /* This is the maximum size (in chars) of a non read/write packet.
401 It is also used as a cap on the size of read/write packets. */
402 long remote_packet_size
;
405 /* Description of the remote protocol state for the currently
406 connected target. This is per-target state, and independent of the
407 selected architecture. */
416 /* Get the remote arch state for GDBARCH. */
417 struct remote_arch_state
*get_remote_arch_state (struct gdbarch
*gdbarch
);
419 void create_async_event_handler ()
421 gdb_assert (m_async_event_handler_token
== nullptr);
422 m_async_event_handler_token
423 = ::create_async_event_handler ([] (gdb_client_data data
)
425 inferior_event_handler (INF_REG_EVENT
);
430 void mark_async_event_handler ()
432 gdb_assert (this->is_async_p ());
433 ::mark_async_event_handler (m_async_event_handler_token
);
436 void clear_async_event_handler ()
437 { ::clear_async_event_handler (m_async_event_handler_token
); }
439 bool async_event_handler_marked () const
440 { return ::async_event_handler_marked (m_async_event_handler_token
); }
442 void delete_async_event_handler ()
444 if (m_async_event_handler_token
!= nullptr)
445 ::delete_async_event_handler (&m_async_event_handler_token
);
448 bool is_async_p () const
450 /* We're async whenever the serial device is. */
451 gdb_assert (this->remote_desc
!= nullptr);
452 return serial_is_async_p (this->remote_desc
);
455 bool can_async_p () const
457 /* We can async whenever the serial device can. */
458 gdb_assert (this->remote_desc
!= nullptr);
459 return serial_can_async_p (this->remote_desc
);
464 /* A buffer to use for incoming packets, and its current size. The
465 buffer is grown dynamically for larger incoming packets.
466 Outgoing packets may also be constructed in this buffer.
467 The size of the buffer is always at least REMOTE_PACKET_SIZE;
468 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
470 gdb::char_vector buf
;
472 /* True if we're going through initial connection setup (finding out
473 about the remote side's threads, relocating symbols, etc.). */
474 bool starting_up
= false;
476 /* If we negotiated packet size explicitly (and thus can bypass
477 heuristics for the largest packet size that will not overflow
478 a buffer in the stub), this will be set to that packet size.
479 Otherwise zero, meaning to use the guessed size. */
480 long explicit_packet_size
= 0;
482 /* True, if in no ack mode. That is, neither GDB nor the stub will
483 expect acks from each other. The connection is assumed to be
485 bool noack_mode
= false;
487 /* True if we're connected in extended remote mode. */
488 bool extended
= false;
490 /* True if we resumed the target and we're waiting for the target to
491 stop. In the mean time, we can't start another command/query.
492 The remote server wouldn't be ready to process it, so we'd
493 timeout waiting for a reply that would never come and eventually
494 we'd close the connection. This can happen in asynchronous mode
495 because we allow GDB commands while the target is running. */
496 bool waiting_for_stop_reply
= false;
498 /* The status of the stub support for the various vCont actions. */
499 vCont_action_support supports_vCont
;
501 /* True if the user has pressed Ctrl-C, but the target hasn't
502 responded to that. */
503 bool ctrlc_pending_p
= false;
505 /* True if we saw a Ctrl-C while reading or writing from/to the
506 remote descriptor. At that point it is not safe to send a remote
507 interrupt packet, so we instead remember we saw the Ctrl-C and
508 process it once we're done with sending/receiving the current
509 packet, which should be shortly. If however that takes too long,
510 and the user presses Ctrl-C again, we offer to disconnect. */
511 bool got_ctrlc_during_io
= false;
513 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
514 remote_open knows that we don't have a file open when the program
516 struct serial
*remote_desc
= nullptr;
518 /* These are the threads which we last sent to the remote system. The
519 TID member will be -1 for all or -2 for not sent yet. */
520 ptid_t general_thread
= null_ptid
;
521 ptid_t continue_thread
= null_ptid
;
523 /* This is the traceframe which we last selected on the remote system.
524 It will be -1 if no traceframe is selected. */
525 int remote_traceframe_number
= -1;
527 char *last_pass_packet
= nullptr;
529 /* The last QProgramSignals packet sent to the target. We bypass
530 sending a new program signals list down to the target if the new
531 packet is exactly the same as the last we sent. IOW, we only let
532 the target know about program signals list changes. */
533 char *last_program_signals_packet
= nullptr;
535 /* Similarly, the last QThreadEvents state we sent to the
537 bool last_thread_events
= false;
539 gdb_signal last_sent_signal
= GDB_SIGNAL_0
;
541 bool last_sent_step
= false;
543 /* The execution direction of the last resume we got. */
544 exec_direction_kind last_resume_exec_dir
= EXEC_FORWARD
;
546 char *finished_object
= nullptr;
547 char *finished_annex
= nullptr;
548 ULONGEST finished_offset
= 0;
550 /* Should we try the 'ThreadInfo' query packet?
552 This variable (NOT available to the user: auto-detect only!)
553 determines whether GDB will use the new, simpler "ThreadInfo"
554 query or the older, more complex syntax for thread queries.
555 This is an auto-detect variable (set to true at each connect,
556 and set to false when the target fails to recognize it). */
557 bool use_threadinfo_query
= false;
558 bool use_threadextra_query
= false;
560 threadref echo_nextthread
{};
561 threadref nextthread
{};
562 threadref resultthreadlist
[MAXTHREADLISTRESULTS
] {};
564 /* The state of remote notification. */
565 struct remote_notif_state
*notif_state
= nullptr;
567 /* The branch trace configuration. */
568 struct btrace_config btrace_config
{};
570 /* The argument to the last "vFile:setfs:" packet we sent, used
571 to avoid sending repeated unnecessary "vFile:setfs:" packets.
572 Initialized to -1 to indicate that no "vFile:setfs:" packet
573 has yet been sent. */
576 /* A readahead cache for vFile:pread. Often, reading a binary
577 involves a sequence of small reads. E.g., when parsing an ELF
578 file. A readahead cache helps mostly the case of remote
579 debugging on a connection with higher latency, due to the
580 request/reply nature of the RSP. We only cache data for a single
581 file descriptor at a time. */
582 struct readahead_cache readahead_cache
;
584 /* The list of already fetched and acknowledged stop events. This
585 queue is used for notification Stop, and other notifications
586 don't need queue for their events, because the notification
587 events of Stop can't be consumed immediately, so that events
588 should be queued first, and be consumed by remote_wait_{ns,as}
589 one per time. Other notifications can consume their events
590 immediately, so queue is not needed for them. */
591 std::vector
<stop_reply_up
> stop_reply_queue
;
593 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
594 ``forever'' still use the normal timeout mechanism. This is
595 currently used by the ASYNC code to guarentee that target reads
596 during the initial connect always time-out. Once getpkt has been
597 modified to return a timeout indication and, in turn
598 remote_wait()/wait_for_inferior() have gained a timeout parameter
600 bool wait_forever_enabled_p
= true;
602 /* The set of thread options the target reported it supports, via
604 gdb_thread_options supported_thread_options
= 0;
607 /* Asynchronous signal handle registered as event loop source for
608 when we have pending events ready to be passed to the core. */
609 async_event_handler
*m_async_event_handler_token
= nullptr;
611 /* Mapping of remote protocol data for each gdbarch. Usually there
612 is only one entry here, though we may see more with stubs that
613 support multi-process. */
614 std::unordered_map
<struct gdbarch
*, remote_arch_state
>
618 static const target_info remote_target_info
= {
620 N_("Remote target using gdb-specific protocol"),
624 /* Description of a remote packet. */
626 struct packet_description
628 /* Name of the packet used for gdb output. */
631 /* Title of the packet, used by the set/show remote name-packet
632 commands to identify the individual packages and gdb output. */
636 /* Configuration of a remote packet. */
640 /* If auto, GDB auto-detects support for this packet or feature,
641 either through qSupported, or by trying the packet and looking
642 at the response. If true, GDB assumes the target supports this
643 packet. If false, the packet is disabled. Configs that don't
644 have an associated command always have this set to auto. */
645 enum auto_boolean detect
;
647 /* Does the target support this packet? */
648 enum packet_support support
;
651 /* User configurable variables for the number of characters in a
652 memory read/write packet. MIN (rsa->remote_packet_size,
653 rsa->sizeof_g_packet) is the default. Some targets need smaller
654 values (fifo overruns, et.al.) and some users need larger values
655 (speed up transfers). The variables ``preferred_*'' (the user
656 request), ``current_*'' (what was actually set) and ``forced_*''
657 (Positive - a soft limit, negative - a hard limit). */
659 struct memory_packet_config
666 /* These global variables contain the default configuration for every new
667 remote_feature object. */
668 static memory_packet_config memory_read_packet_config
=
670 "memory-read-packet-size",
672 static memory_packet_config memory_write_packet_config
=
674 "memory-write-packet-size",
677 /* This global array contains packet descriptions (name and title). */
678 static packet_description packets_descriptions
[PACKET_MAX
];
679 /* This global array contains the default configuration for every new
680 per-remote target array. */
681 static packet_config remote_protocol_packets
[PACKET_MAX
];
683 /* Description of a remote target's features. It stores the configuration
684 and provides functions to determine supported features of the target. */
686 struct remote_features
690 m_memory_read_packet_config
= memory_read_packet_config
;
691 m_memory_write_packet_config
= memory_write_packet_config
;
693 std::copy (std::begin (remote_protocol_packets
),
694 std::end (remote_protocol_packets
),
695 std::begin (m_protocol_packets
));
697 ~remote_features () = default;
699 DISABLE_COPY_AND_ASSIGN (remote_features
);
701 /* Returns whether a given packet defined by its enum value is supported. */
702 enum packet_support
packet_support (int) const;
704 /* Returns the packet's corresponding "set remote foo-packet" command
705 state. See struct packet_config for more details. */
706 enum auto_boolean
packet_set_cmd_state (int packet
) const
707 { return m_protocol_packets
[packet
].detect
; }
709 /* Returns true if the multi-process extensions are in effect. */
710 int remote_multi_process_p () const
711 { return packet_support (PACKET_multiprocess_feature
) == PACKET_ENABLE
; }
713 /* Returns true if fork events are supported. */
714 int remote_fork_event_p () const
715 { return packet_support (PACKET_fork_event_feature
) == PACKET_ENABLE
; }
717 /* Returns true if vfork events are supported. */
718 int remote_vfork_event_p () const
719 { return packet_support (PACKET_vfork_event_feature
) == PACKET_ENABLE
; }
721 /* Returns true if exec events are supported. */
722 int remote_exec_event_p () const
723 { return packet_support (PACKET_exec_event_feature
) == PACKET_ENABLE
; }
725 /* Returns true if memory tagging is supported, false otherwise. */
726 bool remote_memory_tagging_p () const
727 { return packet_support (PACKET_memory_tagging_feature
) == PACKET_ENABLE
; }
729 /* Reset all packets back to "unknown support". Called when opening a
730 new connection to a remote target. */
731 void reset_all_packet_configs_support ();
733 /* Check result value in BUF for packet WHICH_PACKET and update the packet's
734 support configuration accordingly. */
735 packet_result
packet_ok (const char *buf
, const int which_packet
);
736 packet_result
packet_ok (const gdb::char_vector
&buf
, const int which_packet
);
738 /* Configuration of a remote target's memory read packet. */
739 memory_packet_config m_memory_read_packet_config
;
740 /* Configuration of a remote target's memory write packet. */
741 memory_packet_config m_memory_write_packet_config
;
743 /* The per-remote target array which stores a remote's packet
745 packet_config m_protocol_packets
[PACKET_MAX
];
748 class remote_target
: public process_stratum_target
751 remote_target () = default;
752 ~remote_target () override
;
754 const target_info
&info () const override
755 { return remote_target_info
; }
757 const char *connection_string () override
;
759 thread_control_capabilities
get_thread_control_capabilities () override
760 { return tc_schedlock
; }
762 /* Open a remote connection. */
763 static void open (const char *, int);
765 void close () override
;
767 void detach (inferior
*, int) override
;
768 void disconnect (const char *, int) override
;
770 void commit_requested_thread_options ();
772 void commit_resumed () override
;
773 void resume (ptid_t
, int, enum gdb_signal
) override
;
774 ptid_t
wait (ptid_t
, struct target_waitstatus
*, target_wait_flags
) override
;
775 bool has_pending_events () override
;
777 void fetch_registers (struct regcache
*, int) override
;
778 void store_registers (struct regcache
*, int) override
;
779 void prepare_to_store (struct regcache
*) override
;
781 int insert_breakpoint (struct gdbarch
*, struct bp_target_info
*) override
;
783 int remove_breakpoint (struct gdbarch
*, struct bp_target_info
*,
784 enum remove_bp_reason
) override
;
787 bool stopped_by_sw_breakpoint () override
;
788 bool supports_stopped_by_sw_breakpoint () override
;
790 bool stopped_by_hw_breakpoint () override
;
792 bool supports_stopped_by_hw_breakpoint () override
;
794 bool stopped_by_watchpoint () override
;
796 bool stopped_data_address (CORE_ADDR
*) override
;
798 bool watchpoint_addr_within_range (CORE_ADDR
, CORE_ADDR
, int) override
;
800 int can_use_hw_breakpoint (enum bptype
, int, int) override
;
802 int insert_hw_breakpoint (struct gdbarch
*, struct bp_target_info
*) override
;
804 int remove_hw_breakpoint (struct gdbarch
*, struct bp_target_info
*) override
;
806 int region_ok_for_hw_watchpoint (CORE_ADDR
, int) override
;
808 int insert_watchpoint (CORE_ADDR
, int, enum target_hw_bp_type
,
809 struct expression
*) override
;
811 int remove_watchpoint (CORE_ADDR
, int, enum target_hw_bp_type
,
812 struct expression
*) override
;
814 void kill () override
;
816 void load (const char *, int) override
;
818 void mourn_inferior () override
;
820 void pass_signals (gdb::array_view
<const unsigned char>) override
;
822 int set_syscall_catchpoint (int, bool, int,
823 gdb::array_view
<const int>) override
;
825 void program_signals (gdb::array_view
<const unsigned char>) override
;
827 bool thread_alive (ptid_t ptid
) override
;
829 const char *thread_name (struct thread_info
*) override
;
831 void update_thread_list () override
;
833 std::string
pid_to_str (ptid_t
) override
;
835 const char *extra_thread_info (struct thread_info
*) override
;
837 ptid_t
get_ada_task_ptid (long lwp
, ULONGEST thread
) override
;
839 thread_info
*thread_handle_to_thread_info (const gdb_byte
*thread_handle
,
841 inferior
*inf
) override
;
843 gdb::array_view
<const gdb_byte
> thread_info_to_thread_handle (struct thread_info
*tp
)
846 void stop (ptid_t
) override
;
848 void interrupt () override
;
850 void pass_ctrlc () override
;
852 enum target_xfer_status
xfer_partial (enum target_object object
,
855 const gdb_byte
*writebuf
,
856 ULONGEST offset
, ULONGEST len
,
857 ULONGEST
*xfered_len
) override
;
859 ULONGEST
get_memory_xfer_limit () override
;
861 void rcmd (const char *command
, struct ui_file
*output
) override
;
863 const char *pid_to_exec_file (int pid
) override
;
865 void log_command (const char *cmd
) override
867 serial_log_command (this, cmd
);
870 CORE_ADDR
get_thread_local_address (ptid_t ptid
,
871 CORE_ADDR load_module_addr
,
872 CORE_ADDR offset
) override
;
874 bool can_execute_reverse () override
;
876 std::vector
<mem_region
> memory_map () override
;
878 void flash_erase (ULONGEST address
, LONGEST length
) override
;
880 void flash_done () override
;
882 const struct target_desc
*read_description () override
;
884 int search_memory (CORE_ADDR start_addr
, ULONGEST search_space_len
,
885 const gdb_byte
*pattern
, ULONGEST pattern_len
,
886 CORE_ADDR
*found_addrp
) override
;
888 bool can_async_p () override
;
890 bool is_async_p () override
;
892 void async (bool) override
;
894 int async_wait_fd () override
;
896 void thread_events (int) override
;
898 bool supports_set_thread_options (gdb_thread_options
) override
;
900 int can_do_single_step () override
;
902 void terminal_inferior () override
;
904 void terminal_ours () override
;
906 bool supports_non_stop () override
;
908 bool supports_multi_process () override
;
910 bool supports_disable_randomization () override
;
912 bool filesystem_is_local () override
;
915 int fileio_open (struct inferior
*inf
, const char *filename
,
916 int flags
, int mode
, int warn_if_slow
,
917 fileio_error
*target_errno
) override
;
919 int fileio_pwrite (int fd
, const gdb_byte
*write_buf
, int len
,
920 ULONGEST offset
, fileio_error
*target_errno
) override
;
922 int fileio_pread (int fd
, gdb_byte
*read_buf
, int len
,
923 ULONGEST offset
, fileio_error
*target_errno
) override
;
925 int fileio_fstat (int fd
, struct stat
*sb
, fileio_error
*target_errno
) override
;
927 int fileio_close (int fd
, fileio_error
*target_errno
) override
;
929 int fileio_unlink (struct inferior
*inf
,
930 const char *filename
,
931 fileio_error
*target_errno
) override
;
933 std::optional
<std::string
>
934 fileio_readlink (struct inferior
*inf
,
935 const char *filename
,
936 fileio_error
*target_errno
) override
;
938 bool supports_enable_disable_tracepoint () override
;
940 bool supports_string_tracing () override
;
942 int remote_supports_cond_tracepoints ();
944 bool supports_evaluation_of_breakpoint_conditions () override
;
946 int remote_supports_fast_tracepoints ();
948 int remote_supports_static_tracepoints ();
950 int remote_supports_install_in_trace ();
952 bool can_run_breakpoint_commands () override
;
954 void trace_init () override
;
956 void download_tracepoint (struct bp_location
*location
) override
;
958 bool can_download_tracepoint () override
;
960 void download_trace_state_variable (const trace_state_variable
&tsv
) override
;
962 void enable_tracepoint (struct bp_location
*location
) override
;
964 void disable_tracepoint (struct bp_location
*location
) override
;
966 void trace_set_readonly_regions () override
;
968 void trace_start () override
;
970 int get_trace_status (struct trace_status
*ts
) override
;
972 void get_tracepoint_status (tracepoint
*tp
, struct uploaded_tp
*utp
)
975 void trace_stop () override
;
977 int trace_find (enum trace_find_type type
, int num
,
978 CORE_ADDR addr1
, CORE_ADDR addr2
, int *tpp
) override
;
980 bool get_trace_state_variable_value (int tsv
, LONGEST
*val
) override
;
982 int save_trace_data (const char *filename
) override
;
984 int upload_tracepoints (struct uploaded_tp
**utpp
) override
;
986 int upload_trace_state_variables (struct uploaded_tsv
**utsvp
) override
;
988 LONGEST
get_raw_trace_data (gdb_byte
*buf
, ULONGEST offset
, LONGEST len
) override
;
990 int get_min_fast_tracepoint_insn_len () override
;
992 void set_disconnected_tracing (int val
) override
;
994 void set_circular_trace_buffer (int val
) override
;
996 void set_trace_buffer_size (LONGEST val
) override
;
998 bool set_trace_notes (const char *user
, const char *notes
,
999 const char *stopnotes
) override
;
1001 int core_of_thread (ptid_t ptid
) override
;
1003 int verify_memory (const gdb_byte
*data
,
1004 CORE_ADDR memaddr
, ULONGEST size
) override
;
1007 bool get_tib_address (ptid_t ptid
, CORE_ADDR
*addr
) override
;
1009 void set_permissions () override
;
1011 bool static_tracepoint_marker_at (CORE_ADDR
,
1012 struct static_tracepoint_marker
*marker
)
1015 std::vector
<static_tracepoint_marker
>
1016 static_tracepoint_markers_by_strid (const char *id
) override
;
1018 traceframe_info_up
traceframe_info () override
;
1020 bool use_agent (bool use
) override
;
1021 bool can_use_agent () override
;
1023 struct btrace_target_info
*
1024 enable_btrace (thread_info
*tp
, const struct btrace_config
*conf
) override
;
1026 void disable_btrace (struct btrace_target_info
*tinfo
) override
;
1028 void teardown_btrace (struct btrace_target_info
*tinfo
) override
;
1030 enum btrace_error
read_btrace (struct btrace_data
*data
,
1031 struct btrace_target_info
*btinfo
,
1032 enum btrace_read_type type
) override
;
1034 const struct btrace_config
*btrace_conf (const struct btrace_target_info
*) override
;
1035 bool augmented_libraries_svr4_read () override
;
1036 void follow_fork (inferior
*, ptid_t
, target_waitkind
, bool, bool) override
;
1037 void follow_clone (ptid_t child_ptid
) override
;
1038 void follow_exec (inferior
*, ptid_t
, const char *) override
;
1039 int insert_fork_catchpoint (int) override
;
1040 int remove_fork_catchpoint (int) override
;
1041 int insert_vfork_catchpoint (int) override
;
1042 int remove_vfork_catchpoint (int) override
;
1043 int insert_exec_catchpoint (int) override
;
1044 int remove_exec_catchpoint (int) override
;
1045 enum exec_direction_kind
execution_direction () override
;
1047 bool supports_memory_tagging () override
;
1049 bool fetch_memtags (CORE_ADDR address
, size_t len
,
1050 gdb::byte_vector
&tags
, int type
) override
;
1052 bool store_memtags (CORE_ADDR address
, size_t len
,
1053 const gdb::byte_vector
&tags
, int type
) override
;
1055 public: /* Remote specific methods. */
1057 void remote_download_command_source (int num
, ULONGEST addr
,
1058 struct command_line
*cmds
);
1060 void remote_file_put (const char *local_file
, const char *remote_file
,
1062 void remote_file_get (const char *remote_file
, const char *local_file
,
1064 void remote_file_delete (const char *remote_file
, int from_tty
);
1066 int remote_hostio_pread (int fd
, gdb_byte
*read_buf
, int len
,
1067 ULONGEST offset
, fileio_error
*remote_errno
);
1068 int remote_hostio_pwrite (int fd
, const gdb_byte
*write_buf
, int len
,
1069 ULONGEST offset
, fileio_error
*remote_errno
);
1070 int remote_hostio_pread_vFile (int fd
, gdb_byte
*read_buf
, int len
,
1071 ULONGEST offset
, fileio_error
*remote_errno
);
1073 int remote_hostio_send_command (int command_bytes
, int which_packet
,
1074 fileio_error
*remote_errno
, const char **attachment
,
1075 int *attachment_len
);
1076 int remote_hostio_set_filesystem (struct inferior
*inf
,
1077 fileio_error
*remote_errno
);
1078 /* We should get rid of this and use fileio_open directly. */
1079 int remote_hostio_open (struct inferior
*inf
, const char *filename
,
1080 int flags
, int mode
, int warn_if_slow
,
1081 fileio_error
*remote_errno
);
1082 int remote_hostio_close (int fd
, fileio_error
*remote_errno
);
1084 int remote_hostio_unlink (inferior
*inf
, const char *filename
,
1085 fileio_error
*remote_errno
);
1087 struct remote_state
*get_remote_state ();
1089 long get_remote_packet_size (void);
1090 long get_memory_packet_size (struct memory_packet_config
*config
);
1092 long get_memory_write_packet_size ();
1093 long get_memory_read_packet_size ();
1095 char *append_pending_thread_resumptions (char *p
, char *endp
,
1097 static void open_1 (const char *name
, int from_tty
, int extended_p
);
1098 void start_remote (int from_tty
, int extended_p
);
1099 void remote_detach_1 (struct inferior
*inf
, int from_tty
);
1101 char *append_resumption (char *p
, char *endp
,
1102 ptid_t ptid
, int step
, gdb_signal siggnal
);
1103 int remote_resume_with_vcont (ptid_t scope_ptid
, int step
,
1104 gdb_signal siggnal
);
1106 thread_info
*add_current_inferior_and_thread (const char *wait_status
);
1108 ptid_t
wait_ns (ptid_t ptid
, struct target_waitstatus
*status
,
1109 target_wait_flags options
);
1110 ptid_t
wait_as (ptid_t ptid
, target_waitstatus
*status
,
1111 target_wait_flags options
);
1113 ptid_t
process_stop_reply (struct stop_reply
*stop_reply
,
1114 target_waitstatus
*status
);
1116 ptid_t select_thread_for_ambiguous_stop_reply
1117 (const struct target_waitstatus
&status
);
1119 void remote_notice_new_inferior (ptid_t currthread
, bool executing
);
1121 void print_one_stopped_thread (thread_info
*thread
);
1122 void process_initial_stop_replies (int from_tty
);
1124 thread_info
*remote_add_thread (ptid_t ptid
, bool running
, bool executing
,
1127 void btrace_sync_conf (const btrace_config
*conf
);
1129 void remote_btrace_maybe_reopen ();
1131 void remove_new_children (threads_listing_context
*context
);
1132 void kill_new_fork_children (inferior
*inf
);
1133 void discard_pending_stop_replies (struct inferior
*inf
);
1134 int stop_reply_queue_length ();
1136 void check_pending_events_prevent_wildcard_vcont
1137 (bool *may_global_wildcard_vcont
);
1139 void discard_pending_stop_replies_in_queue ();
1140 struct stop_reply
*remote_notif_remove_queued_reply (ptid_t ptid
);
1141 struct stop_reply
*queued_stop_reply (ptid_t ptid
);
1142 int peek_stop_reply (ptid_t ptid
);
1143 void remote_parse_stop_reply (const char *buf
, stop_reply
*event
);
1145 void remote_stop_ns (ptid_t ptid
);
1146 void remote_interrupt_as ();
1147 void remote_interrupt_ns ();
1149 char *remote_get_noisy_reply ();
1150 int remote_query_attached (int pid
);
1151 inferior
*remote_add_inferior (bool fake_pid_p
, int pid
, int attached
,
1154 ptid_t
remote_current_thread (ptid_t oldpid
);
1155 ptid_t
get_current_thread (const char *wait_status
);
1157 void set_thread (ptid_t ptid
, int gen
);
1158 void set_general_thread (ptid_t ptid
);
1159 void set_continue_thread (ptid_t ptid
);
1160 void set_general_process ();
1162 char *write_ptid (char *buf
, const char *endbuf
, ptid_t ptid
);
1164 int remote_unpack_thread_info_response (const char *pkt
, threadref
*expectedref
,
1165 gdb_ext_thread_info
*info
);
1166 int remote_get_threadinfo (threadref
*threadid
, int fieldset
,
1167 gdb_ext_thread_info
*info
);
1169 int parse_threadlist_response (const char *pkt
, int result_limit
,
1170 threadref
*original_echo
,
1171 threadref
*resultlist
,
1173 int remote_get_threadlist (int startflag
, threadref
*nextthread
,
1174 int result_limit
, int *done
, int *result_count
,
1175 threadref
*threadlist
);
1177 int remote_threadlist_iterator (rmt_thread_action stepfunction
,
1178 void *context
, int looplimit
);
1180 int remote_get_threads_with_ql (threads_listing_context
*context
);
1181 int remote_get_threads_with_qxfer (threads_listing_context
*context
);
1182 int remote_get_threads_with_qthreadinfo (threads_listing_context
*context
);
1184 void extended_remote_restart ();
1186 void get_offsets ();
1188 void remote_check_symbols ();
1190 void remote_supported_packet (const struct protocol_feature
*feature
,
1191 enum packet_support support
,
1192 const char *argument
);
1194 void remote_query_supported ();
1196 void remote_packet_size (const protocol_feature
*feature
,
1197 packet_support support
, const char *value
);
1198 void remote_supported_thread_options (const protocol_feature
*feature
,
1199 enum packet_support support
,
1202 void remote_serial_quit_handler ();
1204 void remote_detach_pid (int pid
);
1206 void remote_vcont_probe ();
1208 void remote_resume_with_hc (ptid_t ptid
, int step
,
1209 gdb_signal siggnal
);
1211 void send_interrupt_sequence ();
1212 void interrupt_query ();
1214 void remote_notif_get_pending_events (const notif_client
*nc
);
1216 int fetch_register_using_p (struct regcache
*regcache
,
1218 int send_g_packet ();
1219 void process_g_packet (struct regcache
*regcache
);
1220 void fetch_registers_using_g (struct regcache
*regcache
);
1221 int store_register_using_P (const struct regcache
*regcache
,
1223 void store_registers_using_G (const struct regcache
*regcache
);
1225 void set_remote_traceframe ();
1227 void check_binary_download (CORE_ADDR addr
);
1229 target_xfer_status
remote_write_bytes_aux (const char *header
,
1231 const gdb_byte
*myaddr
,
1234 ULONGEST
*xfered_len_units
,
1238 target_xfer_status
remote_write_bytes (CORE_ADDR memaddr
,
1239 const gdb_byte
*myaddr
, ULONGEST len
,
1240 int unit_size
, ULONGEST
*xfered_len
);
1242 target_xfer_status
remote_read_bytes_1 (CORE_ADDR memaddr
, gdb_byte
*myaddr
,
1244 int unit_size
, ULONGEST
*xfered_len_units
);
1246 target_xfer_status
remote_xfer_live_readonly_partial (gdb_byte
*readbuf
,
1250 ULONGEST
*xfered_len
);
1252 target_xfer_status
remote_read_bytes (CORE_ADDR memaddr
,
1253 gdb_byte
*myaddr
, ULONGEST len
,
1255 ULONGEST
*xfered_len
);
1257 packet_result
remote_send_printf (const char *format
, ...)
1258 ATTRIBUTE_PRINTF (2, 3);
1260 target_xfer_status
remote_flash_write (ULONGEST address
,
1261 ULONGEST length
, ULONGEST
*xfered_len
,
1262 const gdb_byte
*data
);
1264 int readchar (int timeout
);
1266 void remote_serial_write (const char *str
, int len
);
1267 void remote_serial_send_break ();
1269 int putpkt (const char *buf
);
1270 int putpkt_binary (const char *buf
, int cnt
);
1272 int putpkt (const gdb::char_vector
&buf
)
1274 return putpkt (buf
.data ());
1278 long read_frame (gdb::char_vector
*buf_p
);
1279 int getpkt (gdb::char_vector
*buf
, bool forever
= false,
1280 bool *is_notif
= nullptr);
1281 int remote_vkill (int pid
);
1282 void remote_kill_k ();
1284 void extended_remote_disable_randomization (int val
);
1285 int extended_remote_run (const std::string
&args
);
1287 void send_environment_packet (const char *action
,
1291 void extended_remote_environment_support ();
1292 void extended_remote_set_inferior_cwd ();
1294 target_xfer_status
remote_write_qxfer (const char *object_name
,
1296 const gdb_byte
*writebuf
,
1297 ULONGEST offset
, LONGEST len
,
1298 ULONGEST
*xfered_len
,
1299 const unsigned int which_packet
);
1301 target_xfer_status
remote_read_qxfer (const char *object_name
,
1303 gdb_byte
*readbuf
, ULONGEST offset
,
1305 ULONGEST
*xfered_len
,
1306 const unsigned int which_packet
);
1308 void push_stop_reply (struct stop_reply
*new_event
);
1310 bool vcont_r_supported ();
1312 remote_features m_features
;
1316 bool start_remote_1 (int from_tty
, int extended_p
);
1318 /* The remote state. Don't reference this directly. Use the
1319 get_remote_state method instead. */
1320 remote_state m_remote_state
;
1323 static const target_info extended_remote_target_info
= {
1325 N_("Extended remote target using gdb-specific protocol"),
1329 /* Set up the extended remote target by extending the standard remote
1330 target and adding to it. */
1332 class extended_remote_target final
: public remote_target
1335 const target_info
&info () const override
1336 { return extended_remote_target_info
; }
1338 /* Open an extended-remote connection. */
1339 static void open (const char *, int);
1341 bool can_create_inferior () override
{ return true; }
1342 void create_inferior (const char *, const std::string
&,
1343 char **, int) override
;
1345 void detach (inferior
*, int) override
;
1347 bool can_attach () override
{ return true; }
1348 void attach (const char *, int) override
;
1350 void post_attach (int) override
;
1351 bool supports_disable_randomization () override
;
1354 struct stop_reply
: public notif_event
1358 /* The identifier of the thread about this event */
1361 /* The remote state this event is associated with. When the remote
1362 connection, represented by a remote_state object, is closed,
1363 all the associated stop_reply events should be released. */
1364 struct remote_state
*rs
;
1366 struct target_waitstatus ws
;
1368 /* The architecture associated with the expedited registers. */
1371 /* Expedited registers. This makes remote debugging a bit more
1372 efficient for those targets that provide critical registers as
1373 part of their normal status mechanism (as another roundtrip to
1374 fetch them is avoided). */
1375 std::vector
<cached_reg_t
> regcache
;
1377 enum target_stop_reason stop_reason
;
1379 CORE_ADDR watch_data_address
;
1384 /* Return TARGET as a remote_target if it is one, else nullptr. */
1386 static remote_target
*
1387 as_remote_target (process_stratum_target
*target
)
1389 return dynamic_cast<remote_target
*> (target
);
1395 is_remote_target (process_stratum_target
*target
)
1397 return as_remote_target (target
) != nullptr;
1400 /* Per-program-space data key. */
1401 static const registry
<program_space
>::key
<char, gdb::xfree_deleter
<char>>
1404 /* The variable registered as the control variable used by the
1405 remote exec-file commands. While the remote exec-file setting is
1406 per-program-space, the set/show machinery uses this as the
1407 location of the remote exec-file value. */
1408 static std::string remote_exec_file_var
;
1410 /* The size to align memory write packets, when practical. The protocol
1411 does not guarantee any alignment, and gdb will generate short
1412 writes and unaligned writes, but even as a best-effort attempt this
1413 can improve bulk transfers. For instance, if a write is misaligned
1414 relative to the target's data bus, the stub may need to make an extra
1415 round trip fetching data from the target. This doesn't make a
1416 huge difference, but it's easy to do, so we try to be helpful.
1418 The alignment chosen is arbitrary; usually data bus width is
1419 important here, not the possibly larger cache line size. */
1420 enum { REMOTE_ALIGN_WRITES
= 16 };
1422 /* Prototypes for local functions. */
1424 static int hexnumlen (ULONGEST num
);
1426 static int stubhex (int ch
);
1428 static int hexnumstr (char *, ULONGEST
);
1430 static int hexnumnstr (char *, ULONGEST
, int);
1432 static CORE_ADDR
remote_address_masked (CORE_ADDR
);
1434 static int stub_unpack_int (const char *buff
, int fieldlength
);
1436 static void set_remote_protocol_packet_cmd (const char *args
, int from_tty
,
1437 cmd_list_element
*c
);
1439 static void show_packet_config_cmd (ui_file
*file
,
1440 const unsigned int which_packet
,
1441 remote_target
*remote
);
1443 static void show_remote_protocol_packet_cmd (struct ui_file
*file
,
1445 struct cmd_list_element
*c
,
1448 static ptid_t
read_ptid (const char *buf
, const char **obuf
);
1450 static bool remote_read_description_p (struct target_ops
*target
);
1452 static void remote_console_output (const char *msg
);
1454 static void remote_btrace_reset (remote_state
*rs
);
1456 static void remote_unpush_and_throw (remote_target
*target
);
1460 static struct cmd_list_element
*remote_cmdlist
;
1462 /* For "set remote" and "show remote". */
1464 static struct cmd_list_element
*remote_set_cmdlist
;
1465 static struct cmd_list_element
*remote_show_cmdlist
;
1467 /* Controls whether GDB is willing to use range stepping. */
1469 static bool use_range_stepping
= true;
1471 /* From the remote target's point of view, each thread is in one of these three
1473 enum class resume_state
1475 /* Not resumed - we haven't been asked to resume this thread. */
1478 /* We have been asked to resume this thread, but haven't sent a vCont action
1479 for it yet. We'll need to consider it next time commit_resume is
1481 RESUMED_PENDING_VCONT
,
1483 /* We have been asked to resume this thread, and we have sent a vCont action
1488 /* Information about a thread's pending vCont-resume. Used when a thread is in
1489 the remote_resume_state::RESUMED_PENDING_VCONT state. remote_target::resume
1490 stores this information which is then picked up by
1491 remote_target::commit_resume to know which is the proper action for this
1492 thread to include in the vCont packet. */
1493 struct resumed_pending_vcont_info
1495 /* True if the last resume call for this thread was a step request, false
1496 if a continue request. */
1499 /* The signal specified in the last resume call for this thread. */
1503 /* Private data that we'll store in (struct thread_info)->priv. */
1504 struct remote_thread_info
: public private_thread_info
1510 /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
1511 sequence of bytes. */
1512 gdb::byte_vector thread_handle
;
1514 /* Whether the target stopped for a breakpoint/watchpoint. */
1515 enum target_stop_reason stop_reason
= TARGET_STOPPED_BY_NO_REASON
;
1517 /* This is set to the data address of the access causing the target
1518 to stop for a watchpoint. */
1519 CORE_ADDR watch_data_address
= 0;
1521 /* Get the thread's resume state. */
1522 enum resume_state
get_resume_state () const
1524 return m_resume_state
;
1527 /* Put the thread in the NOT_RESUMED state. */
1528 void set_not_resumed ()
1530 m_resume_state
= resume_state::NOT_RESUMED
;
1533 /* Put the thread in the RESUMED_PENDING_VCONT state. */
1534 void set_resumed_pending_vcont (bool step
, gdb_signal sig
)
1536 m_resume_state
= resume_state::RESUMED_PENDING_VCONT
;
1537 m_resumed_pending_vcont_info
.step
= step
;
1538 m_resumed_pending_vcont_info
.sig
= sig
;
1541 /* Get the information this thread's pending vCont-resumption.
1543 Must only be called if the thread is in the RESUMED_PENDING_VCONT resume
1545 const struct resumed_pending_vcont_info
&resumed_pending_vcont_info () const
1547 gdb_assert (m_resume_state
== resume_state::RESUMED_PENDING_VCONT
);
1549 return m_resumed_pending_vcont_info
;
1552 /* Put the thread in the VCONT_RESUMED state. */
1555 m_resume_state
= resume_state::RESUMED
;
1559 /* Resume state for this thread. This is used to implement vCont action
1560 coalescing (only when the target operates in non-stop mode).
1562 remote_target::resume moves the thread to the RESUMED_PENDING_VCONT state,
1563 which notes that this thread must be considered in the next commit_resume
1566 remote_target::commit_resume sends a vCont packet with actions for the
1567 threads in the RESUMED_PENDING_VCONT state and moves them to the
1568 VCONT_RESUMED state.
1570 When reporting a stop to the core for a thread, that thread is moved back
1571 to the NOT_RESUMED state. */
1572 enum resume_state m_resume_state
= resume_state::NOT_RESUMED
;
1574 /* Extra info used if the thread is in the RESUMED_PENDING_VCONT state. */
1575 struct resumed_pending_vcont_info m_resumed_pending_vcont_info
;
1578 remote_state::remote_state ()
1583 remote_state::~remote_state ()
1585 xfree (this->last_pass_packet
);
1586 xfree (this->last_program_signals_packet
);
1587 xfree (this->finished_object
);
1588 xfree (this->finished_annex
);
1591 /* Utility: generate error from an incoming stub packet. */
1593 trace_error (char *buf
)
1596 return; /* not an error msg */
1599 case '1': /* malformed packet error */
1600 if (*++buf
== '0') /* general case: */
1601 error (_("remote.c: error in outgoing packet."));
1603 error (_("remote.c: error in outgoing packet at field #%ld."),
1604 strtol (buf
, NULL
, 16));
1606 error (_("Target returns error code '%s'."), buf
);
1610 /* Utility: wait for reply from stub, while accepting "O" packets. */
1613 remote_target::remote_get_noisy_reply ()
1615 struct remote_state
*rs
= get_remote_state ();
1617 do /* Loop on reply from remote stub. */
1621 QUIT
; /* Allow user to bail out with ^C. */
1623 buf
= rs
->buf
.data ();
1626 else if (startswith (buf
, "qRelocInsn:"))
1629 CORE_ADDR from
, to
, org_to
;
1631 int adjusted_size
= 0;
1634 p
= buf
+ strlen ("qRelocInsn:");
1635 pp
= unpack_varlen_hex (p
, &ul
);
1637 error (_("invalid qRelocInsn packet: %s"), buf
);
1641 unpack_varlen_hex (p
, &ul
);
1648 gdbarch_relocate_instruction (current_inferior ()->arch (),
1652 catch (const gdb_exception
&ex
)
1654 if (ex
.error
== MEMORY_ERROR
)
1656 /* Propagate memory errors silently back to the
1657 target. The stub may have limited the range of
1658 addresses we can write to, for example. */
1662 /* Something unexpectedly bad happened. Be verbose
1663 so we can tell what, and propagate the error back
1664 to the stub, so it doesn't get stuck waiting for
1666 exception_fprintf (gdb_stderr
, ex
,
1667 _("warning: relocating instruction: "));
1674 adjusted_size
= to
- org_to
;
1676 xsnprintf (buf
, rs
->buf
.size (), "qRelocInsn:%x", adjusted_size
);
1680 else if (buf
[0] == 'O' && buf
[1] != 'K')
1681 remote_console_output (buf
+ 1); /* 'O' message from stub */
1683 return buf
; /* Here's the actual reply. */
1688 struct remote_arch_state
*
1689 remote_state::get_remote_arch_state (struct gdbarch
*gdbarch
)
1691 remote_arch_state
*rsa
;
1693 auto it
= this->m_arch_states
.find (gdbarch
);
1694 if (it
== this->m_arch_states
.end ())
1696 auto p
= this->m_arch_states
.emplace (std::piecewise_construct
,
1697 std::forward_as_tuple (gdbarch
),
1698 std::forward_as_tuple (gdbarch
));
1699 rsa
= &p
.first
->second
;
1701 /* Make sure that the packet buffer is plenty big enough for
1702 this architecture. */
1703 if (this->buf
.size () < rsa
->remote_packet_size
)
1704 this->buf
.resize (2 * rsa
->remote_packet_size
);
1712 /* Fetch the global remote target state. */
1715 remote_target::get_remote_state ()
1717 /* Make sure that the remote architecture state has been
1718 initialized, because doing so might reallocate rs->buf. Any
1719 function which calls getpkt also needs to be mindful of changes
1720 to rs->buf, but this call limits the number of places which run
1722 m_remote_state
.get_remote_arch_state (current_inferior ()->arch ());
1724 return &m_remote_state
;
1727 /* Fetch the remote exec-file from the current program space. */
1730 get_remote_exec_file (void)
1732 char *remote_exec_file
;
1734 remote_exec_file
= remote_pspace_data
.get (current_program_space
);
1735 if (remote_exec_file
== NULL
)
1738 return remote_exec_file
;
1741 /* Set the remote exec file for PSPACE. */
1744 set_pspace_remote_exec_file (struct program_space
*pspace
,
1745 const char *remote_exec_file
)
1747 char *old_file
= remote_pspace_data
.get (pspace
);
1750 remote_pspace_data
.set (pspace
, xstrdup (remote_exec_file
));
1753 /* The "set/show remote exec-file" set command hook. */
1756 set_remote_exec_file (const char *ignored
, int from_tty
,
1757 struct cmd_list_element
*c
)
1759 set_pspace_remote_exec_file (current_program_space
,
1760 remote_exec_file_var
.c_str ());
1763 /* The "set/show remote exec-file" show command hook. */
1766 show_remote_exec_file (struct ui_file
*file
, int from_tty
,
1767 struct cmd_list_element
*cmd
, const char *value
)
1769 gdb_printf (file
, "%s\n", get_remote_exec_file ());
1773 map_regcache_remote_table (struct gdbarch
*gdbarch
, struct packet_reg
*regs
)
1775 int regnum
, num_remote_regs
, offset
;
1776 struct packet_reg
**remote_regs
;
1778 for (regnum
= 0; regnum
< gdbarch_num_regs (gdbarch
); regnum
++)
1780 struct packet_reg
*r
= ®s
[regnum
];
1782 if (register_size (gdbarch
, regnum
) == 0)
1783 /* Do not try to fetch zero-sized (placeholder) registers. */
1786 r
->pnum
= gdbarch_remote_register_number (gdbarch
, regnum
);
1791 /* Define the g/G packet format as the contents of each register
1792 with a remote protocol number, in order of ascending protocol
1795 remote_regs
= XALLOCAVEC (struct packet_reg
*, gdbarch_num_regs (gdbarch
));
1796 for (num_remote_regs
= 0, regnum
= 0;
1797 regnum
< gdbarch_num_regs (gdbarch
);
1799 if (regs
[regnum
].pnum
!= -1)
1800 remote_regs
[num_remote_regs
++] = ®s
[regnum
];
1802 std::sort (remote_regs
, remote_regs
+ num_remote_regs
,
1803 [] (const packet_reg
*a
, const packet_reg
*b
)
1804 { return a
->pnum
< b
->pnum
; });
1806 for (regnum
= 0, offset
= 0; regnum
< num_remote_regs
; regnum
++)
1808 remote_regs
[regnum
]->in_g_packet
= 1;
1809 remote_regs
[regnum
]->offset
= offset
;
1810 offset
+= register_size (gdbarch
, remote_regs
[regnum
]->regnum
);
1816 /* Given the architecture described by GDBARCH, return the remote
1817 protocol register's number and the register's offset in the g/G
1818 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
1819 If the target does not have a mapping for REGNUM, return false,
1820 otherwise, return true. */
1823 remote_register_number_and_offset (struct gdbarch
*gdbarch
, int regnum
,
1824 int *pnum
, int *poffset
)
1826 gdb_assert (regnum
< gdbarch_num_regs (gdbarch
));
1828 std::vector
<packet_reg
> regs (gdbarch_num_regs (gdbarch
));
1830 map_regcache_remote_table (gdbarch
, regs
.data ());
1832 *pnum
= regs
[regnum
].pnum
;
1833 *poffset
= regs
[regnum
].offset
;
1838 remote_arch_state::remote_arch_state (struct gdbarch
*gdbarch
)
1840 /* Use the architecture to build a regnum<->pnum table, which will be
1841 1:1 unless a feature set specifies otherwise. */
1842 this->regs
.reset (new packet_reg
[gdbarch_num_regs (gdbarch
)] ());
1844 /* Record the maximum possible size of the g packet - it may turn out
1846 this->sizeof_g_packet
1847 = map_regcache_remote_table (gdbarch
, this->regs
.get ());
1849 /* Default maximum number of characters in a packet body. Many
1850 remote stubs have a hardwired buffer size of 400 bytes
1851 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
1852 as the maximum packet-size to ensure that the packet and an extra
1853 NUL character can always fit in the buffer. This stops GDB
1854 trashing stubs that try to squeeze an extra NUL into what is
1855 already a full buffer (As of 1999-12-04 that was most stubs). */
1856 this->remote_packet_size
= 400 - 1;
1858 /* This one is filled in when a ``g'' packet is received. */
1859 this->actual_register_packet_size
= 0;
1861 /* Should rsa->sizeof_g_packet needs more space than the
1862 default, adjust the size accordingly. Remember that each byte is
1863 encoded as two characters. 32 is the overhead for the packet
1864 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
1865 (``$NN:G...#NN'') is a better guess, the below has been padded a
1867 if (this->sizeof_g_packet
> ((this->remote_packet_size
- 32) / 2))
1868 this->remote_packet_size
= (this->sizeof_g_packet
* 2 + 32);
1871 /* Get a pointer to the current remote target. If not connected to a
1872 remote target, return NULL. */
1874 static remote_target
*
1875 get_current_remote_target ()
1877 target_ops
*proc_target
= current_inferior ()->process_target ();
1878 return dynamic_cast<remote_target
*> (proc_target
);
1881 /* Return the current allowed size of a remote packet. This is
1882 inferred from the current architecture, and should be used to
1883 limit the length of outgoing packets. */
1885 remote_target::get_remote_packet_size ()
1887 struct remote_state
*rs
= get_remote_state ();
1888 remote_arch_state
*rsa
1889 = rs
->get_remote_arch_state (current_inferior ()->arch ());
1891 if (rs
->explicit_packet_size
)
1892 return rs
->explicit_packet_size
;
1894 return rsa
->remote_packet_size
;
1897 static struct packet_reg
*
1898 packet_reg_from_regnum (struct gdbarch
*gdbarch
, struct remote_arch_state
*rsa
,
1901 if (regnum
< 0 && regnum
>= gdbarch_num_regs (gdbarch
))
1905 struct packet_reg
*r
= &rsa
->regs
[regnum
];
1907 gdb_assert (r
->regnum
== regnum
);
1912 static struct packet_reg
*
1913 packet_reg_from_pnum (struct gdbarch
*gdbarch
, struct remote_arch_state
*rsa
,
1918 for (i
= 0; i
< gdbarch_num_regs (gdbarch
); i
++)
1920 struct packet_reg
*r
= &rsa
->regs
[i
];
1922 if (r
->pnum
== pnum
)
1928 /* Allow the user to specify what sequence to send to the remote
1929 when he requests a program interruption: Although ^C is usually
1930 what remote systems expect (this is the default, here), it is
1931 sometimes preferable to send a break. On other systems such
1932 as the Linux kernel, a break followed by g, which is Magic SysRq g
1933 is required in order to interrupt the execution. */
1934 const char interrupt_sequence_control_c
[] = "Ctrl-C";
1935 const char interrupt_sequence_break
[] = "BREAK";
1936 const char interrupt_sequence_break_g
[] = "BREAK-g";
1937 static const char *const interrupt_sequence_modes
[] =
1939 interrupt_sequence_control_c
,
1940 interrupt_sequence_break
,
1941 interrupt_sequence_break_g
,
1944 static const char *interrupt_sequence_mode
= interrupt_sequence_control_c
;
1947 show_interrupt_sequence (struct ui_file
*file
, int from_tty
,
1948 struct cmd_list_element
*c
,
1951 if (interrupt_sequence_mode
== interrupt_sequence_control_c
)
1953 _("Send the ASCII ETX character (Ctrl-c) "
1954 "to the remote target to interrupt the "
1955 "execution of the program.\n"));
1956 else if (interrupt_sequence_mode
== interrupt_sequence_break
)
1958 _("send a break signal to the remote target "
1959 "to interrupt the execution of the program.\n"));
1960 else if (interrupt_sequence_mode
== interrupt_sequence_break_g
)
1962 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
1963 "the remote target to interrupt the execution "
1964 "of Linux kernel.\n"));
1966 internal_error (_("Invalid value for interrupt_sequence_mode: %s."),
1967 interrupt_sequence_mode
);
1970 /* This boolean variable specifies whether interrupt_sequence is sent
1971 to the remote target when gdb connects to it.
1972 This is mostly needed when you debug the Linux kernel: The Linux kernel
1973 expects BREAK g which is Magic SysRq g for connecting gdb. */
1974 static bool interrupt_on_connect
= false;
1976 /* This variable is used to implement the "set/show remotebreak" commands.
1977 Since these commands are now deprecated in favor of "set/show remote
1978 interrupt-sequence", it no longer has any effect on the code. */
1979 static bool remote_break
;
1982 set_remotebreak (const char *args
, int from_tty
, struct cmd_list_element
*c
)
1985 interrupt_sequence_mode
= interrupt_sequence_break
;
1987 interrupt_sequence_mode
= interrupt_sequence_control_c
;
1991 show_remotebreak (struct ui_file
*file
, int from_tty
,
1992 struct cmd_list_element
*c
,
1997 /* This variable sets the number of bits in an address that are to be
1998 sent in a memory ("M" or "m") packet. Normally, after stripping
1999 leading zeros, the entire address would be sent. This variable
2000 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
2001 initial implementation of remote.c restricted the address sent in
2002 memory packets to ``host::sizeof long'' bytes - (typically 32
2003 bits). Consequently, for 64 bit targets, the upper 32 bits of an
2004 address was never sent. Since fixing this bug may cause a break in
2005 some remote targets this variable is principally provided to
2006 facilitate backward compatibility. */
2008 static unsigned int remote_address_size
;
2011 /* The default max memory-write-packet-size, when the setting is
2012 "fixed". The 16k is historical. (It came from older GDB's using
2013 alloca for buffers and the knowledge (folklore?) that some hosts
2014 don't cope very well with large alloca calls.) */
2015 #define DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED 16384
2017 /* The minimum remote packet size for memory transfers. Ensures we
2018 can write at least one byte. */
2019 #define MIN_MEMORY_PACKET_SIZE 20
2021 /* Get the memory packet size, assuming it is fixed. */
2024 get_fixed_memory_packet_size (struct memory_packet_config
*config
)
2026 gdb_assert (config
->fixed_p
);
2028 if (config
->size
<= 0)
2029 return DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED
;
2031 return config
->size
;
2034 /* Compute the current size of a read/write packet. Since this makes
2035 use of ``actual_register_packet_size'' the computation is dynamic. */
2038 remote_target::get_memory_packet_size (struct memory_packet_config
*config
)
2040 struct remote_state
*rs
= get_remote_state ();
2041 remote_arch_state
*rsa
2042 = rs
->get_remote_arch_state (current_inferior ()->arch ());
2045 if (config
->fixed_p
)
2046 what_they_get
= get_fixed_memory_packet_size (config
);
2049 what_they_get
= get_remote_packet_size ();
2050 /* Limit the packet to the size specified by the user. */
2051 if (config
->size
> 0
2052 && what_they_get
> config
->size
)
2053 what_they_get
= config
->size
;
2055 /* Limit it to the size of the targets ``g'' response unless we have
2056 permission from the stub to use a larger packet size. */
2057 if (rs
->explicit_packet_size
== 0
2058 && rsa
->actual_register_packet_size
> 0
2059 && what_they_get
> rsa
->actual_register_packet_size
)
2060 what_they_get
= rsa
->actual_register_packet_size
;
2062 if (what_they_get
< MIN_MEMORY_PACKET_SIZE
)
2063 what_they_get
= MIN_MEMORY_PACKET_SIZE
;
2065 /* Make sure there is room in the global buffer for this packet
2066 (including its trailing NUL byte). */
2067 if (rs
->buf
.size () < what_they_get
+ 1)
2068 rs
->buf
.resize (2 * what_they_get
);
2070 return what_they_get
;
2073 /* Update the size of a read/write packet. If they user wants
2074 something really big then do a sanity check. */
2077 set_memory_packet_size (const char *args
, struct memory_packet_config
*config
,
2078 bool target_connected
)
2080 int fixed_p
= config
->fixed_p
;
2081 long size
= config
->size
;
2084 error (_("Argument required (integer, \"fixed\" or \"limit\")."));
2085 else if (strcmp (args
, "hard") == 0
2086 || strcmp (args
, "fixed") == 0)
2088 else if (strcmp (args
, "soft") == 0
2089 || strcmp (args
, "limit") == 0)
2095 size
= strtoul (args
, &end
, 0);
2097 error (_("Invalid %s (bad syntax)."), config
->name
);
2099 /* Instead of explicitly capping the size of a packet to or
2100 disallowing it, the user is allowed to set the size to
2101 something arbitrarily large. */
2105 if (fixed_p
&& !config
->fixed_p
)
2107 /* So that the query shows the correct value. */
2108 long query_size
= (size
<= 0
2109 ? DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED
2112 if (target_connected
2113 && !query (_("The target may not be able to correctly handle a %s\n"
2114 "of %ld bytes. Change the packet size? "),
2115 config
->name
, query_size
))
2116 error (_("Packet size not changed."));
2117 else if (!target_connected
2118 && !query (_("Future remote targets may not be able to "
2119 "correctly handle a %s\nof %ld bytes. Change the "
2120 "packet size for future remote targets? "),
2121 config
->name
, query_size
))
2122 error (_("Packet size not changed."));
2124 /* Update the config. */
2125 config
->fixed_p
= fixed_p
;
2126 config
->size
= size
;
2128 const char *target_type
= get_target_type_name (target_connected
);
2129 gdb_printf (_("The %s %s is set to \"%s\".\n"), config
->name
, target_type
,
2134 /* Show the memory-read or write-packet size configuration CONFIG of the
2135 target REMOTE. If REMOTE is nullptr, the default configuration for future
2136 remote targets should be passed in CONFIG. */
2139 show_memory_packet_size (memory_packet_config
*config
, remote_target
*remote
)
2141 const char *target_type
= get_target_type_name (remote
!= nullptr);
2143 if (config
->size
== 0)
2144 gdb_printf (_("The %s %s is 0 (default). "), config
->name
, target_type
);
2146 gdb_printf (_("The %s %s is %ld. "), config
->name
, target_type
,
2149 if (config
->fixed_p
)
2150 gdb_printf (_("Packets are fixed at %ld bytes.\n"),
2151 get_fixed_memory_packet_size (config
));
2154 if (remote
!= nullptr)
2155 gdb_printf (_("Packets are limited to %ld bytes.\n"),
2156 remote
->get_memory_packet_size (config
));
2158 gdb_puts ("The actual limit will be further reduced "
2159 "dependent on the target.\n");
2163 /* Configure the memory-write-packet size of the currently selected target. If
2164 no target is available, the default configuration for future remote targets
2168 set_memory_write_packet_size (const char *args
, int from_tty
)
2170 remote_target
*remote
= get_current_remote_target ();
2171 if (remote
!= nullptr)
2173 set_memory_packet_size
2174 (args
, &remote
->m_features
.m_memory_write_packet_config
, true);
2178 memory_packet_config
* config
= &memory_write_packet_config
;
2179 set_memory_packet_size (args
, config
, false);
2183 /* Display the memory-write-packet size of the currently selected target. If
2184 no target is available, the default configuration for future remote targets
2188 show_memory_write_packet_size (const char *args
, int from_tty
)
2190 remote_target
*remote
= get_current_remote_target ();
2191 if (remote
!= nullptr)
2192 show_memory_packet_size (&remote
->m_features
.m_memory_write_packet_config
,
2195 show_memory_packet_size (&memory_write_packet_config
, nullptr);
2198 /* Show the number of hardware watchpoints that can be used. */
2201 show_hardware_watchpoint_limit (struct ui_file
*file
, int from_tty
,
2202 struct cmd_list_element
*c
,
2205 gdb_printf (file
, _("The maximum number of target hardware "
2206 "watchpoints is %s.\n"), value
);
2209 /* Show the length limit (in bytes) for hardware watchpoints. */
2212 show_hardware_watchpoint_length_limit (struct ui_file
*file
, int from_tty
,
2213 struct cmd_list_element
*c
,
2216 gdb_printf (file
, _("The maximum length (in bytes) of a target "
2217 "hardware watchpoint is %s.\n"), value
);
2220 /* Show the number of hardware breakpoints that can be used. */
2223 show_hardware_breakpoint_limit (struct ui_file
*file
, int from_tty
,
2224 struct cmd_list_element
*c
,
2227 gdb_printf (file
, _("The maximum number of target hardware "
2228 "breakpoints is %s.\n"), value
);
2231 /* Controls the maximum number of characters to display in the debug output
2232 for each remote packet. The remaining characters are omitted. */
2234 static int remote_packet_max_chars
= 512;
2236 /* Show the maximum number of characters to display for each remote packet
2237 when remote debugging is enabled. */
2240 show_remote_packet_max_chars (struct ui_file
*file
, int from_tty
,
2241 struct cmd_list_element
*c
,
2244 gdb_printf (file
, _("Number of remote packet characters to "
2245 "display is %s.\n"), value
);
2249 remote_target::get_memory_write_packet_size ()
2251 return get_memory_packet_size (&m_features
.m_memory_write_packet_config
);
2254 /* Configure the memory-read-packet size of the currently selected target. If
2255 no target is available, the default configuration for future remote targets
2259 set_memory_read_packet_size (const char *args
, int from_tty
)
2261 remote_target
*remote
= get_current_remote_target ();
2262 if (remote
!= nullptr)
2263 set_memory_packet_size
2264 (args
, &remote
->m_features
.m_memory_read_packet_config
, true);
2267 memory_packet_config
* config
= &memory_read_packet_config
;
2268 set_memory_packet_size (args
, config
, false);
2273 /* Display the memory-read-packet size of the currently selected target. If
2274 no target is available, the default configuration for future remote targets
2278 show_memory_read_packet_size (const char *args
, int from_tty
)
2280 remote_target
*remote
= get_current_remote_target ();
2281 if (remote
!= nullptr)
2282 show_memory_packet_size (&remote
->m_features
.m_memory_read_packet_config
,
2285 show_memory_packet_size (&memory_read_packet_config
, nullptr);
2289 remote_target::get_memory_read_packet_size ()
2291 long size
= get_memory_packet_size (&m_features
.m_memory_read_packet_config
);
2293 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
2294 extra buffer size argument before the memory read size can be
2295 increased beyond this. */
2296 if (size
> get_remote_packet_size ())
2297 size
= get_remote_packet_size ();
2301 static enum packet_support
packet_config_support (const packet_config
*config
);
2305 set_remote_protocol_packet_cmd (const char *args
, int from_tty
,
2306 cmd_list_element
*c
)
2308 remote_target
*remote
= get_current_remote_target ();
2309 gdb_assert (c
->var
.has_value ());
2311 auto *default_config
= static_cast<packet_config
*> (c
->context ());
2312 const int packet_idx
= std::distance (remote_protocol_packets
,
2315 if (packet_idx
>= 0 && packet_idx
< PACKET_MAX
)
2317 const char *name
= packets_descriptions
[packet_idx
].name
;
2318 const auto_boolean value
= c
->var
->get
<auto_boolean
> ();
2319 const char *support
= get_packet_support_name (value
);
2320 const char *target_type
= get_target_type_name (remote
!= nullptr);
2322 if (remote
!= nullptr)
2323 remote
->m_features
.m_protocol_packets
[packet_idx
].detect
= value
;
2325 remote_protocol_packets
[packet_idx
].detect
= value
;
2327 gdb_printf (_("Support for the '%s' packet %s is set to \"%s\".\n"), name
,
2328 target_type
, support
);
2332 internal_error (_("Could not find config for %s"), c
->name
);
2336 show_packet_config_cmd (ui_file
*file
, const unsigned int which_packet
,
2337 remote_target
*remote
)
2339 const char *support
= "internal-error";
2340 const char *target_type
= get_target_type_name (remote
!= nullptr);
2342 packet_config
*config
;
2343 if (remote
!= nullptr)
2344 config
= &remote
->m_features
.m_protocol_packets
[which_packet
];
2346 config
= &remote_protocol_packets
[which_packet
];
2348 switch (packet_config_support (config
))
2351 support
= "enabled";
2353 case PACKET_DISABLE
:
2354 support
= "disabled";
2356 case PACKET_SUPPORT_UNKNOWN
:
2357 support
= "unknown";
2360 switch (config
->detect
)
2362 case AUTO_BOOLEAN_AUTO
:
2364 _("Support for the '%s' packet %s is \"auto\", "
2366 packets_descriptions
[which_packet
].name
, target_type
,
2369 case AUTO_BOOLEAN_TRUE
:
2370 case AUTO_BOOLEAN_FALSE
:
2372 _("Support for the '%s' packet %s is \"%s\".\n"),
2373 packets_descriptions
[which_packet
].name
, target_type
,
2374 get_packet_support_name (config
->detect
));
2380 add_packet_config_cmd (const unsigned int which_packet
, const char *name
,
2381 const char *title
, int legacy
)
2383 packets_descriptions
[which_packet
].name
= name
;
2384 packets_descriptions
[which_packet
].title
= title
;
2386 packet_config
*config
= &remote_protocol_packets
[which_packet
];
2388 gdb::unique_xmalloc_ptr
<char> set_doc
2389 = xstrprintf ("Set use of remote protocol `%s' (%s) packet.",
2391 gdb::unique_xmalloc_ptr
<char> show_doc
2392 = xstrprintf ("Show current use of remote protocol `%s' (%s) packet.",
2394 /* set/show TITLE-packet {auto,on,off} */
2395 gdb::unique_xmalloc_ptr
<char> cmd_name
= xstrprintf ("%s-packet", title
);
2396 set_show_commands cmds
2397 = add_setshow_auto_boolean_cmd (cmd_name
.release (), class_obscure
,
2398 &config
->detect
, set_doc
.get (),
2399 show_doc
.get (), NULL
, /* help_doc */
2400 set_remote_protocol_packet_cmd
,
2401 show_remote_protocol_packet_cmd
,
2402 &remote_set_cmdlist
, &remote_show_cmdlist
);
2403 cmds
.show
->set_context (config
);
2404 cmds
.set
->set_context (config
);
2406 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
2409 /* It's not clear who should take ownership of the LEGACY_NAME string
2410 created below, so, for now, place the string into a static vector
2411 which ensures the strings is released when GDB exits. */
2412 static std::vector
<gdb::unique_xmalloc_ptr
<char>> legacy_names
;
2413 gdb::unique_xmalloc_ptr
<char> legacy_name
2414 = xstrprintf ("%s-packet", name
);
2415 add_alias_cmd (legacy_name
.get (), cmds
.set
, class_obscure
, 0,
2416 &remote_set_cmdlist
);
2417 add_alias_cmd (legacy_name
.get (), cmds
.show
, class_obscure
, 0,
2418 &remote_show_cmdlist
);
2419 legacy_names
.emplace_back (std::move (legacy_name
));
2423 static enum packet_result
2424 packet_check_result (const char *buf
)
2428 /* The stub recognized the packet request. Check that the
2429 operation succeeded. */
2431 && isxdigit (buf
[1]) && isxdigit (buf
[2])
2433 /* "Enn" - definitely an error. */
2434 return PACKET_ERROR
;
2436 /* Always treat "E." as an error. This will be used for
2437 more verbose error messages, such as E.memtypes. */
2438 if (buf
[0] == 'E' && buf
[1] == '.')
2439 return PACKET_ERROR
;
2441 /* The packet may or may not be OK. Just assume it is. */
2445 /* The stub does not support the packet. */
2446 return PACKET_UNKNOWN
;
2449 static enum packet_result
2450 packet_check_result (const gdb::char_vector
&buf
)
2452 return packet_check_result (buf
.data ());
2456 remote_features::packet_ok (const char *buf
, const int which_packet
)
2458 packet_config
*config
= &m_protocol_packets
[which_packet
];
2459 packet_description
*descr
= &packets_descriptions
[which_packet
];
2461 enum packet_result result
;
2463 if (config
->detect
!= AUTO_BOOLEAN_TRUE
2464 && config
->support
== PACKET_DISABLE
)
2465 internal_error (_("packet_ok: attempt to use a disabled packet"));
2467 result
= packet_check_result (buf
);
2472 /* The stub recognized the packet request. */
2473 if (config
->support
== PACKET_SUPPORT_UNKNOWN
)
2475 remote_debug_printf ("Packet %s (%s) is supported",
2476 descr
->name
, descr
->title
);
2477 config
->support
= PACKET_ENABLE
;
2480 case PACKET_UNKNOWN
:
2481 /* The stub does not support the packet. */
2482 if (config
->detect
== AUTO_BOOLEAN_AUTO
2483 && config
->support
== PACKET_ENABLE
)
2485 /* If the stub previously indicated that the packet was
2486 supported then there is a protocol error. */
2487 error (_("Protocol error: %s (%s) conflicting enabled responses."),
2488 descr
->name
, descr
->title
);
2490 else if (config
->detect
== AUTO_BOOLEAN_TRUE
)
2492 /* The user set it wrong. */
2493 error (_("Enabled packet %s (%s) not recognized by stub"),
2494 descr
->name
, descr
->title
);
2497 remote_debug_printf ("Packet %s (%s) is NOT supported", descr
->name
,
2499 config
->support
= PACKET_DISABLE
;
2507 remote_features::packet_ok (const gdb::char_vector
&buf
, const int which_packet
)
2509 return packet_ok (buf
.data (), which_packet
);
2512 /* Returns whether a given packet or feature is supported. This takes
2513 into account the state of the corresponding "set remote foo-packet"
2514 command, which may be used to bypass auto-detection. */
2516 static enum packet_support
2517 packet_config_support (const packet_config
*config
)
2519 switch (config
->detect
)
2521 case AUTO_BOOLEAN_TRUE
:
2522 return PACKET_ENABLE
;
2523 case AUTO_BOOLEAN_FALSE
:
2524 return PACKET_DISABLE
;
2525 case AUTO_BOOLEAN_AUTO
:
2526 return config
->support
;
2528 gdb_assert_not_reached ("bad switch");
2533 remote_features::packet_support (int packet
) const
2535 const packet_config
*config
= &m_protocol_packets
[packet
];
2536 return packet_config_support (config
);
2540 show_remote_protocol_packet_cmd (struct ui_file
*file
, int from_tty
,
2541 struct cmd_list_element
*c
,
2544 remote_target
*remote
= get_current_remote_target ();
2545 gdb_assert (c
->var
.has_value ());
2547 auto *default_config
= static_cast<packet_config
*> (c
->context ());
2548 const int packet_idx
= std::distance (remote_protocol_packets
,
2551 if (packet_idx
>= 0 && packet_idx
< PACKET_MAX
)
2553 show_packet_config_cmd (file
, packet_idx
, remote
);
2556 internal_error (_("Could not find config for %s"), c
->name
);
2559 /* Should we try one of the 'Z' requests? */
2563 Z_PACKET_SOFTWARE_BP
,
2564 Z_PACKET_HARDWARE_BP
,
2571 /* For compatibility with older distributions. Provide a ``set remote
2572 Z-packet ...'' command that updates all the Z packet types. */
2574 static enum auto_boolean remote_Z_packet_detect
;
2577 set_remote_protocol_Z_packet_cmd (const char *args
, int from_tty
,
2578 struct cmd_list_element
*c
)
2580 remote_target
*remote
= get_current_remote_target ();
2583 for (i
= 0; i
< NR_Z_PACKET_TYPES
; i
++)
2585 if (remote
!= nullptr)
2586 remote
->m_features
.m_protocol_packets
[PACKET_Z0
+ i
].detect
2587 = remote_Z_packet_detect
;
2589 remote_protocol_packets
[PACKET_Z0
+ i
].detect
= remote_Z_packet_detect
;
2592 const char *support
= get_packet_support_name (remote_Z_packet_detect
);
2593 const char *target_type
= get_target_type_name (remote
!= nullptr);
2594 gdb_printf (_("Use of Z packets %s is set to \"%s\".\n"), target_type
,
2600 show_remote_protocol_Z_packet_cmd (struct ui_file
*file
, int from_tty
,
2601 struct cmd_list_element
*c
,
2604 remote_target
*remote
= get_current_remote_target ();
2607 for (i
= 0; i
< NR_Z_PACKET_TYPES
; i
++)
2608 show_packet_config_cmd (file
, PACKET_Z0
+ i
, remote
);
2611 /* Insert fork catchpoint target routine. If fork events are enabled
2612 then return success, nothing more to do. */
2615 remote_target::insert_fork_catchpoint (int pid
)
2617 return !m_features
.remote_fork_event_p ();
2620 /* Remove fork catchpoint target routine. Nothing to do, just
2624 remote_target::remove_fork_catchpoint (int pid
)
2629 /* Insert vfork catchpoint target routine. If vfork events are enabled
2630 then return success, nothing more to do. */
2633 remote_target::insert_vfork_catchpoint (int pid
)
2635 return !m_features
.remote_vfork_event_p ();
2638 /* Remove vfork catchpoint target routine. Nothing to do, just
2642 remote_target::remove_vfork_catchpoint (int pid
)
2647 /* Insert exec catchpoint target routine. If exec events are
2648 enabled, just return success. */
2651 remote_target::insert_exec_catchpoint (int pid
)
2653 return !m_features
.remote_exec_event_p ();
2656 /* Remove exec catchpoint target routine. Nothing to do, just
2660 remote_target::remove_exec_catchpoint (int pid
)
2667 /* Take advantage of the fact that the TID field is not used, to tag
2668 special ptids with it set to != 0. */
2669 static const ptid_t
magic_null_ptid (42000, -1, 1);
2670 static const ptid_t
not_sent_ptid (42000, -2, 1);
2671 static const ptid_t
any_thread_ptid (42000, 0, 1);
2673 /* Find out if the stub attached to PID (and hence GDB should offer to
2674 detach instead of killing it when bailing out). */
2677 remote_target::remote_query_attached (int pid
)
2679 struct remote_state
*rs
= get_remote_state ();
2680 size_t size
= get_remote_packet_size ();
2682 if (m_features
.packet_support (PACKET_qAttached
) == PACKET_DISABLE
)
2685 if (m_features
.remote_multi_process_p ())
2686 xsnprintf (rs
->buf
.data (), size
, "qAttached:%x", pid
);
2688 xsnprintf (rs
->buf
.data (), size
, "qAttached");
2693 switch (m_features
.packet_ok (rs
->buf
, PACKET_qAttached
))
2696 if (strcmp (rs
->buf
.data (), "1") == 0)
2700 warning (_("Remote failure reply: %s"), rs
->buf
.data ());
2702 case PACKET_UNKNOWN
:
2709 /* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
2710 has been invented by GDB, instead of reported by the target. Since
2711 we can be connected to a remote system before before knowing about
2712 any inferior, mark the target with execution when we find the first
2713 inferior. If ATTACHED is 1, then we had just attached to this
2714 inferior. If it is 0, then we just created this inferior. If it
2715 is -1, then try querying the remote stub to find out if it had
2716 attached to the inferior or not. If TRY_OPEN_EXEC is true then
2717 attempt to open this inferior's executable as the main executable
2718 if no main executable is open already. */
2721 remote_target::remote_add_inferior (bool fake_pid_p
, int pid
, int attached
,
2724 struct inferior
*inf
;
2726 /* Check whether this process we're learning about is to be
2727 considered attached, or if is to be considered to have been
2728 spawned by the stub. */
2730 attached
= remote_query_attached (pid
);
2732 if (gdbarch_has_global_solist (current_inferior ()->arch ()))
2734 /* If the target shares code across all inferiors, then every
2735 attach adds a new inferior. */
2736 inf
= add_inferior (pid
);
2738 /* ... and every inferior is bound to the same program space.
2739 However, each inferior may still have its own address
2741 inf
->aspace
= maybe_new_address_space ();
2742 inf
->pspace
= current_program_space
;
2746 /* In the traditional debugging scenario, there's a 1-1 match
2747 between program/address spaces. We simply bind the inferior
2748 to the program space's address space. */
2749 inf
= current_inferior ();
2751 /* However, if the current inferior is already bound to a
2752 process, find some other empty inferior. */
2756 for (inferior
*it
: all_inferiors ())
2765 /* Since all inferiors were already bound to a process, add
2767 inf
= add_inferior_with_spaces ();
2769 switch_to_inferior_no_thread (inf
);
2770 inf
->push_target (this);
2771 inferior_appeared (inf
, pid
);
2774 inf
->attach_flag
= attached
;
2775 inf
->fake_pid_p
= fake_pid_p
;
2777 /* If no main executable is currently open then attempt to
2778 open the file that was executed to create this inferior. */
2779 if (try_open_exec
&& get_exec_file (0) == NULL
)
2780 exec_file_locate_attach (pid
, 0, 1);
2782 /* Check for exec file mismatch, and let the user solve it. */
2783 validate_exec_file (1);
2788 static remote_thread_info
*get_remote_thread_info (thread_info
*thread
);
2789 static remote_thread_info
*get_remote_thread_info (remote_target
*target
,
2792 /* Add thread PTID to GDB's thread list. Tag it as executing/running
2793 according to EXECUTING and RUNNING respectively. If SILENT_P (or the
2794 remote_state::starting_up flag) is true then the new thread is added
2795 silently, otherwise the new thread will be announced to the user. */
2798 remote_target::remote_add_thread (ptid_t ptid
, bool running
, bool executing
,
2801 struct remote_state
*rs
= get_remote_state ();
2802 struct thread_info
*thread
;
2804 /* GDB historically didn't pull threads in the initial connection
2805 setup. If the remote target doesn't even have a concept of
2806 threads (e.g., a bare-metal target), even if internally we
2807 consider that a single-threaded target, mentioning a new thread
2808 might be confusing to the user. Be silent then, preserving the
2809 age old behavior. */
2810 if (rs
->starting_up
|| silent_p
)
2811 thread
= add_thread_silent (this, ptid
);
2813 thread
= add_thread (this, ptid
);
2816 get_remote_thread_info (thread
)->set_resumed ();
2817 set_executing (this, ptid
, executing
);
2818 set_running (this, ptid
, running
);
2823 /* Come here when we learn about a thread id from the remote target.
2824 It may be the first time we hear about such thread, so take the
2825 opportunity to add it to GDB's thread list. In case this is the
2826 first time we're noticing its corresponding inferior, add it to
2827 GDB's inferior list as well. EXECUTING indicates whether the
2828 thread is (internally) executing or stopped. */
2831 remote_target::remote_notice_new_inferior (ptid_t currthread
, bool executing
)
2833 /* In non-stop mode, we assume new found threads are (externally)
2834 running until proven otherwise with a stop reply. In all-stop,
2835 we can only get here if all threads are stopped. */
2836 bool running
= target_is_non_stop_p ();
2838 /* If this is a new thread, add it to GDB's thread list.
2839 If we leave it up to WFI to do this, bad things will happen. */
2841 thread_info
*tp
= this->find_thread (currthread
);
2842 if (tp
!= NULL
&& tp
->state
== THREAD_EXITED
)
2844 /* We're seeing an event on a thread id we knew had exited.
2845 This has to be a new thread reusing the old id. Add it. */
2846 remote_add_thread (currthread
, running
, executing
, false);
2850 if (!in_thread_list (this, currthread
))
2852 struct inferior
*inf
= NULL
;
2853 int pid
= currthread
.pid ();
2855 if (inferior_ptid
.is_pid ()
2856 && pid
== inferior_ptid
.pid ())
2858 /* inferior_ptid has no thread member yet. This can happen
2859 with the vAttach -> remote_wait,"TAAthread:" path if the
2860 stub doesn't support qC. This is the first stop reported
2861 after an attach, so this is the main thread. Update the
2862 ptid in the thread list. */
2863 if (in_thread_list (this, ptid_t (pid
)))
2864 thread_change_ptid (this, inferior_ptid
, currthread
);
2868 = remote_add_thread (currthread
, running
, executing
, false);
2869 switch_to_thread (thr
);
2874 if (magic_null_ptid
== inferior_ptid
)
2876 /* inferior_ptid is not set yet. This can happen with the
2877 vRun -> remote_wait,"TAAthread:" path if the stub
2878 doesn't support qC. This is the first stop reported
2879 after an attach, so this is the main thread. Update the
2880 ptid in the thread list. */
2881 thread_change_ptid (this, inferior_ptid
, currthread
);
2885 /* When connecting to a target remote, or to a target
2886 extended-remote which already was debugging an inferior, we
2887 may not know about it yet. Add it before adding its child
2888 thread, so notifications are emitted in a sensible order. */
2889 if (find_inferior_pid (this, currthread
.pid ()) == NULL
)
2891 bool fake_pid_p
= !m_features
.remote_multi_process_p ();
2893 inf
= remote_add_inferior (fake_pid_p
,
2894 currthread
.pid (), -1, 1);
2897 /* This is really a new thread. Add it. */
2898 thread_info
*new_thr
2899 = remote_add_thread (currthread
, running
, executing
, false);
2901 /* If we found a new inferior, let the common code do whatever
2902 it needs to with it (e.g., read shared libraries, insert
2903 breakpoints), unless we're just setting up an all-stop
2907 struct remote_state
*rs
= get_remote_state ();
2909 if (!rs
->starting_up
)
2910 notice_new_inferior (new_thr
, executing
, 0);
2915 /* Return THREAD's private thread data, creating it if necessary. */
2917 static remote_thread_info
*
2918 get_remote_thread_info (thread_info
*thread
)
2920 gdb_assert (thread
!= NULL
);
2922 if (thread
->priv
== NULL
)
2923 thread
->priv
.reset (new remote_thread_info
);
2925 return gdb::checked_static_cast
<remote_thread_info
*> (thread
->priv
.get ());
2928 /* Return PTID's private thread data, creating it if necessary. */
2930 static remote_thread_info
*
2931 get_remote_thread_info (remote_target
*target
, ptid_t ptid
)
2933 thread_info
*thr
= target
->find_thread (ptid
);
2934 return get_remote_thread_info (thr
);
2937 /* Call this function as a result of
2938 1) A halt indication (T packet) containing a thread id
2939 2) A direct query of currthread
2940 3) Successful execution of set thread */
2943 record_currthread (struct remote_state
*rs
, ptid_t currthread
)
2945 rs
->general_thread
= currthread
;
2948 /* If 'QPassSignals' is supported, tell the remote stub what signals
2949 it can simply pass through to the inferior without reporting. */
2952 remote_target::pass_signals (gdb::array_view
<const unsigned char> pass_signals
)
2954 if (m_features
.packet_support (PACKET_QPassSignals
) != PACKET_DISABLE
)
2956 char *pass_packet
, *p
;
2958 struct remote_state
*rs
= get_remote_state ();
2960 gdb_assert (pass_signals
.size () < 256);
2961 for (size_t i
= 0; i
< pass_signals
.size (); i
++)
2963 if (pass_signals
[i
])
2966 pass_packet
= (char *) xmalloc (count
* 3 + strlen ("QPassSignals:") + 1);
2967 strcpy (pass_packet
, "QPassSignals:");
2968 p
= pass_packet
+ strlen (pass_packet
);
2969 for (size_t i
= 0; i
< pass_signals
.size (); i
++)
2971 if (pass_signals
[i
])
2974 *p
++ = tohex (i
>> 4);
2975 *p
++ = tohex (i
& 15);
2984 if (!rs
->last_pass_packet
|| strcmp (rs
->last_pass_packet
, pass_packet
))
2986 putpkt (pass_packet
);
2988 m_features
.packet_ok (rs
->buf
, PACKET_QPassSignals
);
2989 xfree (rs
->last_pass_packet
);
2990 rs
->last_pass_packet
= pass_packet
;
2993 xfree (pass_packet
);
2997 /* If 'QCatchSyscalls' is supported, tell the remote stub
2998 to report syscalls to GDB. */
3001 remote_target::set_syscall_catchpoint (int pid
, bool needed
, int any_count
,
3002 gdb::array_view
<const int> syscall_counts
)
3004 const char *catch_packet
;
3005 enum packet_result result
;
3008 if (m_features
.packet_support (PACKET_QCatchSyscalls
) == PACKET_DISABLE
)
3010 /* Not supported. */
3014 if (needed
&& any_count
== 0)
3016 /* Count how many syscalls are to be caught. */
3017 for (size_t i
= 0; i
< syscall_counts
.size (); i
++)
3019 if (syscall_counts
[i
] != 0)
3024 remote_debug_printf ("pid %d needed %d any_count %d n_sysno %d",
3025 pid
, needed
, any_count
, n_sysno
);
3027 std::string built_packet
;
3030 /* Prepare a packet with the sysno list, assuming max 8+1
3031 characters for a sysno. If the resulting packet size is too
3032 big, fallback on the non-selective packet. */
3033 const int maxpktsz
= strlen ("QCatchSyscalls:1") + n_sysno
* 9 + 1;
3034 built_packet
.reserve (maxpktsz
);
3035 built_packet
= "QCatchSyscalls:1";
3038 /* Add in each syscall to be caught. */
3039 for (size_t i
= 0; i
< syscall_counts
.size (); i
++)
3041 if (syscall_counts
[i
] != 0)
3042 string_appendf (built_packet
, ";%zx", i
);
3045 if (built_packet
.size () > get_remote_packet_size ())
3047 /* catch_packet too big. Fallback to less efficient
3048 non selective mode, with GDB doing the filtering. */
3049 catch_packet
= "QCatchSyscalls:1";
3052 catch_packet
= built_packet
.c_str ();
3055 catch_packet
= "QCatchSyscalls:0";
3057 struct remote_state
*rs
= get_remote_state ();
3059 putpkt (catch_packet
);
3061 result
= m_features
.packet_ok (rs
->buf
, PACKET_QCatchSyscalls
);
3062 if (result
== PACKET_OK
)
3068 /* If 'QProgramSignals' is supported, tell the remote stub what
3069 signals it should pass through to the inferior when detaching. */
3072 remote_target::program_signals (gdb::array_view
<const unsigned char> signals
)
3074 if (m_features
.packet_support (PACKET_QProgramSignals
) != PACKET_DISABLE
)
3078 struct remote_state
*rs
= get_remote_state ();
3080 gdb_assert (signals
.size () < 256);
3081 for (size_t i
= 0; i
< signals
.size (); i
++)
3086 packet
= (char *) xmalloc (count
* 3 + strlen ("QProgramSignals:") + 1);
3087 strcpy (packet
, "QProgramSignals:");
3088 p
= packet
+ strlen (packet
);
3089 for (size_t i
= 0; i
< signals
.size (); i
++)
3091 if (signal_pass_state (i
))
3094 *p
++ = tohex (i
>> 4);
3095 *p
++ = tohex (i
& 15);
3104 if (!rs
->last_program_signals_packet
3105 || strcmp (rs
->last_program_signals_packet
, packet
) != 0)
3109 m_features
.packet_ok (rs
->buf
, PACKET_QProgramSignals
);
3110 xfree (rs
->last_program_signals_packet
);
3111 rs
->last_program_signals_packet
= packet
;
3118 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
3119 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
3120 thread. If GEN is set, set the general thread, if not, then set
3121 the step/continue thread. */
3123 remote_target::set_thread (ptid_t ptid
, int gen
)
3125 struct remote_state
*rs
= get_remote_state ();
3126 ptid_t state
= gen
? rs
->general_thread
: rs
->continue_thread
;
3127 char *buf
= rs
->buf
.data ();
3128 char *endbuf
= buf
+ get_remote_packet_size ();
3134 *buf
++ = gen
? 'g' : 'c';
3135 if (ptid
== magic_null_ptid
)
3136 xsnprintf (buf
, endbuf
- buf
, "0");
3137 else if (ptid
== any_thread_ptid
)
3138 xsnprintf (buf
, endbuf
- buf
, "0");
3139 else if (ptid
== minus_one_ptid
)
3140 xsnprintf (buf
, endbuf
- buf
, "-1");
3142 write_ptid (buf
, endbuf
, ptid
);
3146 rs
->general_thread
= ptid
;
3148 rs
->continue_thread
= ptid
;
3152 remote_target::set_general_thread (ptid_t ptid
)
3154 set_thread (ptid
, 1);
3158 remote_target::set_continue_thread (ptid_t ptid
)
3160 set_thread (ptid
, 0);
3163 /* Change the remote current process. Which thread within the process
3164 ends up selected isn't important, as long as it is the same process
3165 as what INFERIOR_PTID points to.
3167 This comes from that fact that there is no explicit notion of
3168 "selected process" in the protocol. The selected process for
3169 general operations is the process the selected general thread
3173 remote_target::set_general_process ()
3175 /* If the remote can't handle multiple processes, don't bother. */
3176 if (!m_features
.remote_multi_process_p ())
3179 remote_state
*rs
= get_remote_state ();
3181 /* We only need to change the remote current thread if it's pointing
3182 at some other process. */
3183 if (rs
->general_thread
.pid () != inferior_ptid
.pid ())
3184 set_general_thread (inferior_ptid
);
3188 /* Return nonzero if this is the main thread that we made up ourselves
3189 to model non-threaded targets as single-threaded. */
3192 remote_thread_always_alive (ptid_t ptid
)
3194 if (ptid
== magic_null_ptid
)
3195 /* The main thread is always alive. */
3198 if (ptid
.pid () != 0 && ptid
.lwp () == 0)
3199 /* The main thread is always alive. This can happen after a
3200 vAttach, if the remote side doesn't support
3207 /* Return nonzero if the thread PTID is still alive on the remote
3211 remote_target::thread_alive (ptid_t ptid
)
3213 struct remote_state
*rs
= get_remote_state ();
3216 /* Check if this is a thread that we made up ourselves to model
3217 non-threaded targets as single-threaded. */
3218 if (remote_thread_always_alive (ptid
))
3221 p
= rs
->buf
.data ();
3222 endp
= p
+ get_remote_packet_size ();
3225 write_ptid (p
, endp
, ptid
);
3229 return (rs
->buf
[0] == 'O' && rs
->buf
[1] == 'K');
3232 /* Return a pointer to a thread name if we know it and NULL otherwise.
3233 The thread_info object owns the memory for the name. */
3236 remote_target::thread_name (struct thread_info
*info
)
3238 if (info
->priv
!= NULL
)
3240 const std::string
&name
= get_remote_thread_info (info
)->name
;
3241 return !name
.empty () ? name
.c_str () : NULL
;
3247 /* About these extended threadlist and threadinfo packets. They are
3248 variable length packets but, the fields within them are often fixed
3249 length. They are redundant enough to send over UDP as is the
3250 remote protocol in general. There is a matching unit test module
3253 /* WARNING: This threadref data structure comes from the remote O.S.,
3254 libstub protocol encoding, and remote.c. It is not particularly
3257 /* Right now, the internal structure is int. We want it to be bigger.
3258 Plan to fix this. */
3260 typedef int gdb_threadref
; /* Internal GDB thread reference. */
3262 /* gdb_ext_thread_info is an internal GDB data structure which is
3263 equivalent to the reply of the remote threadinfo packet. */
3265 struct gdb_ext_thread_info
3267 threadref threadid
; /* External form of thread reference. */
3268 int active
; /* Has state interesting to GDB?
3270 char display
[256]; /* Brief state display, name,
3271 blocked/suspended. */
3272 char shortname
[32]; /* To be used to name threads. */
3273 char more_display
[256]; /* Long info, statistics, queue depth,
3277 /* The volume of remote transfers can be limited by submitting
3278 a mask containing bits specifying the desired information.
3279 Use a union of these values as the 'selection' parameter to
3280 get_thread_info. FIXME: Make these TAG names more thread specific. */
3282 #define TAG_THREADID 1
3283 #define TAG_EXISTS 2
3284 #define TAG_DISPLAY 4
3285 #define TAG_THREADNAME 8
3286 #define TAG_MOREDISPLAY 16
3288 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
3290 static const char *unpack_nibble (const char *buf
, int *val
);
3292 static const char *unpack_byte (const char *buf
, int *value
);
3294 static char *pack_int (char *buf
, int value
);
3296 static const char *unpack_int (const char *buf
, int *value
);
3298 static const char *unpack_string (const char *src
, char *dest
, int length
);
3300 static char *pack_threadid (char *pkt
, threadref
*id
);
3302 static const char *unpack_threadid (const char *inbuf
, threadref
*id
);
3304 void int_to_threadref (threadref
*id
, int value
);
3306 static int threadref_to_int (threadref
*ref
);
3308 static void copy_threadref (threadref
*dest
, threadref
*src
);
3310 static int threadmatch (threadref
*dest
, threadref
*src
);
3312 static char *pack_threadinfo_request (char *pkt
, int mode
,
3315 static char *pack_threadlist_request (char *pkt
, int startflag
,
3317 threadref
*nextthread
);
3319 static int remote_newthread_step (threadref
*ref
, void *context
);
3322 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
3323 buffer we're allowed to write to. Returns
3324 BUF+CHARACTERS_WRITTEN. */
3327 remote_target::write_ptid (char *buf
, const char *endbuf
, ptid_t ptid
)
3331 if (m_features
.remote_multi_process_p ())
3335 buf
+= xsnprintf (buf
, endbuf
- buf
, "p-%x.", -pid
);
3337 buf
+= xsnprintf (buf
, endbuf
- buf
, "p%x.", pid
);
3341 buf
+= xsnprintf (buf
, endbuf
- buf
, "-%x", -tid
);
3343 buf
+= xsnprintf (buf
, endbuf
- buf
, "%x", tid
);
3348 /* Extract a PTID from BUF. If non-null, OBUF is set to one past the
3349 last parsed char. Returns null_ptid if no thread id is found, and
3350 throws an error if the thread id has an invalid format. */
3353 read_ptid (const char *buf
, const char **obuf
)
3355 const char *p
= buf
;
3357 ULONGEST pid
= 0, tid
= 0;
3361 /* Multi-process ptid. */
3362 pp
= unpack_varlen_hex (p
+ 1, &pid
);
3364 error (_("invalid remote ptid: %s"), p
);
3367 pp
= unpack_varlen_hex (p
+ 1, &tid
);
3370 return ptid_t (pid
, tid
);
3373 /* No multi-process. Just a tid. */
3374 pp
= unpack_varlen_hex (p
, &tid
);
3376 /* Return null_ptid when no thread id is found. */
3384 /* Since the stub is not sending a process id, default to what's
3385 current_inferior, unless it doesn't have a PID yet. If so,
3386 then since there's no way to know the pid of the reported
3387 threads, use the magic number. */
3388 inferior
*inf
= current_inferior ();
3390 pid
= magic_null_ptid
.pid ();
3396 return ptid_t (pid
, tid
);
3402 if (ch
>= 'a' && ch
<= 'f')
3403 return ch
- 'a' + 10;
3404 if (ch
>= '0' && ch
<= '9')
3406 if (ch
>= 'A' && ch
<= 'F')
3407 return ch
- 'A' + 10;
3412 stub_unpack_int (const char *buff
, int fieldlength
)
3419 nibble
= stubhex (*buff
++);
3423 retval
= retval
<< 4;
3429 unpack_nibble (const char *buf
, int *val
)
3431 *val
= fromhex (*buf
++);
3436 unpack_byte (const char *buf
, int *value
)
3438 *value
= stub_unpack_int (buf
, 2);
3443 pack_int (char *buf
, int value
)
3445 buf
= pack_hex_byte (buf
, (value
>> 24) & 0xff);
3446 buf
= pack_hex_byte (buf
, (value
>> 16) & 0xff);
3447 buf
= pack_hex_byte (buf
, (value
>> 8) & 0x0ff);
3448 buf
= pack_hex_byte (buf
, (value
& 0xff));
3453 unpack_int (const char *buf
, int *value
)
3455 *value
= stub_unpack_int (buf
, 8);
3459 #if 0 /* Currently unused, uncomment when needed. */
3460 static char *pack_string (char *pkt
, char *string
);
3463 pack_string (char *pkt
, char *string
)
3468 len
= strlen (string
);
3470 len
= 200; /* Bigger than most GDB packets, junk??? */
3471 pkt
= pack_hex_byte (pkt
, len
);
3475 if ((ch
== '\0') || (ch
== '#'))
3476 ch
= '*'; /* Protect encapsulation. */
3481 #endif /* 0 (unused) */
3484 unpack_string (const char *src
, char *dest
, int length
)
3493 pack_threadid (char *pkt
, threadref
*id
)
3496 unsigned char *altid
;
3498 altid
= (unsigned char *) id
;
3499 limit
= pkt
+ BUF_THREAD_ID_SIZE
;
3501 pkt
= pack_hex_byte (pkt
, *altid
++);
3507 unpack_threadid (const char *inbuf
, threadref
*id
)
3510 const char *limit
= inbuf
+ BUF_THREAD_ID_SIZE
;
3513 altref
= (char *) id
;
3515 while (inbuf
< limit
)
3517 x
= stubhex (*inbuf
++);
3518 y
= stubhex (*inbuf
++);
3519 *altref
++ = (x
<< 4) | y
;
3524 /* Externally, threadrefs are 64 bits but internally, they are still
3525 ints. This is due to a mismatch of specifications. We would like
3526 to use 64bit thread references internally. This is an adapter
3530 int_to_threadref (threadref
*id
, int value
)
3532 unsigned char *scan
;
3534 scan
= (unsigned char *) id
;
3540 *scan
++ = (value
>> 24) & 0xff;
3541 *scan
++ = (value
>> 16) & 0xff;
3542 *scan
++ = (value
>> 8) & 0xff;
3543 *scan
++ = (value
& 0xff);
3547 threadref_to_int (threadref
*ref
)
3550 unsigned char *scan
;
3556 value
= (value
<< 8) | ((*scan
++) & 0xff);
3561 copy_threadref (threadref
*dest
, threadref
*src
)
3564 unsigned char *csrc
, *cdest
;
3566 csrc
= (unsigned char *) src
;
3567 cdest
= (unsigned char *) dest
;
3574 threadmatch (threadref
*dest
, threadref
*src
)
3576 /* Things are broken right now, so just assume we got a match. */
3578 unsigned char *srcp
, *destp
;
3580 srcp
= (char *) src
;
3581 destp
= (char *) dest
;
3585 result
&= (*srcp
++ == *destp
++) ? 1 : 0;
3592 threadid:1, # always request threadid
3599 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
3602 pack_threadinfo_request (char *pkt
, int mode
, threadref
*id
)
3604 *pkt
++ = 'q'; /* Info Query */
3605 *pkt
++ = 'P'; /* process or thread info */
3606 pkt
= pack_int (pkt
, mode
); /* mode */
3607 pkt
= pack_threadid (pkt
, id
); /* threadid */
3608 *pkt
= '\0'; /* terminate */
3612 /* These values tag the fields in a thread info response packet. */
3613 /* Tagging the fields allows us to request specific fields and to
3614 add more fields as time goes by. */
3616 #define TAG_THREADID 1 /* Echo the thread identifier. */
3617 #define TAG_EXISTS 2 /* Is this process defined enough to
3618 fetch registers and its stack? */
3619 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
3620 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
3621 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
3625 remote_target::remote_unpack_thread_info_response (const char *pkt
,
3626 threadref
*expectedref
,
3627 gdb_ext_thread_info
*info
)
3629 struct remote_state
*rs
= get_remote_state ();
3633 const char *limit
= pkt
+ rs
->buf
.size (); /* Plausible parsing limit. */
3636 /* info->threadid = 0; FIXME: implement zero_threadref. */
3638 info
->display
[0] = '\0';
3639 info
->shortname
[0] = '\0';
3640 info
->more_display
[0] = '\0';
3642 /* Assume the characters indicating the packet type have been
3644 pkt
= unpack_int (pkt
, &mask
); /* arg mask */
3645 pkt
= unpack_threadid (pkt
, &ref
);
3648 warning (_("Incomplete response to threadinfo request."));
3649 if (!threadmatch (&ref
, expectedref
))
3650 { /* This is an answer to a different request. */
3651 warning (_("ERROR RMT Thread info mismatch."));
3654 copy_threadref (&info
->threadid
, &ref
);
3656 /* Loop on tagged fields , try to bail if something goes wrong. */
3658 /* Packets are terminated with nulls. */
3659 while ((pkt
< limit
) && mask
&& *pkt
)
3661 pkt
= unpack_int (pkt
, &tag
); /* tag */
3662 pkt
= unpack_byte (pkt
, &length
); /* length */
3663 if (!(tag
& mask
)) /* Tags out of synch with mask. */
3665 warning (_("ERROR RMT: threadinfo tag mismatch."));
3669 if (tag
== TAG_THREADID
)
3673 warning (_("ERROR RMT: length of threadid is not 16."));
3677 pkt
= unpack_threadid (pkt
, &ref
);
3678 mask
= mask
& ~TAG_THREADID
;
3681 if (tag
== TAG_EXISTS
)
3683 info
->active
= stub_unpack_int (pkt
, length
);
3685 mask
= mask
& ~(TAG_EXISTS
);
3688 warning (_("ERROR RMT: 'exists' length too long."));
3694 if (tag
== TAG_THREADNAME
)
3696 pkt
= unpack_string (pkt
, &info
->shortname
[0], length
);
3697 mask
= mask
& ~TAG_THREADNAME
;
3700 if (tag
== TAG_DISPLAY
)
3702 pkt
= unpack_string (pkt
, &info
->display
[0], length
);
3703 mask
= mask
& ~TAG_DISPLAY
;
3706 if (tag
== TAG_MOREDISPLAY
)
3708 pkt
= unpack_string (pkt
, &info
->more_display
[0], length
);
3709 mask
= mask
& ~TAG_MOREDISPLAY
;
3712 warning (_("ERROR RMT: unknown thread info tag."));
3713 break; /* Not a tag we know about. */
3719 remote_target::remote_get_threadinfo (threadref
*threadid
,
3721 gdb_ext_thread_info
*info
)
3723 struct remote_state
*rs
= get_remote_state ();
3726 pack_threadinfo_request (rs
->buf
.data (), fieldset
, threadid
);
3730 if (rs
->buf
[0] == '\0')
3733 result
= remote_unpack_thread_info_response (&rs
->buf
[2],
3738 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
3741 pack_threadlist_request (char *pkt
, int startflag
, int threadcount
,
3742 threadref
*nextthread
)
3744 *pkt
++ = 'q'; /* info query packet */
3745 *pkt
++ = 'L'; /* Process LIST or threadLIST request */
3746 pkt
= pack_nibble (pkt
, startflag
); /* initflag 1 bytes */
3747 pkt
= pack_hex_byte (pkt
, threadcount
); /* threadcount 2 bytes */
3748 pkt
= pack_threadid (pkt
, nextthread
); /* 64 bit thread identifier */
3753 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
3756 remote_target::parse_threadlist_response (const char *pkt
, int result_limit
,
3757 threadref
*original_echo
,
3758 threadref
*resultlist
,
3761 struct remote_state
*rs
= get_remote_state ();
3762 int count
, resultcount
, done
;
3765 /* Assume the 'q' and 'M chars have been stripped. */
3766 const char *limit
= pkt
+ (rs
->buf
.size () - BUF_THREAD_ID_SIZE
);
3767 /* done parse past here */
3768 pkt
= unpack_byte (pkt
, &count
); /* count field */
3769 pkt
= unpack_nibble (pkt
, &done
);
3770 /* The first threadid is the argument threadid. */
3771 pkt
= unpack_threadid (pkt
, original_echo
); /* should match query packet */
3772 while ((count
-- > 0) && (pkt
< limit
))
3774 pkt
= unpack_threadid (pkt
, resultlist
++);
3775 if (resultcount
++ >= result_limit
)
3783 /* Fetch the next batch of threads from the remote. Returns -1 if the
3784 qL packet is not supported, 0 on error and 1 on success. */
3787 remote_target::remote_get_threadlist (int startflag
, threadref
*nextthread
,
3788 int result_limit
, int *done
, int *result_count
,
3789 threadref
*threadlist
)
3791 struct remote_state
*rs
= get_remote_state ();
3794 /* Truncate result limit to be smaller than the packet size. */
3795 if ((((result_limit
+ 1) * BUF_THREAD_ID_SIZE
) + 10)
3796 >= get_remote_packet_size ())
3797 result_limit
= (get_remote_packet_size () / BUF_THREAD_ID_SIZE
) - 2;
3799 pack_threadlist_request (rs
->buf
.data (), startflag
, result_limit
,
3803 if (rs
->buf
[0] == '\0')
3805 /* Packet not supported. */
3810 parse_threadlist_response (&rs
->buf
[2], result_limit
,
3811 &rs
->echo_nextthread
, threadlist
, done
);
3813 if (!threadmatch (&rs
->echo_nextthread
, nextthread
))
3815 /* FIXME: This is a good reason to drop the packet. */
3816 /* Possibly, there is a duplicate response. */
3818 retransmit immediatly - race conditions
3819 retransmit after timeout - yes
3821 wait for packet, then exit
3823 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
3824 return 0; /* I choose simply exiting. */
3826 if (*result_count
<= 0)
3830 warning (_("RMT ERROR : failed to get remote thread list."));
3833 return result
; /* break; */
3835 if (*result_count
> result_limit
)
3838 warning (_("RMT ERROR: threadlist response longer than requested."));
3844 /* Fetch the list of remote threads, with the qL packet, and call
3845 STEPFUNCTION for each thread found. Stops iterating and returns 1
3846 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
3847 STEPFUNCTION returns false. If the packet is not supported,
3851 remote_target::remote_threadlist_iterator (rmt_thread_action stepfunction
,
3852 void *context
, int looplimit
)
3854 struct remote_state
*rs
= get_remote_state ();
3855 int done
, i
, result_count
;
3863 if (loopcount
++ > looplimit
)
3866 warning (_("Remote fetch threadlist -infinite loop-."));
3869 result
= remote_get_threadlist (startflag
, &rs
->nextthread
,
3870 MAXTHREADLISTRESULTS
,
3871 &done
, &result_count
,
3872 rs
->resultthreadlist
);
3875 /* Clear for later iterations. */
3877 /* Setup to resume next batch of thread references, set nextthread. */
3878 if (result_count
>= 1)
3879 copy_threadref (&rs
->nextthread
,
3880 &rs
->resultthreadlist
[result_count
- 1]);
3882 while (result_count
--)
3884 if (!(*stepfunction
) (&rs
->resultthreadlist
[i
++], context
))
3894 /* A thread found on the remote target. */
3898 explicit thread_item (ptid_t ptid_
)
3902 thread_item (thread_item
&&other
) = default;
3903 thread_item
&operator= (thread_item
&&other
) = default;
3905 DISABLE_COPY_AND_ASSIGN (thread_item
);
3907 /* The thread's PTID. */
3910 /* The thread's extra info. */
3913 /* The thread's name. */
3916 /* The core the thread was running on. -1 if not known. */
3919 /* The thread handle associated with the thread. */
3920 gdb::byte_vector thread_handle
;
3923 /* Context passed around to the various methods listing remote
3924 threads. As new threads are found, they're added to the ITEMS
3927 struct threads_listing_context
3929 /* Return true if this object contains an entry for a thread with ptid
3932 bool contains_thread (ptid_t ptid
) const
3934 auto match_ptid
= [&] (const thread_item
&item
)
3936 return item
.ptid
== ptid
;
3939 auto it
= std::find_if (this->items
.begin (),
3943 return it
!= this->items
.end ();
3946 /* Remove the thread with ptid PTID. */
3948 void remove_thread (ptid_t ptid
)
3950 auto match_ptid
= [&] (const thread_item
&item
)
3952 return item
.ptid
== ptid
;
3955 auto it
= std::remove_if (this->items
.begin (),
3959 if (it
!= this->items
.end ())
3960 this->items
.erase (it
);
3963 /* The threads found on the remote target. */
3964 std::vector
<thread_item
> items
;
3968 remote_newthread_step (threadref
*ref
, void *data
)
3970 struct threads_listing_context
*context
3971 = (struct threads_listing_context
*) data
;
3972 int pid
= inferior_ptid
.pid ();
3973 int lwp
= threadref_to_int (ref
);
3974 ptid_t
ptid (pid
, lwp
);
3976 context
->items
.emplace_back (ptid
);
3978 return 1; /* continue iterator */
3981 #define CRAZY_MAX_THREADS 1000
3984 remote_target::remote_current_thread (ptid_t oldpid
)
3986 struct remote_state
*rs
= get_remote_state ();
3990 if (rs
->buf
[0] == 'Q' && rs
->buf
[1] == 'C')
3995 result
= read_ptid (&rs
->buf
[2], &obuf
);
3997 remote_debug_printf ("warning: garbage in qC reply");
4005 /* List remote threads using the deprecated qL packet. */
4008 remote_target::remote_get_threads_with_ql (threads_listing_context
*context
)
4010 if (remote_threadlist_iterator (remote_newthread_step
, context
,
4011 CRAZY_MAX_THREADS
) >= 0)
4017 #if defined(HAVE_LIBEXPAT)
4020 start_thread (struct gdb_xml_parser
*parser
,
4021 const struct gdb_xml_element
*element
,
4023 std::vector
<gdb_xml_value
> &attributes
)
4025 struct threads_listing_context
*data
4026 = (struct threads_listing_context
*) user_data
;
4027 struct gdb_xml_value
*attr
;
4029 char *id
= (char *) xml_find_attribute (attributes
, "id")->value
.get ();
4030 ptid_t ptid
= read_ptid (id
, NULL
);
4032 data
->items
.emplace_back (ptid
);
4033 thread_item
&item
= data
->items
.back ();
4035 attr
= xml_find_attribute (attributes
, "core");
4037 item
.core
= *(ULONGEST
*) attr
->value
.get ();
4039 attr
= xml_find_attribute (attributes
, "name");
4041 item
.name
= (const char *) attr
->value
.get ();
4043 attr
= xml_find_attribute (attributes
, "handle");
4045 item
.thread_handle
= hex2bin ((const char *) attr
->value
.get ());
4049 end_thread (struct gdb_xml_parser
*parser
,
4050 const struct gdb_xml_element
*element
,
4051 void *user_data
, const char *body_text
)
4053 struct threads_listing_context
*data
4054 = (struct threads_listing_context
*) user_data
;
4056 if (body_text
!= NULL
&& *body_text
!= '\0')
4057 data
->items
.back ().extra
= body_text
;
4060 const struct gdb_xml_attribute thread_attributes
[] = {
4061 { "id", GDB_XML_AF_NONE
, NULL
, NULL
},
4062 { "core", GDB_XML_AF_OPTIONAL
, gdb_xml_parse_attr_ulongest
, NULL
},
4063 { "name", GDB_XML_AF_OPTIONAL
, NULL
, NULL
},
4064 { "handle", GDB_XML_AF_OPTIONAL
, NULL
, NULL
},
4065 { NULL
, GDB_XML_AF_NONE
, NULL
, NULL
}
4068 const struct gdb_xml_element thread_children
[] = {
4069 { NULL
, NULL
, NULL
, GDB_XML_EF_NONE
, NULL
, NULL
}
4072 const struct gdb_xml_element threads_children
[] = {
4073 { "thread", thread_attributes
, thread_children
,
4074 GDB_XML_EF_REPEATABLE
| GDB_XML_EF_OPTIONAL
,
4075 start_thread
, end_thread
},
4076 { NULL
, NULL
, NULL
, GDB_XML_EF_NONE
, NULL
, NULL
}
4079 const struct gdb_xml_element threads_elements
[] = {
4080 { "threads", NULL
, threads_children
,
4081 GDB_XML_EF_NONE
, NULL
, NULL
},
4082 { NULL
, NULL
, NULL
, GDB_XML_EF_NONE
, NULL
, NULL
}
4087 /* List remote threads using qXfer:threads:read. */
4090 remote_target::remote_get_threads_with_qxfer (threads_listing_context
*context
)
4092 #if defined(HAVE_LIBEXPAT)
4093 if (m_features
.packet_support (PACKET_qXfer_threads
) == PACKET_ENABLE
)
4095 std::optional
<gdb::char_vector
> xml
4096 = target_read_stralloc (this, TARGET_OBJECT_THREADS
, NULL
);
4098 if (xml
&& (*xml
)[0] != '\0')
4100 gdb_xml_parse_quick (_("threads"), "threads.dtd",
4101 threads_elements
, xml
->data (), context
);
4111 /* List remote threads using qfThreadInfo/qsThreadInfo. */
4114 remote_target::remote_get_threads_with_qthreadinfo (threads_listing_context
*context
)
4116 struct remote_state
*rs
= get_remote_state ();
4118 if (rs
->use_threadinfo_query
)
4122 putpkt ("qfThreadInfo");
4124 bufp
= rs
->buf
.data ();
4125 if (bufp
[0] != '\0') /* q packet recognized */
4127 while (*bufp
++ == 'm') /* reply contains one or more TID */
4131 ptid_t ptid
= read_ptid (bufp
, &bufp
);
4132 context
->items
.emplace_back (ptid
);
4134 while (*bufp
++ == ','); /* comma-separated list */
4135 putpkt ("qsThreadInfo");
4137 bufp
= rs
->buf
.data ();
4143 /* Packet not recognized. */
4144 rs
->use_threadinfo_query
= 0;
4151 /* Return true if INF only has one non-exited thread. */
4154 has_single_non_exited_thread (inferior
*inf
)
4157 for (thread_info
*tp ATTRIBUTE_UNUSED
: inf
->non_exited_threads ())
4163 /* Implement the to_update_thread_list function for the remote
4167 remote_target::update_thread_list ()
4169 struct threads_listing_context context
;
4172 /* We have a few different mechanisms to fetch the thread list. Try
4173 them all, starting with the most preferred one first, falling
4174 back to older methods. */
4175 if (remote_get_threads_with_qxfer (&context
)
4176 || remote_get_threads_with_qthreadinfo (&context
)
4177 || remote_get_threads_with_ql (&context
))
4181 if (context
.items
.empty ()
4182 && remote_thread_always_alive (inferior_ptid
))
4184 /* Some targets don't really support threads, but still
4185 reply an (empty) thread list in response to the thread
4186 listing packets, instead of replying "packet not
4187 supported". Exit early so we don't delete the main
4192 /* CONTEXT now holds the current thread list on the remote
4193 target end. Delete GDB-side threads no longer found on the
4195 for (thread_info
*tp
: all_threads_safe ())
4197 if (tp
->inf
->process_target () != this)
4200 if (!context
.contains_thread (tp
->ptid
))
4202 /* Do not remove the thread if it is the last thread in
4203 the inferior. This situation happens when we have a
4204 pending exit process status to process. Otherwise we
4205 may end up with a seemingly live inferior (i.e. pid
4206 != 0) that has no threads. */
4207 if (has_single_non_exited_thread (tp
->inf
))
4210 /* Do not remove the thread if we've requested to be
4211 notified of its exit. For example, the thread may be
4212 displaced stepping, infrun will need to handle the
4213 exit event, and displaced stepping info is recorded
4214 in the thread object. If we deleted the thread now,
4215 we'd lose that info. */
4216 if ((tp
->thread_options () & GDB_THREAD_OPTION_EXIT
) != 0)
4224 /* Remove any unreported fork/vfork/clone child threads from
4225 CONTEXT so that we don't interfere with follow
4226 fork/vfork/clone, which is where creation of such threads is
4228 remove_new_children (&context
);
4230 /* And now add threads we don't know about yet to our list. */
4231 for (thread_item
&item
: context
.items
)
4233 if (item
.ptid
!= null_ptid
)
4235 /* In non-stop mode, we assume new found threads are
4236 executing until proven otherwise with a stop reply.
4237 In all-stop, we can only get here if all threads are
4239 bool executing
= target_is_non_stop_p ();
4241 remote_notice_new_inferior (item
.ptid
, executing
);
4243 thread_info
*tp
= this->find_thread (item
.ptid
);
4244 remote_thread_info
*info
= get_remote_thread_info (tp
);
4245 info
->core
= item
.core
;
4246 info
->extra
= std::move (item
.extra
);
4247 info
->name
= std::move (item
.name
);
4248 info
->thread_handle
= std::move (item
.thread_handle
);
4255 /* If no thread listing method is supported, then query whether
4256 each known thread is alive, one by one, with the T packet.
4257 If the target doesn't support threads at all, then this is a
4258 no-op. See remote_thread_alive. */
4264 * Collect a descriptive string about the given thread.
4265 * The target may say anything it wants to about the thread
4266 * (typically info about its blocked / runnable state, name, etc.).
4267 * This string will appear in the info threads display.
4269 * Optional: targets are not required to implement this function.
4273 remote_target::extra_thread_info (thread_info
*tp
)
4275 struct remote_state
*rs
= get_remote_state ();
4278 struct gdb_ext_thread_info threadinfo
;
4280 if (rs
->remote_desc
== 0) /* paranoia */
4281 internal_error (_("remote_threads_extra_info"));
4283 if (tp
->ptid
== magic_null_ptid
4284 || (tp
->ptid
.pid () != 0 && tp
->ptid
.lwp () == 0))
4285 /* This is the main thread which was added by GDB. The remote
4286 server doesn't know about it. */
4289 std::string
&extra
= get_remote_thread_info (tp
)->extra
;
4291 /* If already have cached info, use it. */
4292 if (!extra
.empty ())
4293 return extra
.c_str ();
4295 if (m_features
.packet_support (PACKET_qXfer_threads
) == PACKET_ENABLE
)
4297 /* If we're using qXfer:threads:read, then the extra info is
4298 included in the XML. So if we didn't have anything cached,
4299 it's because there's really no extra info. */
4303 if (rs
->use_threadextra_query
)
4305 char *b
= rs
->buf
.data ();
4306 char *endb
= b
+ get_remote_packet_size ();
4308 xsnprintf (b
, endb
- b
, "qThreadExtraInfo,");
4310 write_ptid (b
, endb
, tp
->ptid
);
4314 if (rs
->buf
[0] != 0)
4316 extra
.resize (strlen (rs
->buf
.data ()) / 2);
4317 hex2bin (rs
->buf
.data (), (gdb_byte
*) &extra
[0], extra
.size ());
4318 return extra
.c_str ();
4322 /* If the above query fails, fall back to the old method. */
4323 rs
->use_threadextra_query
= 0;
4324 set
= TAG_THREADID
| TAG_EXISTS
| TAG_THREADNAME
4325 | TAG_MOREDISPLAY
| TAG_DISPLAY
;
4326 int_to_threadref (&id
, tp
->ptid
.lwp ());
4327 if (remote_get_threadinfo (&id
, set
, &threadinfo
))
4328 if (threadinfo
.active
)
4330 if (*threadinfo
.shortname
)
4331 string_appendf (extra
, " Name: %s", threadinfo
.shortname
);
4332 if (*threadinfo
.display
)
4334 if (!extra
.empty ())
4336 string_appendf (extra
, " State: %s", threadinfo
.display
);
4338 if (*threadinfo
.more_display
)
4340 if (!extra
.empty ())
4342 string_appendf (extra
, " Priority: %s", threadinfo
.more_display
);
4344 return extra
.c_str ();
4351 remote_target::static_tracepoint_marker_at (CORE_ADDR addr
,
4352 struct static_tracepoint_marker
*marker
)
4354 struct remote_state
*rs
= get_remote_state ();
4355 char *p
= rs
->buf
.data ();
4357 xsnprintf (p
, get_remote_packet_size (), "qTSTMat:");
4359 p
+= hexnumstr (p
, addr
);
4362 p
= rs
->buf
.data ();
4365 error (_("Remote failure reply: %s"), p
);
4369 parse_static_tracepoint_marker_definition (p
, NULL
, marker
);
4376 std::vector
<static_tracepoint_marker
>
4377 remote_target::static_tracepoint_markers_by_strid (const char *strid
)
4379 struct remote_state
*rs
= get_remote_state ();
4380 std::vector
<static_tracepoint_marker
> markers
;
4382 static_tracepoint_marker marker
;
4384 /* Ask for a first packet of static tracepoint marker
4388 p
= rs
->buf
.data ();
4390 error (_("Remote failure reply: %s"), p
);
4396 parse_static_tracepoint_marker_definition (p
, &p
, &marker
);
4398 if (strid
== NULL
|| marker
.str_id
== strid
)
4399 markers
.push_back (std::move (marker
));
4401 while (*p
++ == ','); /* comma-separated list */
4402 /* Ask for another packet of static tracepoint definition. */
4405 p
= rs
->buf
.data ();
4412 /* Implement the to_get_ada_task_ptid function for the remote targets. */
4415 remote_target::get_ada_task_ptid (long lwp
, ULONGEST thread
)
4417 return ptid_t (inferior_ptid
.pid (), lwp
);
4421 /* Restart the remote side; this is an extended protocol operation. */
4424 remote_target::extended_remote_restart ()
4426 struct remote_state
*rs
= get_remote_state ();
4428 /* Send the restart command; for reasons I don't understand the
4429 remote side really expects a number after the "R". */
4430 xsnprintf (rs
->buf
.data (), get_remote_packet_size (), "R%x", 0);
4433 remote_fileio_reset ();
4436 /* Clean up connection to a remote debugger. */
4439 remote_target::close ()
4441 /* Make sure we leave stdin registered in the event loop. */
4444 trace_reset_local_state ();
4449 remote_target::~remote_target ()
4451 struct remote_state
*rs
= get_remote_state ();
4453 /* Check for NULL because we may get here with a partially
4454 constructed target/connection. */
4455 if (rs
->remote_desc
== nullptr)
4458 serial_close (rs
->remote_desc
);
4460 /* We are destroying the remote target, so we should discard
4461 everything of this target. */
4462 discard_pending_stop_replies_in_queue ();
4464 rs
->delete_async_event_handler ();
4466 delete rs
->notif_state
;
4469 /* Query the remote side for the text, data and bss offsets. */
4472 remote_target::get_offsets ()
4474 struct remote_state
*rs
= get_remote_state ();
4477 int lose
, num_segments
= 0, do_sections
, do_segments
;
4478 CORE_ADDR text_addr
, data_addr
, bss_addr
, segments
[2];
4480 if (current_program_space
->symfile_object_file
== NULL
)
4483 putpkt ("qOffsets");
4485 buf
= rs
->buf
.data ();
4487 if (buf
[0] == '\000')
4488 return; /* Return silently. Stub doesn't support
4492 warning (_("Remote failure reply: %s"), buf
);
4496 /* Pick up each field in turn. This used to be done with scanf, but
4497 scanf will make trouble if CORE_ADDR size doesn't match
4498 conversion directives correctly. The following code will work
4499 with any size of CORE_ADDR. */
4500 text_addr
= data_addr
= bss_addr
= 0;
4504 if (startswith (ptr
, "Text="))
4507 /* Don't use strtol, could lose on big values. */
4508 while (*ptr
&& *ptr
!= ';')
4509 text_addr
= (text_addr
<< 4) + fromhex (*ptr
++);
4511 if (startswith (ptr
, ";Data="))
4514 while (*ptr
&& *ptr
!= ';')
4515 data_addr
= (data_addr
<< 4) + fromhex (*ptr
++);
4520 if (!lose
&& startswith (ptr
, ";Bss="))
4523 while (*ptr
&& *ptr
!= ';')
4524 bss_addr
= (bss_addr
<< 4) + fromhex (*ptr
++);
4526 if (bss_addr
!= data_addr
)
4527 warning (_("Target reported unsupported offsets: %s"), buf
);
4532 else if (startswith (ptr
, "TextSeg="))
4535 /* Don't use strtol, could lose on big values. */
4536 while (*ptr
&& *ptr
!= ';')
4537 text_addr
= (text_addr
<< 4) + fromhex (*ptr
++);
4540 if (startswith (ptr
, ";DataSeg="))
4543 while (*ptr
&& *ptr
!= ';')
4544 data_addr
= (data_addr
<< 4) + fromhex (*ptr
++);
4552 error (_("Malformed response to offset query, %s"), buf
);
4553 else if (*ptr
!= '\0')
4554 warning (_("Target reported unsupported offsets: %s"), buf
);
4556 objfile
*objf
= current_program_space
->symfile_object_file
;
4557 section_offsets offs
= objf
->section_offsets
;
4559 symfile_segment_data_up data
= get_symfile_segment_data (objf
->obfd
.get ());
4560 do_segments
= (data
!= NULL
);
4561 do_sections
= num_segments
== 0;
4563 if (num_segments
> 0)
4565 segments
[0] = text_addr
;
4566 segments
[1] = data_addr
;
4568 /* If we have two segments, we can still try to relocate everything
4569 by assuming that the .text and .data offsets apply to the whole
4570 text and data segments. Convert the offsets given in the packet
4571 to base addresses for symfile_map_offsets_to_segments. */
4572 else if (data
!= nullptr && data
->segments
.size () == 2)
4574 segments
[0] = data
->segments
[0].base
+ text_addr
;
4575 segments
[1] = data
->segments
[1].base
+ data_addr
;
4578 /* If the object file has only one segment, assume that it is text
4579 rather than data; main programs with no writable data are rare,
4580 but programs with no code are useless. Of course the code might
4581 have ended up in the data segment... to detect that we would need
4582 the permissions here. */
4583 else if (data
&& data
->segments
.size () == 1)
4585 segments
[0] = data
->segments
[0].base
+ text_addr
;
4588 /* There's no way to relocate by segment. */
4594 int ret
= symfile_map_offsets_to_segments (objf
->obfd
.get (),
4596 num_segments
, segments
);
4598 if (ret
== 0 && !do_sections
)
4599 error (_("Can not handle qOffsets TextSeg "
4600 "response with this symbol file"));
4608 offs
[SECT_OFF_TEXT (objf
)] = text_addr
;
4610 /* This is a temporary kludge to force data and bss to use the
4611 same offsets because that's what nlmconv does now. The real
4612 solution requires changes to the stub and remote.c that I
4613 don't have time to do right now. */
4615 offs
[SECT_OFF_DATA (objf
)] = data_addr
;
4616 offs
[SECT_OFF_BSS (objf
)] = data_addr
;
4619 objfile_relocate (objf
, offs
);
4622 /* Send interrupt_sequence to remote target. */
4625 remote_target::send_interrupt_sequence ()
4627 if (interrupt_sequence_mode
== interrupt_sequence_control_c
)
4628 remote_serial_write ("\x03", 1);
4629 else if (interrupt_sequence_mode
== interrupt_sequence_break
)
4630 remote_serial_send_break ();
4631 else if (interrupt_sequence_mode
== interrupt_sequence_break_g
)
4633 remote_serial_send_break ();
4634 remote_serial_write ("g", 1);
4637 internal_error (_("Invalid value for interrupt_sequence_mode: %s."),
4638 interrupt_sequence_mode
);
4641 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
4642 and extract the PTID. Returns NULL_PTID if not found. */
4645 stop_reply_extract_thread (const char *stop_reply
)
4647 if (stop_reply
[0] == 'T' && strlen (stop_reply
) > 3)
4651 /* Txx r:val ; r:val (...) */
4654 /* Look for "register" named "thread". */
4659 p1
= strchr (p
, ':');
4663 if (strncmp (p
, "thread", p1
- p
) == 0)
4664 return read_ptid (++p1
, &p
);
4666 p1
= strchr (p
, ';');
4678 /* Determine the remote side's current thread. If we have a stop
4679 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
4680 "thread" register we can extract the current thread from. If not,
4681 ask the remote which is the current thread with qC. The former
4682 method avoids a roundtrip. */
4685 remote_target::get_current_thread (const char *wait_status
)
4687 ptid_t ptid
= null_ptid
;
4689 /* Note we don't use remote_parse_stop_reply as that makes use of
4690 the target architecture, which we haven't yet fully determined at
4692 if (wait_status
!= NULL
)
4693 ptid
= stop_reply_extract_thread (wait_status
);
4694 if (ptid
== null_ptid
)
4695 ptid
= remote_current_thread (inferior_ptid
);
4700 /* Query the remote target for which is the current thread/process,
4701 add it to our tables, and update INFERIOR_PTID. The caller is
4702 responsible for setting the state such that the remote end is ready
4703 to return the current thread.
4705 This function is called after handling the '?' or 'vRun' packets,
4706 whose response is a stop reply from which we can also try
4707 extracting the thread. If the target doesn't support the explicit
4708 qC query, we infer the current thread from that stop reply, passed
4709 in in WAIT_STATUS, which may be NULL.
4711 The function returns pointer to the main thread of the inferior. */
4714 remote_target::add_current_inferior_and_thread (const char *wait_status
)
4716 bool fake_pid_p
= false;
4718 switch_to_no_thread ();
4720 /* Now, if we have thread information, update the current thread's
4722 ptid_t curr_ptid
= get_current_thread (wait_status
);
4724 if (curr_ptid
!= null_ptid
)
4726 if (!m_features
.remote_multi_process_p ())
4731 /* Without this, some commands which require an active target
4732 (such as kill) won't work. This variable serves (at least)
4733 double duty as both the pid of the target process (if it has
4734 such), and as a flag indicating that a target is active. */
4735 curr_ptid
= magic_null_ptid
;
4739 remote_add_inferior (fake_pid_p
, curr_ptid
.pid (), -1, 1);
4741 /* Add the main thread and switch to it. Don't try reading
4742 registers yet, since we haven't fetched the target description
4744 thread_info
*tp
= add_thread_silent (this, curr_ptid
);
4745 switch_to_thread_no_regs (tp
);
4750 /* Print info about a thread that was found already stopped on
4754 remote_target::print_one_stopped_thread (thread_info
*thread
)
4756 target_waitstatus ws
;
4758 /* If there is a pending waitstatus, use it. If there isn't it's because
4759 the thread's stop was reported with TARGET_WAITKIND_STOPPED / GDB_SIGNAL_0
4760 and process_initial_stop_replies decided it wasn't interesting to save
4761 and report to the core. */
4762 if (thread
->has_pending_waitstatus ())
4764 ws
= thread
->pending_waitstatus ();
4765 thread
->clear_pending_waitstatus ();
4769 ws
.set_stopped (GDB_SIGNAL_0
);
4772 switch_to_thread (thread
);
4773 thread
->set_stop_pc (get_frame_pc (get_current_frame ()));
4774 set_current_sal_from_frame (get_current_frame ());
4776 /* For "info program". */
4777 set_last_target_status (this, thread
->ptid
, ws
);
4779 if (ws
.kind () == TARGET_WAITKIND_STOPPED
)
4781 enum gdb_signal sig
= ws
.sig ();
4783 if (signal_print_state (sig
))
4784 notify_signal_received (sig
);
4787 notify_normal_stop (nullptr, 1);
4790 /* Process all initial stop replies the remote side sent in response
4791 to the ? packet. These indicate threads that were already stopped
4792 on initial connection. We mark these threads as stopped and print
4793 their current frame before giving the user the prompt. */
4796 remote_target::process_initial_stop_replies (int from_tty
)
4798 int pending_stop_replies
= stop_reply_queue_length ();
4799 struct thread_info
*selected
= NULL
;
4800 struct thread_info
*lowest_stopped
= NULL
;
4801 struct thread_info
*first
= NULL
;
4803 /* This is only used when the target is non-stop. */
4804 gdb_assert (target_is_non_stop_p ());
4806 /* Consume the initial pending events. */
4807 while (pending_stop_replies
-- > 0)
4809 ptid_t waiton_ptid
= minus_one_ptid
;
4811 struct target_waitstatus ws
;
4812 int ignore_event
= 0;
4814 event_ptid
= target_wait (waiton_ptid
, &ws
, TARGET_WNOHANG
);
4816 print_target_wait_results (waiton_ptid
, event_ptid
, ws
);
4820 case TARGET_WAITKIND_IGNORE
:
4821 case TARGET_WAITKIND_NO_RESUMED
:
4822 case TARGET_WAITKIND_SIGNALLED
:
4823 case TARGET_WAITKIND_EXITED
:
4824 /* We shouldn't see these, but if we do, just ignore. */
4825 remote_debug_printf ("event ignored");
4836 thread_info
*evthread
= this->find_thread (event_ptid
);
4838 if (ws
.kind () == TARGET_WAITKIND_STOPPED
)
4840 enum gdb_signal sig
= ws
.sig ();
4842 /* Stubs traditionally report SIGTRAP as initial signal,
4843 instead of signal 0. Suppress it. */
4844 if (sig
== GDB_SIGNAL_TRAP
)
4846 evthread
->set_stop_signal (sig
);
4847 ws
.set_stopped (sig
);
4850 if (ws
.kind () != TARGET_WAITKIND_STOPPED
4851 || ws
.sig () != GDB_SIGNAL_0
)
4852 evthread
->set_pending_waitstatus (ws
);
4854 set_executing (this, event_ptid
, false);
4855 set_running (this, event_ptid
, false);
4856 get_remote_thread_info (evthread
)->set_not_resumed ();
4859 /* "Notice" the new inferiors before anything related to
4860 registers/memory. */
4861 for (inferior
*inf
: all_non_exited_inferiors (this))
4863 inf
->needs_setup
= true;
4867 thread_info
*thread
= any_live_thread_of_inferior (inf
);
4868 notice_new_inferior (thread
, thread
->state
== THREAD_RUNNING
,
4873 /* If all-stop on top of non-stop, pause all threads. Note this
4874 records the threads' stop pc, so must be done after "noticing"
4879 /* At this point, the remote target is not async. It needs to be for
4880 the poll in stop_all_threads to consider events from it, so enable
4882 gdb_assert (!this->is_async_p ());
4883 SCOPE_EXIT
{ target_async (false); };
4884 target_async (true);
4885 stop_all_threads ("remote connect in all-stop");
4888 /* If all threads of an inferior were already stopped, we
4889 haven't setup the inferior yet. */
4890 for (inferior
*inf
: all_non_exited_inferiors (this))
4892 if (inf
->needs_setup
)
4894 thread_info
*thread
= any_live_thread_of_inferior (inf
);
4895 switch_to_thread_no_regs (thread
);
4901 /* Now go over all threads that are stopped, and print their current
4902 frame. If all-stop, then if there's a signalled thread, pick
4904 for (thread_info
*thread
: all_non_exited_threads (this))
4910 thread
->set_running (false);
4911 else if (thread
->state
!= THREAD_STOPPED
)
4914 if (selected
== nullptr && thread
->has_pending_waitstatus ())
4917 if (lowest_stopped
== NULL
4918 || thread
->inf
->num
< lowest_stopped
->inf
->num
4919 || thread
->per_inf_num
< lowest_stopped
->per_inf_num
)
4920 lowest_stopped
= thread
;
4923 print_one_stopped_thread (thread
);
4926 /* In all-stop, we only print the status of one thread, and leave
4927 others with their status pending. */
4930 thread_info
*thread
= selected
;
4932 thread
= lowest_stopped
;
4936 print_one_stopped_thread (thread
);
4940 /* Mark a remote_target as starting (by setting the starting_up flag within
4941 its remote_state) for the lifetime of this object. The reference count
4942 on the remote target is temporarily incremented, to prevent the target
4943 being deleted under our feet. */
4945 struct scoped_mark_target_starting
4947 /* Constructor, TARGET is the target to be marked as starting, its
4948 reference count will be incremented. */
4949 scoped_mark_target_starting (remote_target
*target
)
4950 : m_remote_target (remote_target_ref::new_reference (target
)),
4951 m_restore_starting_up (set_starting_up_flag (target
))
4956 /* Helper function, set the starting_up flag on TARGET and return an
4957 object which, when it goes out of scope, will restore the previous
4958 value of the starting_up flag. */
4959 static scoped_restore_tmpl
<bool>
4960 set_starting_up_flag (remote_target
*target
)
4962 remote_state
*rs
= target
->get_remote_state ();
4963 gdb_assert (!rs
->starting_up
);
4964 return make_scoped_restore (&rs
->starting_up
, true);
4967 /* A gdb::ref_ptr pointer to a remote_target. */
4968 using remote_target_ref
= gdb::ref_ptr
<remote_target
, target_ops_ref_policy
>;
4970 /* A reference to the target on which we are operating. */
4971 remote_target_ref m_remote_target
;
4973 /* An object which restores the previous value of the starting_up flag
4974 when it goes out of scope. */
4975 scoped_restore_tmpl
<bool> m_restore_starting_up
;
4978 /* Helper for remote_target::start_remote, start the remote connection and
4979 sync state. Return true if everything goes OK, otherwise, return false.
4980 This function exists so that the scoped_restore created within it will
4981 expire before we return to remote_target::start_remote. */
4984 remote_target::start_remote_1 (int from_tty
, int extended_p
)
4986 REMOTE_SCOPED_DEBUG_ENTER_EXIT
;
4988 struct remote_state
*rs
= get_remote_state ();
4990 /* Signal other parts that we're going through the initial setup,
4991 and so things may not be stable yet. E.g., we don't try to
4992 install tracepoints until we've relocated symbols. Also, a
4993 Ctrl-C before we're connected and synced up can't interrupt the
4994 target. Instead, it offers to drop the (potentially wedged)
4996 scoped_mark_target_starting
target_is_starting (this);
5000 if (interrupt_on_connect
)
5001 send_interrupt_sequence ();
5003 /* Ack any packet which the remote side has already sent. */
5004 remote_serial_write ("+", 1);
5006 /* The first packet we send to the target is the optional "supported
5007 packets" request. If the target can answer this, it will tell us
5008 which later probes to skip. */
5009 remote_query_supported ();
5011 /* Check vCont support and set the remote state's vCont_action_support
5013 remote_vcont_probe ();
5015 /* If the stub wants to get a QAllow, compose one and send it. */
5016 if (m_features
.packet_support (PACKET_QAllow
) != PACKET_DISABLE
)
5019 /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
5020 unknown 'v' packet with string "OK". "OK" gets interpreted by GDB
5021 as a reply to known packet. For packet "vFile:setfs:" it is an
5022 invalid reply and GDB would return error in
5023 remote_hostio_set_filesystem, making remote files access impossible.
5024 Disable "vFile:setfs:" in such case. Do not disable other 'v' packets as
5025 other "vFile" packets get correctly detected even on gdbserver < 7.7. */
5027 const char v_mustreplyempty
[] = "vMustReplyEmpty";
5029 putpkt (v_mustreplyempty
);
5031 if (strcmp (rs
->buf
.data (), "OK") == 0)
5033 m_features
.m_protocol_packets
[PACKET_vFile_setfs
].support
5036 else if (strcmp (rs
->buf
.data (), "") != 0)
5037 error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty
,
5041 /* Next, we possibly activate noack mode.
5043 If the QStartNoAckMode packet configuration is set to AUTO,
5044 enable noack mode if the stub reported a wish for it with
5047 If set to TRUE, then enable noack mode even if the stub didn't
5048 report it in qSupported. If the stub doesn't reply OK, the
5049 session ends with an error.
5051 If FALSE, then don't activate noack mode, regardless of what the
5052 stub claimed should be the default with qSupported. */
5054 if (m_features
.packet_support (PACKET_QStartNoAckMode
) != PACKET_DISABLE
)
5056 putpkt ("QStartNoAckMode");
5058 if (m_features
.packet_ok (rs
->buf
, PACKET_QStartNoAckMode
) == PACKET_OK
)
5064 /* Tell the remote that we are using the extended protocol. */
5069 /* Let the target know which signals it is allowed to pass down to
5071 update_signals_program_target ();
5073 /* Next, if the target can specify a description, read it. We do
5074 this before anything involving memory or registers. */
5075 target_find_description ();
5077 /* Next, now that we know something about the target, update the
5078 address spaces in the program spaces. */
5079 update_address_spaces ();
5081 /* On OSs where the list of libraries is global to all
5082 processes, we fetch them early. */
5083 if (gdbarch_has_global_solist (current_inferior ()->arch ()))
5084 solib_add (NULL
, from_tty
, auto_solib_add
);
5086 if (target_is_non_stop_p ())
5088 if (m_features
.packet_support (PACKET_QNonStop
) != PACKET_ENABLE
)
5089 error (_("Non-stop mode requested, but remote "
5090 "does not support non-stop"));
5092 putpkt ("QNonStop:1");
5095 if (strcmp (rs
->buf
.data (), "OK") != 0)
5096 error (_("Remote refused setting non-stop mode with: %s"),
5099 /* Find about threads and processes the stub is already
5100 controlling. We default to adding them in the running state.
5101 The '?' query below will then tell us about which threads are
5103 this->update_thread_list ();
5105 else if (m_features
.packet_support (PACKET_QNonStop
) == PACKET_ENABLE
)
5107 /* Don't assume that the stub can operate in all-stop mode.
5108 Request it explicitly. */
5109 putpkt ("QNonStop:0");
5112 if (strcmp (rs
->buf
.data (), "OK") != 0)
5113 error (_("Remote refused setting all-stop mode with: %s"),
5117 /* Upload TSVs regardless of whether the target is running or not. The
5118 remote stub, such as GDBserver, may have some predefined or builtin
5119 TSVs, even if the target is not running. */
5120 if (get_trace_status (current_trace_status ()) != -1)
5122 struct uploaded_tsv
*uploaded_tsvs
= NULL
;
5124 upload_trace_state_variables (&uploaded_tsvs
);
5125 merge_uploaded_trace_state_variables (&uploaded_tsvs
);
5128 /* Check whether the target is running now. */
5132 if (!target_is_non_stop_p ())
5134 char *wait_status
= NULL
;
5136 if (rs
->buf
[0] == 'W' || rs
->buf
[0] == 'X')
5139 error (_("The target is not running (try extended-remote?)"));
5144 /* Save the reply for later. */
5145 wait_status
= (char *) alloca (strlen (rs
->buf
.data ()) + 1);
5146 strcpy (wait_status
, rs
->buf
.data ());
5149 /* Fetch thread list. */
5150 target_update_thread_list ();
5152 /* Let the stub know that we want it to return the thread. */
5153 set_continue_thread (minus_one_ptid
);
5155 if (thread_count (this) == 0)
5157 /* Target has no concept of threads at all. GDB treats
5158 non-threaded target as single-threaded; add a main
5160 thread_info
*tp
= add_current_inferior_and_thread (wait_status
);
5161 get_remote_thread_info (tp
)->set_resumed ();
5165 /* We have thread information; select the thread the target
5166 says should be current. If we're reconnecting to a
5167 multi-threaded program, this will ideally be the thread
5168 that last reported an event before GDB disconnected. */
5169 ptid_t curr_thread
= get_current_thread (wait_status
);
5170 if (curr_thread
== null_ptid
)
5172 /* Odd... The target was able to list threads, but not
5173 tell us which thread was current (no "thread"
5174 register in T stop reply?). Just pick the first
5175 thread in the thread list then. */
5177 remote_debug_printf ("warning: couldn't determine remote "
5178 "current thread; picking first in list.");
5180 for (thread_info
*tp
: all_non_exited_threads (this,
5183 switch_to_thread (tp
);
5188 switch_to_thread (this->find_thread (curr_thread
));
5190 get_remote_thread_info (inferior_thread ())->set_resumed ();
5193 /* init_wait_for_inferior should be called before get_offsets in order
5194 to manage `inserted' flag in bp loc in a correct state.
5195 breakpoint_init_inferior, called from init_wait_for_inferior, set
5196 `inserted' flag to 0, while before breakpoint_re_set, called from
5197 start_remote, set `inserted' flag to 1. In the initialization of
5198 inferior, breakpoint_init_inferior should be called first, and then
5199 breakpoint_re_set can be called. If this order is broken, state of
5200 `inserted' flag is wrong, and cause some problems on breakpoint
5202 init_wait_for_inferior ();
5204 get_offsets (); /* Get text, data & bss offsets. */
5206 /* If we could not find a description using qXfer, and we know
5207 how to do it some other way, try again. This is not
5208 supported for non-stop; it could be, but it is tricky if
5209 there are no stopped threads when we connect. */
5210 if (remote_read_description_p (this)
5211 && gdbarch_target_desc (current_inferior ()->arch ()) == NULL
)
5213 target_clear_description ();
5214 target_find_description ();
5217 /* Use the previously fetched status. */
5218 gdb_assert (wait_status
!= NULL
);
5219 struct notif_event
*reply
5220 = remote_notif_parse (this, ¬if_client_stop
, wait_status
);
5221 push_stop_reply ((struct stop_reply
*) reply
);
5223 ::start_remote (from_tty
); /* Initialize gdb process mechanisms. */
5227 /* Clear WFI global state. Do this before finding about new
5228 threads and inferiors, and setting the current inferior.
5229 Otherwise we would clear the proceed status of the current
5230 inferior when we want its stop_soon state to be preserved
5231 (see notice_new_inferior). */
5232 init_wait_for_inferior ();
5234 /* In non-stop, we will either get an "OK", meaning that there
5235 are no stopped threads at this time; or, a regular stop
5236 reply. In the latter case, there may be more than one thread
5237 stopped --- we pull them all out using the vStopped
5239 if (strcmp (rs
->buf
.data (), "OK") != 0)
5241 const notif_client
*notif
= ¬if_client_stop
;
5243 /* remote_notif_get_pending_replies acks this one, and gets
5245 rs
->notif_state
->pending_event
[notif_client_stop
.id
]
5246 = remote_notif_parse (this, notif
, rs
->buf
.data ());
5247 remote_notif_get_pending_events (notif
);
5250 if (thread_count (this) == 0)
5253 error (_("The target is not running (try extended-remote?)"));
5257 /* Report all signals during attach/startup. */
5260 /* If there are already stopped threads, mark them stopped and
5261 report their stops before giving the prompt to the user. */
5262 process_initial_stop_replies (from_tty
);
5264 if (target_can_async_p ())
5265 target_async (true);
5268 /* Give the target a chance to look up symbols. */
5269 for (inferior
*inf
: all_inferiors (this))
5271 /* The inferiors that exist at this point were created from what
5272 was found already running on the remote side, so we know they
5274 gdb_assert (this->has_execution (inf
));
5276 /* No use without a symbol-file. */
5277 if (inf
->pspace
->symfile_object_file
== nullptr)
5280 /* Need to switch to a specific thread, because remote_check_symbols
5281 uses INFERIOR_PTID to set the general thread. */
5282 scoped_restore_current_thread restore_thread
;
5283 thread_info
*thread
= any_thread_of_inferior (inf
);
5284 switch_to_thread (thread
);
5285 this->remote_check_symbols ();
5288 /* Possibly the target has been engaged in a trace run started
5289 previously; find out where things are at. */
5290 if (get_trace_status (current_trace_status ()) != -1)
5292 struct uploaded_tp
*uploaded_tps
= NULL
;
5294 if (current_trace_status ()->running
)
5295 gdb_printf (_("Trace is already running on the target.\n"));
5297 upload_tracepoints (&uploaded_tps
);
5299 merge_uploaded_tracepoints (&uploaded_tps
);
5302 /* Possibly the target has been engaged in a btrace record started
5303 previously; find out where things are at. */
5304 remote_btrace_maybe_reopen ();
5309 /* Start the remote connection and sync state. */
5312 remote_target::start_remote (int from_tty
, int extended_p
)
5314 if (start_remote_1 (from_tty
, extended_p
)
5315 && breakpoints_should_be_inserted_now ())
5316 insert_breakpoints ();
5320 remote_target::connection_string ()
5322 remote_state
*rs
= get_remote_state ();
5324 if (rs
->remote_desc
->name
!= NULL
)
5325 return rs
->remote_desc
->name
;
5330 /* Open a connection to a remote debugger.
5331 NAME is the filename used for communication. */
5334 remote_target::open (const char *name
, int from_tty
)
5336 open_1 (name
, from_tty
, 0);
5339 /* Open a connection to a remote debugger using the extended
5340 remote gdb protocol. NAME is the filename used for communication. */
5343 extended_remote_target::open (const char *name
, int from_tty
)
5345 open_1 (name
, from_tty
, 1 /*extended_p */);
5349 remote_features::reset_all_packet_configs_support ()
5353 for (i
= 0; i
< PACKET_MAX
; i
++)
5354 m_protocol_packets
[i
].support
= PACKET_SUPPORT_UNKNOWN
;
5357 /* Initialize all packet configs. */
5360 init_all_packet_configs (void)
5364 for (i
= 0; i
< PACKET_MAX
; i
++)
5366 remote_protocol_packets
[i
].detect
= AUTO_BOOLEAN_AUTO
;
5367 remote_protocol_packets
[i
].support
= PACKET_SUPPORT_UNKNOWN
;
5371 /* Symbol look-up. */
5374 remote_target::remote_check_symbols ()
5379 /* It doesn't make sense to send a qSymbol packet for an inferior that
5380 doesn't have execution, because the remote side doesn't know about
5381 inferiors without execution. */
5382 gdb_assert (target_has_execution ());
5384 if (m_features
.packet_support (PACKET_qSymbol
) == PACKET_DISABLE
)
5387 /* Make sure the remote is pointing at the right process. Note
5388 there's no way to select "no process". */
5389 set_general_process ();
5391 /* Allocate a message buffer. We can't reuse the input buffer in RS,
5392 because we need both at the same time. */
5393 gdb::char_vector
msg (get_remote_packet_size ());
5394 gdb::char_vector
reply (get_remote_packet_size ());
5396 /* Invite target to request symbol lookups. */
5398 putpkt ("qSymbol::");
5400 m_features
.packet_ok (reply
, PACKET_qSymbol
);
5402 while (startswith (reply
.data (), "qSymbol:"))
5404 struct bound_minimal_symbol sym
;
5407 end
= hex2bin (tmp
, reinterpret_cast <gdb_byte
*> (msg
.data ()),
5410 sym
= lookup_minimal_symbol (msg
.data (), NULL
, NULL
);
5411 if (sym
.minsym
== NULL
)
5412 xsnprintf (msg
.data (), get_remote_packet_size (), "qSymbol::%s",
5416 int addr_size
= gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
5417 CORE_ADDR sym_addr
= sym
.value_address ();
5419 /* If this is a function address, return the start of code
5420 instead of any data function descriptor. */
5421 sym_addr
= gdbarch_convert_from_func_ptr_addr
5422 (current_inferior ()->arch (), sym_addr
,
5423 current_inferior ()->top_target ());
5425 xsnprintf (msg
.data (), get_remote_packet_size (), "qSymbol:%s:%s",
5426 phex_nz (sym_addr
, addr_size
), &reply
[8]);
5429 putpkt (msg
.data ());
5434 static struct serial
*
5435 remote_serial_open (const char *name
)
5437 static int udp_warning
= 0;
5439 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
5440 of in ser-tcp.c, because it is the remote protocol assuming that the
5441 serial connection is reliable and not the serial connection promising
5443 if (!udp_warning
&& startswith (name
, "udp:"))
5445 warning (_("The remote protocol may be unreliable over UDP.\n"
5446 "Some events may be lost, rendering further debugging "
5451 return serial_open (name
);
5454 /* Inform the target of our permission settings. The permission flags
5455 work without this, but if the target knows the settings, it can do
5456 a couple things. First, it can add its own check, to catch cases
5457 that somehow manage to get by the permissions checks in target
5458 methods. Second, if the target is wired to disallow particular
5459 settings (for instance, a system in the field that is not set up to
5460 be able to stop at a breakpoint), it can object to any unavailable
5464 remote_target::set_permissions ()
5466 struct remote_state
*rs
= get_remote_state ();
5468 xsnprintf (rs
->buf
.data (), get_remote_packet_size (), "QAllow:"
5469 "WriteReg:%x;WriteMem:%x;"
5470 "InsertBreak:%x;InsertTrace:%x;"
5471 "InsertFastTrace:%x;Stop:%x",
5472 may_write_registers
, may_write_memory
,
5473 may_insert_breakpoints
, may_insert_tracepoints
,
5474 may_insert_fast_tracepoints
, may_stop
);
5478 /* If the target didn't like the packet, warn the user. Do not try
5479 to undo the user's settings, that would just be maddening. */
5480 if (strcmp (rs
->buf
.data (), "OK") != 0)
5481 warning (_("Remote refused setting permissions with: %s"),
5485 /* This type describes each known response to the qSupported
5487 struct protocol_feature
5489 /* The name of this protocol feature. */
5492 /* The default for this protocol feature. */
5493 enum packet_support default_support
;
5495 /* The function to call when this feature is reported, or after
5496 qSupported processing if the feature is not supported.
5497 The first argument points to this structure. The second
5498 argument indicates whether the packet requested support be
5499 enabled, disabled, or probed (or the default, if this function
5500 is being called at the end of processing and this feature was
5501 not reported). The third argument may be NULL; if not NULL, it
5502 is a NUL-terminated string taken from the packet following
5503 this feature's name and an equals sign. */
5504 void (*func
) (remote_target
*remote
, const struct protocol_feature
*,
5505 enum packet_support
, const char *);
5507 /* The corresponding packet for this feature. Only used if
5508 FUNC is remote_supported_packet. */
5513 remote_supported_packet (remote_target
*remote
,
5514 const struct protocol_feature
*feature
,
5515 enum packet_support support
,
5516 const char *argument
)
5520 warning (_("Remote qSupported response supplied an unexpected value for"
5521 " \"%s\"."), feature
->name
);
5525 remote
->m_features
.m_protocol_packets
[feature
->packet
].support
= support
;
5529 remote_target::remote_packet_size (const protocol_feature
*feature
,
5530 enum packet_support support
,
5533 struct remote_state
*rs
= get_remote_state ();
5538 if (support
!= PACKET_ENABLE
)
5541 if (value
== NULL
|| *value
== '\0')
5543 warning (_("Remote target reported \"%s\" without a size."),
5549 packet_size
= strtol (value
, &value_end
, 16);
5550 if (errno
!= 0 || *value_end
!= '\0' || packet_size
< 0)
5552 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
5553 feature
->name
, value
);
5557 /* Record the new maximum packet size. */
5558 rs
->explicit_packet_size
= packet_size
;
5562 remote_packet_size (remote_target
*remote
, const protocol_feature
*feature
,
5563 enum packet_support support
, const char *value
)
5565 remote
->remote_packet_size (feature
, support
, value
);
5569 remote_target::remote_supported_thread_options (const protocol_feature
*feature
,
5570 enum packet_support support
,
5573 struct remote_state
*rs
= get_remote_state ();
5575 m_features
.m_protocol_packets
[feature
->packet
].support
= support
;
5577 if (support
!= PACKET_ENABLE
)
5580 if (value
== nullptr || *value
== '\0')
5582 warning (_("Remote target reported \"%s\" without supported options."),
5587 ULONGEST options
= 0;
5588 const char *p
= unpack_varlen_hex (value
, &options
);
5592 warning (_("Remote target reported \"%s\" with "
5593 "bad thread options: \"%s\"."),
5594 feature
->name
, value
);
5598 /* Record the set of supported options. */
5599 rs
->supported_thread_options
= (gdb_thread_option
) options
;
5603 remote_supported_thread_options (remote_target
*remote
,
5604 const protocol_feature
*feature
,
5605 enum packet_support support
,
5608 remote
->remote_supported_thread_options (feature
, support
, value
);
5611 static const struct protocol_feature remote_protocol_features
[] = {
5612 { "PacketSize", PACKET_DISABLE
, remote_packet_size
, -1 },
5613 { "qXfer:auxv:read", PACKET_DISABLE
, remote_supported_packet
,
5614 PACKET_qXfer_auxv
},
5615 { "qXfer:exec-file:read", PACKET_DISABLE
, remote_supported_packet
,
5616 PACKET_qXfer_exec_file
},
5617 { "qXfer:features:read", PACKET_DISABLE
, remote_supported_packet
,
5618 PACKET_qXfer_features
},
5619 { "qXfer:libraries:read", PACKET_DISABLE
, remote_supported_packet
,
5620 PACKET_qXfer_libraries
},
5621 { "qXfer:libraries-svr4:read", PACKET_DISABLE
, remote_supported_packet
,
5622 PACKET_qXfer_libraries_svr4
},
5623 { "augmented-libraries-svr4-read", PACKET_DISABLE
,
5624 remote_supported_packet
, PACKET_augmented_libraries_svr4_read_feature
},
5625 { "qXfer:memory-map:read", PACKET_DISABLE
, remote_supported_packet
,
5626 PACKET_qXfer_memory_map
},
5627 { "qXfer:osdata:read", PACKET_DISABLE
, remote_supported_packet
,
5628 PACKET_qXfer_osdata
},
5629 { "qXfer:threads:read", PACKET_DISABLE
, remote_supported_packet
,
5630 PACKET_qXfer_threads
},
5631 { "qXfer:traceframe-info:read", PACKET_DISABLE
, remote_supported_packet
,
5632 PACKET_qXfer_traceframe_info
},
5633 { "QPassSignals", PACKET_DISABLE
, remote_supported_packet
,
5634 PACKET_QPassSignals
},
5635 { "QCatchSyscalls", PACKET_DISABLE
, remote_supported_packet
,
5636 PACKET_QCatchSyscalls
},
5637 { "QProgramSignals", PACKET_DISABLE
, remote_supported_packet
,
5638 PACKET_QProgramSignals
},
5639 { "QSetWorkingDir", PACKET_DISABLE
, remote_supported_packet
,
5640 PACKET_QSetWorkingDir
},
5641 { "QStartupWithShell", PACKET_DISABLE
, remote_supported_packet
,
5642 PACKET_QStartupWithShell
},
5643 { "QEnvironmentHexEncoded", PACKET_DISABLE
, remote_supported_packet
,
5644 PACKET_QEnvironmentHexEncoded
},
5645 { "QEnvironmentReset", PACKET_DISABLE
, remote_supported_packet
,
5646 PACKET_QEnvironmentReset
},
5647 { "QEnvironmentUnset", PACKET_DISABLE
, remote_supported_packet
,
5648 PACKET_QEnvironmentUnset
},
5649 { "QStartNoAckMode", PACKET_DISABLE
, remote_supported_packet
,
5650 PACKET_QStartNoAckMode
},
5651 { "multiprocess", PACKET_DISABLE
, remote_supported_packet
,
5652 PACKET_multiprocess_feature
},
5653 { "QNonStop", PACKET_DISABLE
, remote_supported_packet
, PACKET_QNonStop
},
5654 { "qXfer:siginfo:read", PACKET_DISABLE
, remote_supported_packet
,
5655 PACKET_qXfer_siginfo_read
},
5656 { "qXfer:siginfo:write", PACKET_DISABLE
, remote_supported_packet
,
5657 PACKET_qXfer_siginfo_write
},
5658 { "ConditionalTracepoints", PACKET_DISABLE
, remote_supported_packet
,
5659 PACKET_ConditionalTracepoints
},
5660 { "ConditionalBreakpoints", PACKET_DISABLE
, remote_supported_packet
,
5661 PACKET_ConditionalBreakpoints
},
5662 { "BreakpointCommands", PACKET_DISABLE
, remote_supported_packet
,
5663 PACKET_BreakpointCommands
},
5664 { "FastTracepoints", PACKET_DISABLE
, remote_supported_packet
,
5665 PACKET_FastTracepoints
},
5666 { "StaticTracepoints", PACKET_DISABLE
, remote_supported_packet
,
5667 PACKET_StaticTracepoints
},
5668 {"InstallInTrace", PACKET_DISABLE
, remote_supported_packet
,
5669 PACKET_InstallInTrace
},
5670 { "DisconnectedTracing", PACKET_DISABLE
, remote_supported_packet
,
5671 PACKET_DisconnectedTracing_feature
},
5672 { "ReverseContinue", PACKET_DISABLE
, remote_supported_packet
,
5674 { "ReverseStep", PACKET_DISABLE
, remote_supported_packet
,
5676 { "TracepointSource", PACKET_DISABLE
, remote_supported_packet
,
5677 PACKET_TracepointSource
},
5678 { "QAllow", PACKET_DISABLE
, remote_supported_packet
,
5680 { "EnableDisableTracepoints", PACKET_DISABLE
, remote_supported_packet
,
5681 PACKET_EnableDisableTracepoints_feature
},
5682 { "qXfer:fdpic:read", PACKET_DISABLE
, remote_supported_packet
,
5683 PACKET_qXfer_fdpic
},
5684 { "qXfer:uib:read", PACKET_DISABLE
, remote_supported_packet
,
5686 { "QDisableRandomization", PACKET_DISABLE
, remote_supported_packet
,
5687 PACKET_QDisableRandomization
},
5688 { "QAgent", PACKET_DISABLE
, remote_supported_packet
, PACKET_QAgent
},
5689 { "QTBuffer:size", PACKET_DISABLE
,
5690 remote_supported_packet
, PACKET_QTBuffer_size
},
5691 { "tracenz", PACKET_DISABLE
, remote_supported_packet
, PACKET_tracenz_feature
},
5692 { "Qbtrace:off", PACKET_DISABLE
, remote_supported_packet
, PACKET_Qbtrace_off
},
5693 { "Qbtrace:bts", PACKET_DISABLE
, remote_supported_packet
, PACKET_Qbtrace_bts
},
5694 { "Qbtrace:pt", PACKET_DISABLE
, remote_supported_packet
, PACKET_Qbtrace_pt
},
5695 { "qXfer:btrace:read", PACKET_DISABLE
, remote_supported_packet
,
5696 PACKET_qXfer_btrace
},
5697 { "qXfer:btrace-conf:read", PACKET_DISABLE
, remote_supported_packet
,
5698 PACKET_qXfer_btrace_conf
},
5699 { "Qbtrace-conf:bts:size", PACKET_DISABLE
, remote_supported_packet
,
5700 PACKET_Qbtrace_conf_bts_size
},
5701 { "swbreak", PACKET_DISABLE
, remote_supported_packet
, PACKET_swbreak_feature
},
5702 { "hwbreak", PACKET_DISABLE
, remote_supported_packet
, PACKET_hwbreak_feature
},
5703 { "fork-events", PACKET_DISABLE
, remote_supported_packet
,
5704 PACKET_fork_event_feature
},
5705 { "vfork-events", PACKET_DISABLE
, remote_supported_packet
,
5706 PACKET_vfork_event_feature
},
5707 { "exec-events", PACKET_DISABLE
, remote_supported_packet
,
5708 PACKET_exec_event_feature
},
5709 { "Qbtrace-conf:pt:size", PACKET_DISABLE
, remote_supported_packet
,
5710 PACKET_Qbtrace_conf_pt_size
},
5711 { "vContSupported", PACKET_DISABLE
, remote_supported_packet
, PACKET_vContSupported
},
5712 { "QThreadEvents", PACKET_DISABLE
, remote_supported_packet
, PACKET_QThreadEvents
},
5713 { "QThreadOptions", PACKET_DISABLE
, remote_supported_thread_options
,
5714 PACKET_QThreadOptions
},
5715 { "no-resumed", PACKET_DISABLE
, remote_supported_packet
, PACKET_no_resumed
},
5716 { "memory-tagging", PACKET_DISABLE
, remote_supported_packet
,
5717 PACKET_memory_tagging_feature
},
5720 static char *remote_support_xml
;
5722 /* Register string appended to "xmlRegisters=" in qSupported query. */
5725 register_remote_support_xml (const char *xml
)
5727 #if defined(HAVE_LIBEXPAT)
5728 if (remote_support_xml
== NULL
)
5729 remote_support_xml
= concat ("xmlRegisters=", xml
, (char *) NULL
);
5732 char *copy
= xstrdup (remote_support_xml
+ 13);
5734 char *p
= strtok_r (copy
, ",", &saveptr
);
5738 if (strcmp (p
, xml
) == 0)
5745 while ((p
= strtok_r (NULL
, ",", &saveptr
)) != NULL
);
5748 remote_support_xml
= reconcat (remote_support_xml
,
5749 remote_support_xml
, ",", xml
,
5756 remote_query_supported_append (std::string
*msg
, const char *append
)
5760 msg
->append (append
);
5764 remote_target::remote_query_supported ()
5766 struct remote_state
*rs
= get_remote_state ();
5769 unsigned char seen
[ARRAY_SIZE (remote_protocol_features
)];
5771 /* The packet support flags are handled differently for this packet
5772 than for most others. We treat an error, a disabled packet, and
5773 an empty response identically: any features which must be reported
5774 to be used will be automatically disabled. An empty buffer
5775 accomplishes this, since that is also the representation for a list
5776 containing no features. */
5779 if (m_features
.packet_support (PACKET_qSupported
) != PACKET_DISABLE
)
5783 if (m_features
.packet_set_cmd_state (PACKET_multiprocess_feature
)
5784 != AUTO_BOOLEAN_FALSE
)
5785 remote_query_supported_append (&q
, "multiprocess+");
5787 if (m_features
.packet_set_cmd_state (PACKET_swbreak_feature
)
5788 != AUTO_BOOLEAN_FALSE
)
5789 remote_query_supported_append (&q
, "swbreak+");
5791 if (m_features
.packet_set_cmd_state (PACKET_hwbreak_feature
)
5792 != AUTO_BOOLEAN_FALSE
)
5793 remote_query_supported_append (&q
, "hwbreak+");
5795 remote_query_supported_append (&q
, "qRelocInsn+");
5797 if (m_features
.packet_set_cmd_state (PACKET_fork_event_feature
)
5798 != AUTO_BOOLEAN_FALSE
)
5799 remote_query_supported_append (&q
, "fork-events+");
5801 if (m_features
.packet_set_cmd_state (PACKET_vfork_event_feature
)
5802 != AUTO_BOOLEAN_FALSE
)
5803 remote_query_supported_append (&q
, "vfork-events+");
5805 if (m_features
.packet_set_cmd_state (PACKET_exec_event_feature
)
5806 != AUTO_BOOLEAN_FALSE
)
5807 remote_query_supported_append (&q
, "exec-events+");
5809 if (m_features
.packet_set_cmd_state (PACKET_vContSupported
)
5810 != AUTO_BOOLEAN_FALSE
)
5811 remote_query_supported_append (&q
, "vContSupported+");
5813 if (m_features
.packet_set_cmd_state (PACKET_QThreadEvents
)
5814 != AUTO_BOOLEAN_FALSE
)
5815 remote_query_supported_append (&q
, "QThreadEvents+");
5817 if (m_features
.packet_set_cmd_state (PACKET_QThreadOptions
)
5818 != AUTO_BOOLEAN_FALSE
)
5819 remote_query_supported_append (&q
, "QThreadOptions+");
5821 if (m_features
.packet_set_cmd_state (PACKET_no_resumed
)
5822 != AUTO_BOOLEAN_FALSE
)
5823 remote_query_supported_append (&q
, "no-resumed+");
5825 if (m_features
.packet_set_cmd_state (PACKET_memory_tagging_feature
)
5826 != AUTO_BOOLEAN_FALSE
)
5827 remote_query_supported_append (&q
, "memory-tagging+");
5829 /* Keep this one last to work around a gdbserver <= 7.10 bug in
5830 the qSupported:xmlRegisters=i386 handling. */
5831 if (remote_support_xml
!= NULL
5832 && (m_features
.packet_support (PACKET_qXfer_features
)
5834 remote_query_supported_append (&q
, remote_support_xml
);
5836 q
= "qSupported:" + q
;
5837 putpkt (q
.c_str ());
5841 /* If an error occurred, warn, but do not return - just reset the
5842 buffer to empty and go on to disable features. */
5843 if (m_features
.packet_ok (rs
->buf
, PACKET_qSupported
) == PACKET_ERROR
)
5845 warning (_("Remote failure reply: %s"), rs
->buf
.data ());
5850 memset (seen
, 0, sizeof (seen
));
5852 next
= rs
->buf
.data ();
5855 enum packet_support is_supported
;
5856 char *p
, *end
, *name_end
, *value
;
5858 /* First separate out this item from the rest of the packet. If
5859 there's another item after this, we overwrite the separator
5860 (terminated strings are much easier to work with). */
5862 end
= strchr (p
, ';');
5865 end
= p
+ strlen (p
);
5875 warning (_("empty item in \"qSupported\" response"));
5880 name_end
= strchr (p
, '=');
5883 /* This is a name=value entry. */
5884 is_supported
= PACKET_ENABLE
;
5885 value
= name_end
+ 1;
5894 is_supported
= PACKET_ENABLE
;
5898 is_supported
= PACKET_DISABLE
;
5902 is_supported
= PACKET_SUPPORT_UNKNOWN
;
5906 warning (_("unrecognized item \"%s\" "
5907 "in \"qSupported\" response"), p
);
5913 for (i
= 0; i
< ARRAY_SIZE (remote_protocol_features
); i
++)
5914 if (strcmp (remote_protocol_features
[i
].name
, p
) == 0)
5916 const struct protocol_feature
*feature
;
5919 feature
= &remote_protocol_features
[i
];
5920 feature
->func (this, feature
, is_supported
, value
);
5925 /* If we increased the packet size, make sure to increase the global
5926 buffer size also. We delay this until after parsing the entire
5927 qSupported packet, because this is the same buffer we were
5929 if (rs
->buf
.size () < rs
->explicit_packet_size
)
5930 rs
->buf
.resize (rs
->explicit_packet_size
);
5932 /* Handle the defaults for unmentioned features. */
5933 for (i
= 0; i
< ARRAY_SIZE (remote_protocol_features
); i
++)
5936 const struct protocol_feature
*feature
;
5938 feature
= &remote_protocol_features
[i
];
5939 feature
->func (this, feature
, feature
->default_support
, NULL
);
5943 /* Serial QUIT handler for the remote serial descriptor.
5945 Defers handling a Ctrl-C until we're done with the current
5946 command/response packet sequence, unless:
5948 - We're setting up the connection. Don't send a remote interrupt
5949 request, as we're not fully synced yet. Quit immediately
5952 - The target has been resumed in the foreground
5953 (target_terminal::is_ours is false) with a synchronous resume
5954 packet, and we're blocked waiting for the stop reply, thus a
5955 Ctrl-C should be immediately sent to the target.
5957 - We get a second Ctrl-C while still within the same serial read or
5958 write. In that case the serial is seemingly wedged --- offer to
5961 - We see a second Ctrl-C without target response, after having
5962 previously interrupted the target. In that case the target/stub
5963 is probably wedged --- offer to quit/disconnect.
5967 remote_target::remote_serial_quit_handler ()
5969 struct remote_state
*rs
= get_remote_state ();
5971 if (check_quit_flag ())
5973 /* If we're starting up, we're not fully synced yet. Quit
5975 if (rs
->starting_up
)
5977 else if (rs
->got_ctrlc_during_io
)
5979 if (query (_("The target is not responding to GDB commands.\n"
5980 "Stop debugging it? ")))
5981 remote_unpush_and_throw (this);
5983 /* If ^C has already been sent once, offer to disconnect. */
5984 else if (!target_terminal::is_ours () && rs
->ctrlc_pending_p
)
5986 /* All-stop protocol, and blocked waiting for stop reply. Send
5987 an interrupt request. */
5988 else if (!target_terminal::is_ours () && rs
->waiting_for_stop_reply
)
5989 target_interrupt ();
5991 rs
->got_ctrlc_during_io
= 1;
5995 /* The remote_target that is current while the quit handler is
5996 overridden with remote_serial_quit_handler. */
5997 static remote_target
*curr_quit_handler_target
;
6000 remote_serial_quit_handler ()
6002 curr_quit_handler_target
->remote_serial_quit_handler ();
6005 /* Remove the remote target from the target stack of each inferior
6006 that is using it. Upper targets depend on it so remove them
6010 remote_unpush_target (remote_target
*target
)
6012 /* We have to unpush the target from all inferiors, even those that
6014 scoped_restore_current_inferior restore_current_inferior
;
6016 for (inferior
*inf
: all_inferiors (target
))
6018 switch_to_inferior_no_thread (inf
);
6019 inf
->pop_all_targets_at_and_above (process_stratum
);
6020 generic_mourn_inferior ();
6023 /* Don't rely on target_close doing this when the target is popped
6024 from the last remote inferior above, because something may be
6025 holding a reference to the target higher up on the stack, meaning
6026 target_close won't be called yet. We lost the connection to the
6027 target, so clear these now, otherwise we may later throw
6028 TARGET_CLOSE_ERROR while trying to tell the remote target to
6030 fileio_handles_invalidate_target (target
);
6034 remote_unpush_and_throw (remote_target
*target
)
6036 remote_unpush_target (target
);
6037 throw_error (TARGET_CLOSE_ERROR
, _("Disconnected from target."));
6041 remote_target::open_1 (const char *name
, int from_tty
, int extended_p
)
6043 remote_target
*curr_remote
= get_current_remote_target ();
6046 error (_("To open a remote debug connection, you need to specify what\n"
6047 "serial device is attached to the remote system\n"
6048 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
6050 /* If we're connected to a running target, target_preopen will kill it.
6051 Ask this question first, before target_preopen has a chance to kill
6053 if (curr_remote
!= NULL
&& !target_has_execution ())
6056 && !query (_("Already connected to a remote target. Disconnect? ")))
6057 error (_("Still connected."));
6060 /* Here the possibly existing remote target gets unpushed. */
6061 target_preopen (from_tty
);
6063 remote_fileio_reset ();
6064 reopen_exec_file ();
6065 reread_symbols (from_tty
);
6067 remote_target
*remote
6068 = (extended_p
? new extended_remote_target () : new remote_target ());
6069 target_ops_up
target_holder (remote
);
6071 remote_state
*rs
= remote
->get_remote_state ();
6073 /* See FIXME above. */
6074 if (!target_async_permitted
)
6075 rs
->wait_forever_enabled_p
= true;
6077 rs
->remote_desc
= remote_serial_open (name
);
6079 if (baud_rate
!= -1)
6083 serial_setbaudrate (rs
->remote_desc
, baud_rate
);
6085 catch (const gdb_exception_error
&)
6087 /* The requested speed could not be set. Error out to
6088 top level after closing remote_desc. Take care to
6089 set remote_desc to NULL to avoid closing remote_desc
6091 serial_close (rs
->remote_desc
);
6092 rs
->remote_desc
= NULL
;
6097 serial_setparity (rs
->remote_desc
, serial_parity
);
6098 serial_raw (rs
->remote_desc
);
6100 /* If there is something sitting in the buffer we might take it as a
6101 response to a command, which would be bad. */
6102 serial_flush_input (rs
->remote_desc
);
6106 gdb_puts ("Remote debugging using ");
6111 /* Switch to using the remote target now. */
6112 current_inferior ()->push_target (std::move (target_holder
));
6114 /* Register extra event sources in the event loop. */
6115 rs
->create_async_event_handler ();
6117 rs
->notif_state
= remote_notif_state_allocate (remote
);
6119 /* Reset the target state; these things will be queried either by
6120 remote_query_supported or as they are needed. */
6121 remote
->m_features
.reset_all_packet_configs_support ();
6122 rs
->explicit_packet_size
= 0;
6124 rs
->extended
= extended_p
;
6125 rs
->waiting_for_stop_reply
= 0;
6126 rs
->ctrlc_pending_p
= 0;
6127 rs
->got_ctrlc_during_io
= 0;
6129 rs
->general_thread
= not_sent_ptid
;
6130 rs
->continue_thread
= not_sent_ptid
;
6131 rs
->remote_traceframe_number
= -1;
6133 rs
->last_resume_exec_dir
= EXEC_FORWARD
;
6135 /* Probe for ability to use "ThreadInfo" query, as required. */
6136 rs
->use_threadinfo_query
= 1;
6137 rs
->use_threadextra_query
= 1;
6139 rs
->readahead_cache
.invalidate ();
6141 if (target_async_permitted
)
6143 /* FIXME: cagney/1999-09-23: During the initial connection it is
6144 assumed that the target is already ready and able to respond to
6145 requests. Unfortunately remote_start_remote() eventually calls
6146 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
6147 around this. Eventually a mechanism that allows
6148 wait_for_inferior() to expect/get timeouts will be
6150 rs
->wait_forever_enabled_p
= false;
6153 /* First delete any symbols previously loaded from shared libraries. */
6154 no_shared_libraries (NULL
, 0);
6156 /* Start the remote connection. If error() or QUIT, discard this
6157 target (we'd otherwise be in an inconsistent state) and then
6158 propogate the error on up the exception chain. This ensures that
6159 the caller doesn't stumble along blindly assuming that the
6160 function succeeded. The CLI doesn't have this problem but other
6161 UI's, such as MI do.
6163 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
6164 this function should return an error indication letting the
6165 caller restore the previous state. Unfortunately the command
6166 ``target remote'' is directly wired to this function making that
6167 impossible. On a positive note, the CLI side of this problem has
6168 been fixed - the function set_cmd_context() makes it possible for
6169 all the ``target ....'' commands to share a common callback
6170 function. See cli-dump.c. */
6175 remote
->start_remote (from_tty
, extended_p
);
6177 catch (const gdb_exception
&ex
)
6179 /* Pop the partially set up target - unless something else did
6180 already before throwing the exception. */
6181 if (ex
.error
!= TARGET_CLOSE_ERROR
)
6182 remote_unpush_target (remote
);
6187 remote_btrace_reset (rs
);
6189 if (target_async_permitted
)
6190 rs
->wait_forever_enabled_p
= true;
6193 /* Determine if WS represents a fork status. */
6196 is_fork_status (target_waitkind kind
)
6198 return (kind
== TARGET_WAITKIND_FORKED
6199 || kind
== TARGET_WAITKIND_VFORKED
);
6202 /* Return a reference to the field where a pending child status, if
6203 there's one, is recorded. If there's no child event pending, the
6204 returned waitstatus has TARGET_WAITKIND_IGNORE kind. */
6206 static const target_waitstatus
&
6207 thread_pending_status (struct thread_info
*thread
)
6209 return (thread
->has_pending_waitstatus ()
6210 ? thread
->pending_waitstatus ()
6211 : thread
->pending_follow
);
6214 /* Return THREAD's pending status if it is a pending fork/vfork (but
6215 not clone) parent, else return nullptr. */
6217 static const target_waitstatus
*
6218 thread_pending_fork_status (struct thread_info
*thread
)
6220 const target_waitstatus
&ws
= thread_pending_status (thread
);
6222 if (!is_fork_status (ws
.kind ()))
6228 /* Return THREAD's pending status if is is a pending fork/vfork/clone
6229 event, else return nullptr. */
6231 static const target_waitstatus
*
6232 thread_pending_child_status (thread_info
*thread
)
6234 const target_waitstatus
&ws
= thread_pending_status (thread
);
6236 if (!is_new_child_status (ws
.kind ()))
6242 /* Detach the specified process. */
6245 remote_target::remote_detach_pid (int pid
)
6247 struct remote_state
*rs
= get_remote_state ();
6249 /* This should not be necessary, but the handling for D;PID in
6250 GDBserver versions prior to 8.2 incorrectly assumes that the
6251 selected process points to the same process we're detaching,
6252 leading to misbehavior (and possibly GDBserver crashing) when it
6253 does not. Since it's easy and cheap, work around it by forcing
6254 GDBserver to select GDB's current process. */
6255 set_general_process ();
6257 if (m_features
.remote_multi_process_p ())
6258 xsnprintf (rs
->buf
.data (), get_remote_packet_size (), "D;%x", pid
);
6260 strcpy (rs
->buf
.data (), "D");
6265 if (rs
->buf
[0] == 'O' && rs
->buf
[1] == 'K')
6267 else if (rs
->buf
[0] == '\0')
6268 error (_("Remote doesn't know how to detach"));
6271 /* It is possible that we have an unprocessed exit event for this
6272 pid. If this is the case then we can ignore the failure to detach
6273 and just pretend that the detach worked, as far as the user is
6274 concerned, the process exited immediately after the detach. */
6275 bool process_has_already_exited
= false;
6276 remote_notif_get_pending_events (¬if_client_stop
);
6277 for (stop_reply_up
&reply
: rs
->stop_reply_queue
)
6279 if (reply
->ptid
.pid () != pid
)
6282 enum target_waitkind kind
= reply
->ws
.kind ();
6283 if (kind
== TARGET_WAITKIND_EXITED
6284 || kind
== TARGET_WAITKIND_SIGNALLED
)
6286 process_has_already_exited
= true;
6288 ("detach failed, but process already exited");
6293 if (!process_has_already_exited
)
6294 error (_("can't detach process: %s"), (char *) rs
->buf
.data ());
6298 /* This detaches a program to which we previously attached, using
6299 inferior_ptid to identify the process. After this is done, GDB
6300 can be used to debug some other program. We better not have left
6301 any breakpoints in the target program or it'll die when it hits
6305 remote_target::remote_detach_1 (inferior
*inf
, int from_tty
)
6307 int pid
= inferior_ptid
.pid ();
6308 struct remote_state
*rs
= get_remote_state ();
6311 if (!target_has_execution ())
6312 error (_("No process to detach from."));
6314 target_announce_detach (from_tty
);
6316 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
6318 /* If we're in breakpoints-always-inserted mode, or the inferior
6319 is running, we have to remove breakpoints before detaching.
6320 We don't do this in common code instead because not all
6321 targets support removing breakpoints while the target is
6322 running. The remote target / gdbserver does, though. */
6323 remove_breakpoints_inf (current_inferior ());
6326 /* Tell the remote target to detach. */
6327 remote_detach_pid (pid
);
6329 /* Exit only if this is the only active inferior. */
6330 if (from_tty
&& !rs
->extended
&& number_of_live_inferiors (this) == 1)
6331 gdb_puts (_("Ending remote debugging.\n"));
6333 /* See if any thread of the inferior we are detaching has a pending fork
6334 status. In that case, we must detach from the child resulting from
6336 for (thread_info
*thread
: inf
->non_exited_threads ())
6338 const target_waitstatus
*ws
= thread_pending_fork_status (thread
);
6343 remote_detach_pid (ws
->child_ptid ().pid ());
6346 /* Check also for any pending fork events in the stop reply queue. */
6347 remote_notif_get_pending_events (¬if_client_stop
);
6348 for (stop_reply_up
&reply
: rs
->stop_reply_queue
)
6350 if (reply
->ptid
.pid () != pid
)
6353 if (!is_fork_status (reply
->ws
.kind ()))
6356 remote_detach_pid (reply
->ws
.child_ptid ().pid ());
6359 thread_info
*tp
= this->find_thread (inferior_ptid
);
6361 /* Check to see if we are detaching a fork parent. Note that if we
6362 are detaching a fork child, tp == NULL. */
6363 is_fork_parent
= (tp
!= NULL
6364 && tp
->pending_follow
.kind () == TARGET_WAITKIND_FORKED
);
6366 /* If doing detach-on-fork, we don't mourn, because that will delete
6367 breakpoints that should be available for the followed inferior. */
6368 if (!is_fork_parent
)
6370 /* Save the pid as a string before mourning, since that will
6371 unpush the remote target, and we need the string after. */
6372 std::string infpid
= target_pid_to_str (ptid_t (pid
));
6374 target_mourn_inferior (inferior_ptid
);
6375 if (print_inferior_events
)
6376 gdb_printf (_("[Inferior %d (%s) detached]\n"),
6377 inf
->num
, infpid
.c_str ());
6381 switch_to_no_thread ();
6382 detach_inferior (current_inferior ());
6387 remote_target::detach (inferior
*inf
, int from_tty
)
6389 remote_detach_1 (inf
, from_tty
);
6393 extended_remote_target::detach (inferior
*inf
, int from_tty
)
6395 remote_detach_1 (inf
, from_tty
);
6398 /* Target follow-fork function for remote targets. On entry, and
6399 at return, the current inferior is the fork parent.
6401 Note that although this is currently only used for extended-remote,
6402 it is named remote_follow_fork in anticipation of using it for the
6403 remote target as well. */
6406 remote_target::follow_fork (inferior
*child_inf
, ptid_t child_ptid
,
6407 target_waitkind fork_kind
, bool follow_child
,
6410 process_stratum_target::follow_fork (child_inf
, child_ptid
,
6411 fork_kind
, follow_child
, detach_fork
);
6413 if ((fork_kind
== TARGET_WAITKIND_FORKED
6414 && m_features
.remote_fork_event_p ())
6415 || (fork_kind
== TARGET_WAITKIND_VFORKED
6416 && m_features
.remote_vfork_event_p ()))
6418 /* When following the parent and detaching the child, we detach
6419 the child here. For the case of following the child and
6420 detaching the parent, the detach is done in the target-
6421 independent follow fork code in infrun.c. We can't use
6422 target_detach when detaching an unfollowed child because
6423 the client side doesn't know anything about the child. */
6424 if (detach_fork
&& !follow_child
)
6426 /* Detach the fork child. */
6427 remote_detach_pid (child_ptid
.pid ());
6433 remote_target::follow_clone (ptid_t child_ptid
)
6435 remote_add_thread (child_ptid
, false, false, false);
6438 /* Target follow-exec function for remote targets. Save EXECD_PATHNAME
6439 in the program space of the new inferior. */
6442 remote_target::follow_exec (inferior
*follow_inf
, ptid_t ptid
,
6443 const char *execd_pathname
)
6445 process_stratum_target::follow_exec (follow_inf
, ptid
, execd_pathname
);
6447 /* We know that this is a target file name, so if it has the "target:"
6448 prefix we strip it off before saving it in the program space. */
6449 if (is_target_filename (execd_pathname
))
6450 execd_pathname
+= strlen (TARGET_SYSROOT_PREFIX
);
6452 set_pspace_remote_exec_file (follow_inf
->pspace
, execd_pathname
);
6455 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
6458 remote_target::disconnect (const char *args
, int from_tty
)
6461 error (_("Argument given to \"disconnect\" when remotely debugging."));
6463 /* Make sure we unpush even the extended remote targets. Calling
6464 target_mourn_inferior won't unpush, and
6465 remote_target::mourn_inferior won't unpush if there is more than
6466 one inferior left. */
6467 remote_unpush_target (this);
6470 gdb_puts ("Ending remote debugging.\n");
6473 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
6474 be chatty about it. */
6477 extended_remote_target::attach (const char *args
, int from_tty
)
6479 struct remote_state
*rs
= get_remote_state ();
6481 char *wait_status
= NULL
;
6483 pid
= parse_pid_to_attach (args
);
6485 /* Remote PID can be freely equal to getpid, do not check it here the same
6486 way as in other targets. */
6488 if (m_features
.packet_support (PACKET_vAttach
) == PACKET_DISABLE
)
6489 error (_("This target does not support attaching to a process"));
6491 target_announce_attach (from_tty
, pid
);
6493 xsnprintf (rs
->buf
.data (), get_remote_packet_size (), "vAttach;%x", pid
);
6497 switch (m_features
.packet_ok (rs
->buf
, PACKET_vAttach
))
6500 if (!target_is_non_stop_p ())
6502 /* Save the reply for later. */
6503 wait_status
= (char *) alloca (strlen (rs
->buf
.data ()) + 1);
6504 strcpy (wait_status
, rs
->buf
.data ());
6506 else if (strcmp (rs
->buf
.data (), "OK") != 0)
6507 error (_("Attaching to %s failed with: %s"),
6508 target_pid_to_str (ptid_t (pid
)).c_str (),
6511 case PACKET_UNKNOWN
:
6512 error (_("This target does not support attaching to a process"));
6514 error (_("Attaching to %s failed"),
6515 target_pid_to_str (ptid_t (pid
)).c_str ());
6518 switch_to_inferior_no_thread (remote_add_inferior (false, pid
, 1, 0));
6520 inferior_ptid
= ptid_t (pid
);
6522 if (target_is_non_stop_p ())
6524 /* Get list of threads. */
6525 update_thread_list ();
6527 thread_info
*thread
= first_thread_of_inferior (current_inferior ());
6528 if (thread
!= nullptr)
6529 switch_to_thread (thread
);
6531 /* Invalidate our notion of the remote current thread. */
6532 record_currthread (rs
, minus_one_ptid
);
6536 /* Now, if we have thread information, update the main thread's
6538 ptid_t curr_ptid
= remote_current_thread (ptid_t (pid
));
6540 /* Add the main thread to the thread list. We add the thread
6541 silently in this case (the final true parameter). */
6542 thread_info
*thr
= remote_add_thread (curr_ptid
, true, true, true);
6544 switch_to_thread (thr
);
6547 /* Next, if the target can specify a description, read it. We do
6548 this before anything involving memory or registers. */
6549 target_find_description ();
6551 if (!target_is_non_stop_p ())
6553 /* Use the previously fetched status. */
6554 gdb_assert (wait_status
!= NULL
);
6556 struct notif_event
*reply
6557 = remote_notif_parse (this, ¬if_client_stop
, wait_status
);
6559 push_stop_reply ((struct stop_reply
*) reply
);
6563 gdb_assert (wait_status
== NULL
);
6565 gdb_assert (target_can_async_p ());
6569 /* Implementation of the to_post_attach method. */
6572 extended_remote_target::post_attach (int pid
)
6574 /* Get text, data & bss offsets. */
6577 /* In certain cases GDB might not have had the chance to start
6578 symbol lookup up until now. This could happen if the debugged
6579 binary is not using shared libraries, the vsyscall page is not
6580 present (on Linux) and the binary itself hadn't changed since the
6581 debugging process was started. */
6582 if (current_program_space
->symfile_object_file
!= NULL
)
6583 remote_check_symbols();
6587 /* Check for the availability of vCont. This function should also check
6591 remote_target::remote_vcont_probe ()
6593 remote_state
*rs
= get_remote_state ();
6596 strcpy (rs
->buf
.data (), "vCont?");
6599 buf
= rs
->buf
.data ();
6601 /* Make sure that the features we assume are supported. */
6602 if (startswith (buf
, "vCont"))
6605 int support_c
, support_C
;
6607 rs
->supports_vCont
.s
= 0;
6608 rs
->supports_vCont
.S
= 0;
6611 rs
->supports_vCont
.t
= 0;
6612 rs
->supports_vCont
.r
= 0;
6613 while (p
&& *p
== ';')
6616 if (*p
== 's' && (*(p
+ 1) == ';' || *(p
+ 1) == 0))
6617 rs
->supports_vCont
.s
= 1;
6618 else if (*p
== 'S' && (*(p
+ 1) == ';' || *(p
+ 1) == 0))
6619 rs
->supports_vCont
.S
= 1;
6620 else if (*p
== 'c' && (*(p
+ 1) == ';' || *(p
+ 1) == 0))
6622 else if (*p
== 'C' && (*(p
+ 1) == ';' || *(p
+ 1) == 0))
6624 else if (*p
== 't' && (*(p
+ 1) == ';' || *(p
+ 1) == 0))
6625 rs
->supports_vCont
.t
= 1;
6626 else if (*p
== 'r' && (*(p
+ 1) == ';' || *(p
+ 1) == 0))
6627 rs
->supports_vCont
.r
= 1;
6629 p
= strchr (p
, ';');
6632 /* If c, and C are not all supported, we can't use vCont. Clearing
6633 BUF will make packet_ok disable the packet. */
6634 if (!support_c
|| !support_C
)
6638 m_features
.packet_ok (rs
->buf
, PACKET_vCont
);
6641 /* Helper function for building "vCont" resumptions. Write a
6642 resumption to P. ENDP points to one-passed-the-end of the buffer
6643 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
6644 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
6645 resumed thread should be single-stepped and/or signalled. If PTID
6646 equals minus_one_ptid, then all threads are resumed; if PTID
6647 represents a process, then all threads of the process are
6651 remote_target::append_resumption (char *p
, char *endp
,
6652 ptid_t ptid
, int step
, gdb_signal siggnal
)
6654 struct remote_state
*rs
= get_remote_state ();
6656 if (step
&& siggnal
!= GDB_SIGNAL_0
)
6657 p
+= xsnprintf (p
, endp
- p
, ";S%02x", siggnal
);
6659 /* GDB is willing to range step. */
6660 && use_range_stepping
6661 /* Target supports range stepping. */
6662 && rs
->supports_vCont
.r
6663 /* We don't currently support range stepping multiple
6664 threads with a wildcard (though the protocol allows it,
6665 so stubs shouldn't make an active effort to forbid
6667 && !(m_features
.remote_multi_process_p () && ptid
.is_pid ()))
6669 struct thread_info
*tp
;
6671 if (ptid
== minus_one_ptid
)
6673 /* If we don't know about the target thread's tid, then
6674 we're resuming magic_null_ptid (see caller). */
6675 tp
= this->find_thread (magic_null_ptid
);
6678 tp
= this->find_thread (ptid
);
6679 gdb_assert (tp
!= NULL
);
6681 if (tp
->control
.may_range_step
)
6683 int addr_size
= gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
6685 p
+= xsnprintf (p
, endp
- p
, ";r%s,%s",
6686 phex_nz (tp
->control
.step_range_start
,
6688 phex_nz (tp
->control
.step_range_end
,
6692 p
+= xsnprintf (p
, endp
- p
, ";s");
6695 p
+= xsnprintf (p
, endp
- p
, ";s");
6696 else if (siggnal
!= GDB_SIGNAL_0
)
6697 p
+= xsnprintf (p
, endp
- p
, ";C%02x", siggnal
);
6699 p
+= xsnprintf (p
, endp
- p
, ";c");
6701 if (m_features
.remote_multi_process_p () && ptid
.is_pid ())
6705 /* All (-1) threads of process. */
6706 nptid
= ptid_t (ptid
.pid (), -1);
6708 p
+= xsnprintf (p
, endp
- p
, ":");
6709 p
= write_ptid (p
, endp
, nptid
);
6711 else if (ptid
!= minus_one_ptid
)
6713 p
+= xsnprintf (p
, endp
- p
, ":");
6714 p
= write_ptid (p
, endp
, ptid
);
6720 /* Clear the thread's private info on resume. */
6723 resume_clear_thread_private_info (struct thread_info
*thread
)
6725 if (thread
->priv
!= NULL
)
6727 remote_thread_info
*priv
= get_remote_thread_info (thread
);
6729 priv
->stop_reason
= TARGET_STOPPED_BY_NO_REASON
;
6730 priv
->watch_data_address
= 0;
6734 /* Append a vCont continue-with-signal action for threads that have a
6735 non-zero stop signal. */
6738 remote_target::append_pending_thread_resumptions (char *p
, char *endp
,
6741 for (thread_info
*thread
: all_non_exited_threads (this, ptid
))
6742 if (inferior_ptid
!= thread
->ptid
6743 && thread
->stop_signal () != GDB_SIGNAL_0
)
6745 p
= append_resumption (p
, endp
, thread
->ptid
,
6746 0, thread
->stop_signal ());
6747 thread
->set_stop_signal (GDB_SIGNAL_0
);
6748 resume_clear_thread_private_info (thread
);
6754 /* Set the target running, using the packets that use Hc
6758 remote_target::remote_resume_with_hc (ptid_t ptid
, int step
,
6761 struct remote_state
*rs
= get_remote_state ();
6764 rs
->last_sent_signal
= siggnal
;
6765 rs
->last_sent_step
= step
;
6767 /* The c/s/C/S resume packets use Hc, so set the continue
6769 if (ptid
== minus_one_ptid
)
6770 set_continue_thread (any_thread_ptid
);
6772 set_continue_thread (ptid
);
6774 for (thread_info
*thread
: all_non_exited_threads (this))
6775 resume_clear_thread_private_info (thread
);
6777 buf
= rs
->buf
.data ();
6778 if (::execution_direction
== EXEC_REVERSE
)
6780 /* We don't pass signals to the target in reverse exec mode. */
6781 if (info_verbose
&& siggnal
!= GDB_SIGNAL_0
)
6782 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
6785 if (step
&& m_features
.packet_support (PACKET_bs
) == PACKET_DISABLE
)
6786 error (_("Remote reverse-step not supported."));
6787 if (!step
&& m_features
.packet_support (PACKET_bc
) == PACKET_DISABLE
)
6788 error (_("Remote reverse-continue not supported."));
6790 strcpy (buf
, step
? "bs" : "bc");
6792 else if (siggnal
!= GDB_SIGNAL_0
)
6794 buf
[0] = step
? 'S' : 'C';
6795 buf
[1] = tohex (((int) siggnal
>> 4) & 0xf);
6796 buf
[2] = tohex (((int) siggnal
) & 0xf);
6800 strcpy (buf
, step
? "s" : "c");
6805 /* Resume the remote inferior by using a "vCont" packet. SCOPE_PTID,
6806 STEP, and SIGGNAL have the same meaning as in target_resume. This
6807 function returns non-zero iff it resumes the inferior.
6809 This function issues a strict subset of all possible vCont commands
6813 remote_target::remote_resume_with_vcont (ptid_t scope_ptid
, int step
,
6814 enum gdb_signal siggnal
)
6816 struct remote_state
*rs
= get_remote_state ();
6820 /* No reverse execution actions defined for vCont. */
6821 if (::execution_direction
== EXEC_REVERSE
)
6824 if (m_features
.packet_support (PACKET_vCont
) == PACKET_DISABLE
)
6827 p
= rs
->buf
.data ();
6828 endp
= p
+ get_remote_packet_size ();
6830 /* If we could generate a wider range of packets, we'd have to worry
6831 about overflowing BUF. Should there be a generic
6832 "multi-part-packet" packet? */
6834 p
+= xsnprintf (p
, endp
- p
, "vCont");
6836 if (scope_ptid
== magic_null_ptid
)
6838 /* MAGIC_NULL_PTID means that we don't have any active threads,
6839 so we don't have any TID numbers the inferior will
6840 understand. Make sure to only send forms that do not specify
6842 append_resumption (p
, endp
, minus_one_ptid
, step
, siggnal
);
6844 else if (scope_ptid
== minus_one_ptid
|| scope_ptid
.is_pid ())
6846 /* Resume all threads (of all processes, or of a single
6847 process), with preference for INFERIOR_PTID. This assumes
6848 inferior_ptid belongs to the set of all threads we are about
6850 if (step
|| siggnal
!= GDB_SIGNAL_0
)
6852 /* Step inferior_ptid, with or without signal. */
6853 p
= append_resumption (p
, endp
, inferior_ptid
, step
, siggnal
);
6856 /* Also pass down any pending signaled resumption for other
6857 threads not the current. */
6858 p
= append_pending_thread_resumptions (p
, endp
, scope_ptid
);
6860 /* And continue others without a signal. */
6861 append_resumption (p
, endp
, scope_ptid
, /*step=*/ 0, GDB_SIGNAL_0
);
6865 /* Scheduler locking; resume only SCOPE_PTID. */
6866 append_resumption (p
, endp
, scope_ptid
, step
, siggnal
);
6869 gdb_assert (strlen (rs
->buf
.data ()) < get_remote_packet_size ());
6872 if (target_is_non_stop_p ())
6874 /* In non-stop, the stub replies to vCont with "OK". The stop
6875 reply will be reported asynchronously by means of a `%Stop'
6878 if (strcmp (rs
->buf
.data (), "OK") != 0)
6879 error (_("Unexpected vCont reply in non-stop mode: %s"),
6886 /* Tell the remote machine to resume. */
6889 remote_target::resume (ptid_t scope_ptid
, int step
, enum gdb_signal siggnal
)
6891 struct remote_state
*rs
= get_remote_state ();
6893 /* When connected in non-stop mode, the core resumes threads
6894 individually. Resuming remote threads directly in target_resume
6895 would thus result in sending one packet per thread. Instead, to
6896 minimize roundtrip latency, here we just store the resume
6897 request (put the thread in RESUMED_PENDING_VCONT state); the actual remote
6898 resumption will be done in remote_target::commit_resume, where we'll be
6899 able to do vCont action coalescing. */
6900 if (target_is_non_stop_p () && ::execution_direction
!= EXEC_REVERSE
)
6902 remote_thread_info
*remote_thr
6903 = get_remote_thread_info (inferior_thread ());
6905 /* We don't expect the core to ask to resume an already resumed (from
6906 its point of view) thread. */
6907 gdb_assert (remote_thr
->get_resume_state () == resume_state::NOT_RESUMED
);
6909 remote_thr
->set_resumed_pending_vcont (step
, siggnal
);
6911 /* There's actually nothing that says that the core can't
6912 request a wildcard resume in non-stop mode, though. It's
6913 just that we know it doesn't currently, so we don't bother
6915 gdb_assert (scope_ptid
== inferior_ptid
);
6919 commit_requested_thread_options ();
6921 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
6922 (explained in remote-notif.c:handle_notification) so
6923 remote_notif_process is not called. We need find a place where
6924 it is safe to start a 'vNotif' sequence. It is good to do it
6925 before resuming inferior, because inferior was stopped and no RSP
6926 traffic at that moment. */
6927 if (!target_is_non_stop_p ())
6928 remote_notif_process (rs
->notif_state
, ¬if_client_stop
);
6930 rs
->last_resume_exec_dir
= ::execution_direction
;
6932 /* Prefer vCont, and fallback to s/c/S/C, which use Hc. */
6933 if (!remote_resume_with_vcont (scope_ptid
, step
, siggnal
))
6934 remote_resume_with_hc (scope_ptid
, step
, siggnal
);
6936 /* Update resumed state tracked by the remote target. */
6937 for (thread_info
*tp
: all_non_exited_threads (this, scope_ptid
))
6938 get_remote_thread_info (tp
)->set_resumed ();
6940 /* We've just told the target to resume. The remote server will
6941 wait for the inferior to stop, and then send a stop reply. In
6942 the mean time, we can't start another command/query ourselves
6943 because the stub wouldn't be ready to process it. This applies
6944 only to the base all-stop protocol, however. In non-stop (which
6945 only supports vCont), the stub replies with an "OK", and is
6946 immediate able to process further serial input. */
6947 if (!target_is_non_stop_p ())
6948 rs
->waiting_for_stop_reply
= 1;
6951 /* Private per-inferior info for target remote processes. */
6953 struct remote_inferior
: public private_inferior
6955 /* Whether we can send a wildcard vCont for this process. */
6956 bool may_wildcard_vcont
= true;
6959 /* Get the remote private inferior data associated to INF. */
6961 static remote_inferior
*
6962 get_remote_inferior (inferior
*inf
)
6964 if (inf
->priv
== NULL
)
6965 inf
->priv
.reset (new remote_inferior
);
6967 return gdb::checked_static_cast
<remote_inferior
*> (inf
->priv
.get ());
6970 /* Class used to track the construction of a vCont packet in the
6971 outgoing packet buffer. This is used to send multiple vCont
6972 packets if we have more actions than would fit a single packet. */
6977 explicit vcont_builder (remote_target
*remote
)
6984 void push_action (ptid_t ptid
, bool step
, gdb_signal siggnal
);
6989 /* The remote target. */
6990 remote_target
*m_remote
;
6992 /* Pointer to the first action. P points here if no action has been
6994 char *m_first_action
;
6996 /* Where the next action will be appended. */
6999 /* The end of the buffer. Must never write past this. */
7003 /* Prepare the outgoing buffer for a new vCont packet. */
7006 vcont_builder::restart ()
7008 struct remote_state
*rs
= m_remote
->get_remote_state ();
7010 m_p
= rs
->buf
.data ();
7011 m_endp
= m_p
+ m_remote
->get_remote_packet_size ();
7012 m_p
+= xsnprintf (m_p
, m_endp
- m_p
, "vCont");
7013 m_first_action
= m_p
;
7016 /* If the vCont packet being built has any action, send it to the
7020 vcont_builder::flush ()
7022 struct remote_state
*rs
;
7024 if (m_p
== m_first_action
)
7027 rs
= m_remote
->get_remote_state ();
7028 m_remote
->putpkt (rs
->buf
);
7029 m_remote
->getpkt (&rs
->buf
);
7030 if (strcmp (rs
->buf
.data (), "OK") != 0)
7031 error (_("Unexpected vCont reply in non-stop mode: %s"), rs
->buf
.data ());
7034 /* The largest action is range-stepping, with its two addresses. This
7035 is more than sufficient. If a new, bigger action is created, it'll
7036 quickly trigger a failed assertion in append_resumption (and we'll
7038 #define MAX_ACTION_SIZE 200
7040 /* Append a new vCont action in the outgoing packet being built. If
7041 the action doesn't fit the packet along with previous actions, push
7042 what we've got so far to the remote end and start over a new vCont
7043 packet (with the new action). */
7046 vcont_builder::push_action (ptid_t ptid
, bool step
, gdb_signal siggnal
)
7048 char buf
[MAX_ACTION_SIZE
+ 1];
7050 char *endp
= m_remote
->append_resumption (buf
, buf
+ sizeof (buf
),
7051 ptid
, step
, siggnal
);
7053 /* Check whether this new action would fit in the vCont packet along
7054 with previous actions. If not, send what we've got so far and
7055 start a new vCont packet. */
7056 size_t rsize
= endp
- buf
;
7057 if (rsize
> m_endp
- m_p
)
7062 /* Should now fit. */
7063 gdb_assert (rsize
<= m_endp
- m_p
);
7066 memcpy (m_p
, buf
, rsize
);
7071 /* to_commit_resume implementation. */
7074 remote_target::commit_resumed ()
7076 /* If connected in all-stop mode, we'd send the remote resume
7077 request directly from remote_resume. Likewise if
7078 reverse-debugging, as there are no defined vCont actions for
7079 reverse execution. */
7080 if (!target_is_non_stop_p () || ::execution_direction
== EXEC_REVERSE
)
7083 commit_requested_thread_options ();
7085 /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
7086 instead of resuming all threads of each process individually.
7087 However, if any thread of a process must remain halted, we can't
7088 send wildcard resumes and must send one action per thread.
7090 Care must be taken to not resume threads/processes the server
7091 side already told us are stopped, but the core doesn't know about
7092 yet, because the events are still in the vStopped notification
7095 #1 => vCont s:p1.1;c
7097 #3 <= %Stopped T05 p1.1
7102 #8 (infrun handles the stop for p1.1 and continues stepping)
7103 #9 => vCont s:p1.1;c
7105 The last vCont above would resume thread p1.2 by mistake, because
7106 the server has no idea that the event for p1.2 had not been
7109 The server side must similarly ignore resume actions for the
7110 thread that has a pending %Stopped notification (and any other
7111 threads with events pending), until GDB acks the notification
7112 with vStopped. Otherwise, e.g., the following case is
7115 #1 => g (or any other packet)
7117 #3 <= %Stopped T05 p1.2
7118 #4 => vCont s:p1.1;c
7121 Above, the server must not resume thread p1.2. GDB can't know
7122 that p1.2 stopped until it acks the %Stopped notification, and
7123 since from GDB's perspective all threads should be running, it
7126 Finally, special care must also be given to handling fork/vfork
7127 events. A (v)fork event actually tells us that two processes
7128 stopped -- the parent and the child. Until we follow the fork,
7129 we must not resume the child. Therefore, if we have a pending
7130 fork follow, we must not send a global wildcard resume action
7131 (vCont;c). We can still send process-wide wildcards though. */
7133 /* Start by assuming a global wildcard (vCont;c) is possible. */
7134 bool may_global_wildcard_vcont
= true;
7136 /* And assume every process is individually wildcard-able too. */
7137 for (inferior
*inf
: all_non_exited_inferiors (this))
7139 remote_inferior
*priv
= get_remote_inferior (inf
);
7141 priv
->may_wildcard_vcont
= true;
7144 /* Check for any pending events (not reported or processed yet) and
7145 disable process and global wildcard resumes appropriately. */
7146 check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont
);
7148 bool any_pending_vcont_resume
= false;
7150 for (thread_info
*tp
: all_non_exited_threads (this))
7152 remote_thread_info
*priv
= get_remote_thread_info (tp
);
7154 /* If a thread of a process is not meant to be resumed, then we
7155 can't wildcard that process. */
7156 if (priv
->get_resume_state () == resume_state::NOT_RESUMED
)
7158 get_remote_inferior (tp
->inf
)->may_wildcard_vcont
= false;
7160 /* And if we can't wildcard a process, we can't wildcard
7161 everything either. */
7162 may_global_wildcard_vcont
= false;
7166 if (priv
->get_resume_state () == resume_state::RESUMED_PENDING_VCONT
)
7167 any_pending_vcont_resume
= true;
7169 /* If a thread is the parent of an unfollowed fork/vfork/clone,
7170 then we can't do a global wildcard, as that would resume the
7172 if (thread_pending_child_status (tp
) != nullptr)
7173 may_global_wildcard_vcont
= false;
7176 /* We didn't have any resumed thread pending a vCont resume, so nothing to
7178 if (!any_pending_vcont_resume
)
7181 /* Now let's build the vCont packet(s). Actions must be appended
7182 from narrower to wider scopes (thread -> process -> global). If
7183 we end up with too many actions for a single packet vcont_builder
7184 flushes the current vCont packet to the remote side and starts a
7186 struct vcont_builder
vcont_builder (this);
7188 /* Threads first. */
7189 for (thread_info
*tp
: all_non_exited_threads (this))
7191 remote_thread_info
*remote_thr
= get_remote_thread_info (tp
);
7193 /* If the thread was previously vCont-resumed, no need to send a specific
7194 action for it. If we didn't receive a resume request for it, don't
7195 send an action for it either. */
7196 if (remote_thr
->get_resume_state () != resume_state::RESUMED_PENDING_VCONT
)
7199 gdb_assert (!thread_is_in_step_over_chain (tp
));
7201 /* We should never be commit-resuming a thread that has a stop reply.
7202 Otherwise, we would end up reporting a stop event for a thread while
7203 it is running on the remote target. */
7204 remote_state
*rs
= get_remote_state ();
7205 for (const auto &stop_reply
: rs
->stop_reply_queue
)
7206 gdb_assert (stop_reply
->ptid
!= tp
->ptid
);
7208 const resumed_pending_vcont_info
&info
7209 = remote_thr
->resumed_pending_vcont_info ();
7211 /* Check if we need to send a specific action for this thread. If not,
7212 it will be included in a wildcard resume instead. */
7213 if (info
.step
|| info
.sig
!= GDB_SIGNAL_0
7214 || !get_remote_inferior (tp
->inf
)->may_wildcard_vcont
)
7215 vcont_builder
.push_action (tp
->ptid
, info
.step
, info
.sig
);
7217 remote_thr
->set_resumed ();
7220 /* Now check whether we can send any process-wide wildcard. This is
7221 to avoid sending a global wildcard in the case nothing is
7222 supposed to be resumed. */
7223 bool any_process_wildcard
= false;
7225 for (inferior
*inf
: all_non_exited_inferiors (this))
7227 if (get_remote_inferior (inf
)->may_wildcard_vcont
)
7229 any_process_wildcard
= true;
7234 if (any_process_wildcard
)
7236 /* If all processes are wildcard-able, then send a single "c"
7237 action, otherwise, send an "all (-1) threads of process"
7238 continue action for each running process, if any. */
7239 if (may_global_wildcard_vcont
)
7241 vcont_builder
.push_action (minus_one_ptid
,
7242 false, GDB_SIGNAL_0
);
7246 for (inferior
*inf
: all_non_exited_inferiors (this))
7248 if (get_remote_inferior (inf
)->may_wildcard_vcont
)
7250 vcont_builder
.push_action (ptid_t (inf
->pid
),
7251 false, GDB_SIGNAL_0
);
7257 vcont_builder
.flush ();
7260 /* Implementation of target_has_pending_events. */
7263 remote_target::has_pending_events ()
7265 if (target_can_async_p ())
7267 remote_state
*rs
= get_remote_state ();
7269 if (rs
->async_event_handler_marked ())
7272 /* Note that BUFCNT can be negative, indicating sticky
7274 if (rs
->remote_desc
->bufcnt
!= 0)
7282 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
7283 thread, all threads of a remote process, or all threads of all
7287 remote_target::remote_stop_ns (ptid_t ptid
)
7289 struct remote_state
*rs
= get_remote_state ();
7290 char *p
= rs
->buf
.data ();
7291 char *endp
= p
+ get_remote_packet_size ();
7293 /* If any thread that needs to stop was resumed but pending a vCont
7294 resume, generate a phony stop_reply. However, first check
7295 whether the thread wasn't resumed with a signal. Generating a
7296 phony stop in that case would result in losing the signal. */
7297 bool needs_commit
= false;
7298 for (thread_info
*tp
: all_non_exited_threads (this, ptid
))
7300 remote_thread_info
*remote_thr
= get_remote_thread_info (tp
);
7302 if (remote_thr
->get_resume_state ()
7303 == resume_state::RESUMED_PENDING_VCONT
)
7305 const resumed_pending_vcont_info
&info
7306 = remote_thr
->resumed_pending_vcont_info ();
7307 if (info
.sig
!= GDB_SIGNAL_0
)
7309 /* This signal must be forwarded to the inferior. We
7310 could commit-resume just this thread, but its simpler
7311 to just commit-resume everything. */
7312 needs_commit
= true;
7321 for (thread_info
*tp
: all_non_exited_threads (this, ptid
))
7323 remote_thread_info
*remote_thr
= get_remote_thread_info (tp
);
7325 if (remote_thr
->get_resume_state ()
7326 == resume_state::RESUMED_PENDING_VCONT
)
7328 remote_debug_printf ("Enqueueing phony stop reply for thread pending "
7329 "vCont-resume (%d, %ld, %s)", tp
->ptid
.pid(),
7331 pulongest (tp
->ptid
.tid ()));
7333 /* Check that the thread wasn't resumed with a signal.
7334 Generating a phony stop would result in losing the
7336 const resumed_pending_vcont_info
&info
7337 = remote_thr
->resumed_pending_vcont_info ();
7338 gdb_assert (info
.sig
== GDB_SIGNAL_0
);
7340 stop_reply
*sr
= new stop_reply ();
7341 sr
->ptid
= tp
->ptid
;
7343 sr
->ws
.set_stopped (GDB_SIGNAL_0
);
7344 sr
->arch
= tp
->inf
->arch ();
7345 sr
->stop_reason
= TARGET_STOPPED_BY_NO_REASON
;
7346 sr
->watch_data_address
= 0;
7348 this->push_stop_reply (sr
);
7350 /* Pretend that this thread was actually resumed on the
7351 remote target, then stopped. If we leave it in the
7352 RESUMED_PENDING_VCONT state and the commit_resumed
7353 method is called while the stop reply is still in the
7354 queue, we'll end up reporting a stop event to the core
7355 for that thread while it is running on the remote
7356 target... that would be bad. */
7357 remote_thr
->set_resumed ();
7361 if (!rs
->supports_vCont
.t
)
7362 error (_("Remote server does not support stopping threads"));
7364 if (ptid
== minus_one_ptid
7365 || (!m_features
.remote_multi_process_p () && ptid
.is_pid ()))
7366 p
+= xsnprintf (p
, endp
- p
, "vCont;t");
7371 p
+= xsnprintf (p
, endp
- p
, "vCont;t:");
7374 /* All (-1) threads of process. */
7375 nptid
= ptid_t (ptid
.pid (), -1);
7378 /* Small optimization: if we already have a stop reply for
7379 this thread, no use in telling the stub we want this
7381 if (peek_stop_reply (ptid
))
7387 write_ptid (p
, endp
, nptid
);
7390 /* In non-stop, we get an immediate OK reply. The stop reply will
7391 come in asynchronously by notification. */
7394 if (strcmp (rs
->buf
.data (), "OK") != 0)
7395 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid
).c_str (),
7399 /* All-stop version of target_interrupt. Sends a break or a ^C to
7400 interrupt the remote target. It is undefined which thread of which
7401 process reports the interrupt. */
7404 remote_target::remote_interrupt_as ()
7406 struct remote_state
*rs
= get_remote_state ();
7408 rs
->ctrlc_pending_p
= 1;
7410 /* If the inferior is stopped already, but the core didn't know
7411 about it yet, just ignore the request. The pending stop events
7412 will be collected in remote_wait. */
7413 if (stop_reply_queue_length () > 0)
7416 /* Send interrupt_sequence to remote target. */
7417 send_interrupt_sequence ();
7420 /* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
7421 the remote target. It is undefined which thread of which process
7422 reports the interrupt. Throws an error if the packet is not
7423 supported by the server. */
7426 remote_target::remote_interrupt_ns ()
7428 struct remote_state
*rs
= get_remote_state ();
7429 char *p
= rs
->buf
.data ();
7430 char *endp
= p
+ get_remote_packet_size ();
7432 xsnprintf (p
, endp
- p
, "vCtrlC");
7434 /* In non-stop, we get an immediate OK reply. The stop reply will
7435 come in asynchronously by notification. */
7439 switch (m_features
.packet_ok (rs
->buf
, PACKET_vCtrlC
))
7443 case PACKET_UNKNOWN
:
7444 error (_("No support for interrupting the remote target."));
7446 error (_("Interrupting target failed: %s"), rs
->buf
.data ());
7450 /* Implement the to_stop function for the remote targets. */
7453 remote_target::stop (ptid_t ptid
)
7455 REMOTE_SCOPED_DEBUG_ENTER_EXIT
;
7457 if (target_is_non_stop_p ())
7458 remote_stop_ns (ptid
);
7461 /* We don't currently have a way to transparently pause the
7462 remote target in all-stop mode. Interrupt it instead. */
7463 remote_interrupt_as ();
7467 /* Implement the to_interrupt function for the remote targets. */
7470 remote_target::interrupt ()
7472 REMOTE_SCOPED_DEBUG_ENTER_EXIT
;
7474 if (target_is_non_stop_p ())
7475 remote_interrupt_ns ();
7477 remote_interrupt_as ();
7480 /* Implement the to_pass_ctrlc function for the remote targets. */
7483 remote_target::pass_ctrlc ()
7485 REMOTE_SCOPED_DEBUG_ENTER_EXIT
;
7487 struct remote_state
*rs
= get_remote_state ();
7489 /* If we're starting up, we're not fully synced yet. Quit
7491 if (rs
->starting_up
)
7493 /* If ^C has already been sent once, offer to disconnect. */
7494 else if (rs
->ctrlc_pending_p
)
7497 target_interrupt ();
7500 /* Ask the user what to do when an interrupt is received. */
7503 remote_target::interrupt_query ()
7505 struct remote_state
*rs
= get_remote_state ();
7507 if (rs
->waiting_for_stop_reply
&& rs
->ctrlc_pending_p
)
7509 if (query (_("The target is not responding to interrupt requests.\n"
7510 "Stop debugging it? ")))
7512 remote_unpush_target (this);
7513 throw_error (TARGET_CLOSE_ERROR
, _("Disconnected from target."));
7518 if (query (_("Interrupted while waiting for the program.\n"
7519 "Give up waiting? ")))
7524 /* Enable/disable target terminal ownership. Most targets can use
7525 terminal groups to control terminal ownership. Remote targets are
7526 different in that explicit transfer of ownership to/from GDB/target
7530 remote_target::terminal_inferior ()
7532 /* NOTE: At this point we could also register our selves as the
7533 recipient of all input. Any characters typed could then be
7534 passed on down to the target. */
7538 remote_target::terminal_ours ()
7543 remote_console_output (const char *msg
)
7547 for (p
= msg
; p
[0] && p
[1]; p
+= 2)
7550 char c
= fromhex (p
[0]) * 16 + fromhex (p
[1]);
7554 gdb_stdtarg
->puts (tb
);
7556 gdb_stdtarg
->flush ();
7559 /* Return the length of the stop reply queue. */
7562 remote_target::stop_reply_queue_length ()
7564 remote_state
*rs
= get_remote_state ();
7565 return rs
->stop_reply_queue
.size ();
7569 remote_notif_stop_parse (remote_target
*remote
,
7570 const notif_client
*self
, const char *buf
,
7571 struct notif_event
*event
)
7573 remote
->remote_parse_stop_reply (buf
, (struct stop_reply
*) event
);
7577 remote_notif_stop_ack (remote_target
*remote
,
7578 const notif_client
*self
, const char *buf
,
7579 struct notif_event
*event
)
7581 struct stop_reply
*stop_reply
= (struct stop_reply
*) event
;
7584 putpkt (remote
, self
->ack_command
);
7586 /* Kind can be TARGET_WAITKIND_IGNORE if we have meanwhile discarded
7587 the notification. It was left in the queue because we need to
7588 acknowledge it and pull the rest of the notifications out. */
7589 if (stop_reply
->ws
.kind () != TARGET_WAITKIND_IGNORE
)
7590 remote
->push_stop_reply (stop_reply
);
7594 remote_notif_stop_can_get_pending_events (remote_target
*remote
,
7595 const notif_client
*self
)
7597 /* We can't get pending events in remote_notif_process for
7598 notification stop, and we have to do this in remote_wait_ns
7599 instead. If we fetch all queued events from stub, remote stub
7600 may exit and we have no chance to process them back in
7602 remote_state
*rs
= remote
->get_remote_state ();
7603 rs
->mark_async_event_handler ();
7607 stop_reply::~stop_reply ()
7609 for (cached_reg_t
®
: regcache
)
7613 static notif_event_up
7614 remote_notif_stop_alloc_reply ()
7616 return notif_event_up (new struct stop_reply ());
7619 /* A client of notification Stop. */
7621 const notif_client notif_client_stop
=
7625 remote_notif_stop_parse
,
7626 remote_notif_stop_ack
,
7627 remote_notif_stop_can_get_pending_events
,
7628 remote_notif_stop_alloc_reply
,
7632 /* If CONTEXT contains any fork/vfork/clone child threads that have
7633 not been reported yet, remove them from the CONTEXT list. If such
7634 a thread exists it is because we are stopped at a fork/vfork/clone
7635 catchpoint and have not yet called follow_fork/follow_clone, which
7636 will set up the host-side data structures for the new child. */
7639 remote_target::remove_new_children (threads_listing_context
*context
)
7641 const notif_client
*notif
= ¬if_client_stop
;
7643 /* For any threads stopped at a (v)fork/clone event, remove the
7644 corresponding child threads from the CONTEXT list. */
7645 for (thread_info
*thread
: all_non_exited_threads (this))
7647 const target_waitstatus
*ws
= thread_pending_child_status (thread
);
7652 context
->remove_thread (ws
->child_ptid ());
7655 /* Check for any pending (v)fork/clone events (not reported or
7656 processed yet) in process PID and remove those child threads from
7657 the CONTEXT list as well. */
7658 remote_notif_get_pending_events (notif
);
7659 for (auto &event
: get_remote_state ()->stop_reply_queue
)
7660 if (is_new_child_status (event
->ws
.kind ()))
7661 context
->remove_thread (event
->ws
.child_ptid ());
7662 else if (event
->ws
.kind () == TARGET_WAITKIND_THREAD_EXITED
)
7663 context
->remove_thread (event
->ptid
);
7666 /* Check whether any event pending in the vStopped queue would prevent a
7667 global or process wildcard vCont action. Set *may_global_wildcard to
7668 false if we can't do a global wildcard (vCont;c), and clear the event
7669 inferior's may_wildcard_vcont flag if we can't do a process-wide
7670 wildcard resume (vCont;c:pPID.-1). */
7673 remote_target::check_pending_events_prevent_wildcard_vcont
7674 (bool *may_global_wildcard
)
7676 const notif_client
*notif
= ¬if_client_stop
;
7678 remote_notif_get_pending_events (notif
);
7679 for (auto &event
: get_remote_state ()->stop_reply_queue
)
7681 if (event
->ws
.kind () == TARGET_WAITKIND_NO_RESUMED
7682 || event
->ws
.kind () == TARGET_WAITKIND_NO_HISTORY
)
7685 if (event
->ws
.kind () == TARGET_WAITKIND_FORKED
7686 || event
->ws
.kind () == TARGET_WAITKIND_VFORKED
)
7687 *may_global_wildcard
= false;
7689 /* This may be the first time we heard about this process.
7690 Regardless, we must not do a global wildcard resume, otherwise
7691 we'd resume this process too. */
7692 *may_global_wildcard
= false;
7693 if (event
->ptid
!= null_ptid
)
7695 inferior
*inf
= find_inferior_ptid (this, event
->ptid
);
7697 get_remote_inferior (inf
)->may_wildcard_vcont
= false;
7702 /* Discard all pending stop replies of inferior INF. */
7705 remote_target::discard_pending_stop_replies (struct inferior
*inf
)
7707 struct stop_reply
*reply
;
7708 struct remote_state
*rs
= get_remote_state ();
7709 struct remote_notif_state
*rns
= rs
->notif_state
;
7711 /* This function can be notified when an inferior exists. When the
7712 target is not remote, the notification state is NULL. */
7713 if (rs
->remote_desc
== NULL
)
7716 reply
= (struct stop_reply
*) rns
->pending_event
[notif_client_stop
.id
];
7718 /* Discard the in-flight notification. */
7719 if (reply
!= NULL
&& reply
->ptid
.pid () == inf
->pid
)
7721 /* Leave the notification pending, since the server expects that
7722 we acknowledge it with vStopped. But clear its contents, so
7723 that later on when we acknowledge it, we also discard it. */
7725 ("discarding in-flight notification: ptid: %s, ws: %s\n",
7726 reply
->ptid
.to_string().c_str(),
7727 reply
->ws
.to_string ().c_str ());
7728 reply
->ws
.set_ignore ();
7731 /* Discard the stop replies we have already pulled with
7733 auto iter
= std::remove_if (rs
->stop_reply_queue
.begin (),
7734 rs
->stop_reply_queue
.end (),
7735 [=] (const stop_reply_up
&event
)
7737 return event
->ptid
.pid () == inf
->pid
;
7739 for (auto it
= iter
; it
!= rs
->stop_reply_queue
.end (); ++it
)
7741 ("discarding queued stop reply: ptid: %s, ws: %s\n",
7742 (*it
)->ptid
.to_string().c_str(),
7743 (*it
)->ws
.to_string ().c_str ());
7744 rs
->stop_reply_queue
.erase (iter
, rs
->stop_reply_queue
.end ());
7747 /* Discard the stop replies for RS in stop_reply_queue. */
7750 remote_target::discard_pending_stop_replies_in_queue ()
7752 remote_state
*rs
= get_remote_state ();
7754 /* Discard the stop replies we have already pulled with
7756 auto iter
= std::remove_if (rs
->stop_reply_queue
.begin (),
7757 rs
->stop_reply_queue
.end (),
7758 [=] (const stop_reply_up
&event
)
7760 return event
->rs
== rs
;
7762 rs
->stop_reply_queue
.erase (iter
, rs
->stop_reply_queue
.end ());
7765 /* Remove the first reply in 'stop_reply_queue' which matches
7769 remote_target::remote_notif_remove_queued_reply (ptid_t ptid
)
7771 remote_state
*rs
= get_remote_state ();
7773 auto iter
= std::find_if (rs
->stop_reply_queue
.begin (),
7774 rs
->stop_reply_queue
.end (),
7775 [=] (const stop_reply_up
&event
)
7777 return event
->ptid
.matches (ptid
);
7779 struct stop_reply
*result
;
7780 if (iter
== rs
->stop_reply_queue
.end ())
7784 result
= iter
->release ();
7785 rs
->stop_reply_queue
.erase (iter
);
7789 gdb_printf (gdb_stdlog
,
7790 "notif: discard queued event: 'Stop' in %s\n",
7791 ptid
.to_string ().c_str ());
7796 /* Look for a queued stop reply belonging to PTID. If one is found,
7797 remove it from the queue, and return it. Returns NULL if none is
7798 found. If there are still queued events left to process, tell the
7799 event loop to get back to target_wait soon. */
7802 remote_target::queued_stop_reply (ptid_t ptid
)
7804 remote_state
*rs
= get_remote_state ();
7805 struct stop_reply
*r
= remote_notif_remove_queued_reply (ptid
);
7807 if (!rs
->stop_reply_queue
.empty () && target_can_async_p ())
7809 /* There's still at least an event left. */
7810 rs
->mark_async_event_handler ();
7816 /* Push a fully parsed stop reply in the stop reply queue. Since we
7817 know that we now have at least one queued event left to pass to the
7818 core side, tell the event loop to get back to target_wait soon. */
7821 remote_target::push_stop_reply (struct stop_reply
*new_event
)
7823 remote_state
*rs
= get_remote_state ();
7824 rs
->stop_reply_queue
.push_back (stop_reply_up (new_event
));
7827 gdb_printf (gdb_stdlog
,
7828 "notif: push 'Stop' %s to queue %d\n",
7829 new_event
->ptid
.to_string ().c_str (),
7830 int (rs
->stop_reply_queue
.size ()));
7832 /* Mark the pending event queue only if async mode is currently enabled.
7833 If async mode is not currently enabled, then, if it later becomes
7834 enabled, and there are events in this queue, we will mark the event
7835 token at that point, see remote_target::async. */
7836 if (target_is_async_p ())
7837 rs
->mark_async_event_handler ();
7840 /* Returns true if we have a stop reply for PTID. */
7843 remote_target::peek_stop_reply (ptid_t ptid
)
7845 remote_state
*rs
= get_remote_state ();
7846 for (auto &event
: rs
->stop_reply_queue
)
7847 if (ptid
== event
->ptid
7848 && event
->ws
.kind () == TARGET_WAITKIND_STOPPED
)
7853 /* Helper for remote_parse_stop_reply. Return nonzero if the substring
7854 starting with P and ending with PEND matches PREFIX. */
7857 strprefix (const char *p
, const char *pend
, const char *prefix
)
7859 for ( ; p
< pend
; p
++, prefix
++)
7862 return *prefix
== '\0';
7865 /* Parse the stop reply in BUF. Either the function succeeds, and the
7866 result is stored in EVENT, or throws an error. */
7869 remote_target::remote_parse_stop_reply (const char *buf
, stop_reply
*event
)
7871 remote_arch_state
*rsa
= NULL
;
7876 event
->ptid
= null_ptid
;
7877 event
->rs
= get_remote_state ();
7878 event
->ws
.set_ignore ();
7879 event
->stop_reason
= TARGET_STOPPED_BY_NO_REASON
;
7880 event
->regcache
.clear ();
7885 case 'T': /* Status with PC, SP, FP, ... */
7886 /* Expedited reply, containing Signal, {regno, reg} repeat. */
7887 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
7889 n... = register number
7890 r... = register contents
7893 p
= &buf
[3]; /* after Txx */
7899 p1
= strchr (p
, ':');
7901 error (_("Malformed packet(a) (missing colon): %s\n\
7905 error (_("Malformed packet(a) (missing register number): %s\n\
7909 /* Some "registers" are actually extended stop information.
7910 Note if you're adding a new entry here: GDB 7.9 and
7911 earlier assume that all register "numbers" that start
7912 with an hex digit are real register numbers. Make sure
7913 the server only sends such a packet if it knows the
7914 client understands it. */
7916 if (strprefix (p
, p1
, "thread"))
7917 event
->ptid
= read_ptid (++p1
, &p
);
7918 else if (strprefix (p
, p1
, "syscall_entry"))
7922 p
= unpack_varlen_hex (++p1
, &sysno
);
7923 event
->ws
.set_syscall_entry ((int) sysno
);
7925 else if (strprefix (p
, p1
, "syscall_return"))
7929 p
= unpack_varlen_hex (++p1
, &sysno
);
7930 event
->ws
.set_syscall_return ((int) sysno
);
7932 else if (strprefix (p
, p1
, "watch")
7933 || strprefix (p
, p1
, "rwatch")
7934 || strprefix (p
, p1
, "awatch"))
7936 event
->stop_reason
= TARGET_STOPPED_BY_WATCHPOINT
;
7937 p
= unpack_varlen_hex (++p1
, &addr
);
7938 event
->watch_data_address
= (CORE_ADDR
) addr
;
7940 else if (strprefix (p
, p1
, "swbreak"))
7942 event
->stop_reason
= TARGET_STOPPED_BY_SW_BREAKPOINT
;
7944 /* Make sure the stub doesn't forget to indicate support
7946 if (m_features
.packet_support (PACKET_swbreak_feature
)
7948 error (_("Unexpected swbreak stop reason"));
7950 /* The value part is documented as "must be empty",
7951 though we ignore it, in case we ever decide to make
7952 use of it in a backward compatible way. */
7953 p
= strchrnul (p1
+ 1, ';');
7955 else if (strprefix (p
, p1
, "hwbreak"))
7957 event
->stop_reason
= TARGET_STOPPED_BY_HW_BREAKPOINT
;
7959 /* Make sure the stub doesn't forget to indicate support
7961 if (m_features
.packet_support (PACKET_hwbreak_feature
)
7963 error (_("Unexpected hwbreak stop reason"));
7966 p
= strchrnul (p1
+ 1, ';');
7968 else if (strprefix (p
, p1
, "library"))
7970 event
->ws
.set_loaded ();
7971 p
= strchrnul (p1
+ 1, ';');
7973 else if (strprefix (p
, p1
, "replaylog"))
7975 event
->ws
.set_no_history ();
7976 /* p1 will indicate "begin" or "end", but it makes
7977 no difference for now, so ignore it. */
7978 p
= strchrnul (p1
+ 1, ';');
7980 else if (strprefix (p
, p1
, "core"))
7984 p
= unpack_varlen_hex (++p1
, &c
);
7987 else if (strprefix (p
, p1
, "fork"))
7988 event
->ws
.set_forked (read_ptid (++p1
, &p
));
7989 else if (strprefix (p
, p1
, "vfork"))
7990 event
->ws
.set_vforked (read_ptid (++p1
, &p
));
7991 else if (strprefix (p
, p1
, "clone"))
7992 event
->ws
.set_thread_cloned (read_ptid (++p1
, &p
));
7993 else if (strprefix (p
, p1
, "vforkdone"))
7995 event
->ws
.set_vfork_done ();
7996 p
= strchrnul (p1
+ 1, ';');
7998 else if (strprefix (p
, p1
, "exec"))
8003 /* Determine the length of the execd pathname. */
8004 p
= unpack_varlen_hex (++p1
, &ignored
);
8005 pathlen
= (p
- p1
) / 2;
8007 /* Save the pathname for event reporting and for
8008 the next run command. */
8009 gdb::unique_xmalloc_ptr
<char> pathname
8010 ((char *) xmalloc (pathlen
+ 1));
8011 hex2bin (p1
, (gdb_byte
*) pathname
.get (), pathlen
);
8012 pathname
.get ()[pathlen
] = '\0';
8014 /* This is freed during event handling. */
8015 event
->ws
.set_execd (std::move (pathname
));
8017 /* Skip the registers included in this packet, since
8018 they may be for an architecture different from the
8019 one used by the original program. */
8022 else if (strprefix (p
, p1
, "create"))
8024 event
->ws
.set_thread_created ();
8025 p
= strchrnul (p1
+ 1, ';');
8034 p
= strchrnul (p1
+ 1, ';');
8039 /* Maybe a real ``P'' register number. */
8040 p_temp
= unpack_varlen_hex (p
, &pnum
);
8041 /* If the first invalid character is the colon, we got a
8042 register number. Otherwise, it's an unknown stop
8046 /* If we haven't parsed the event's thread yet, find
8047 it now, in order to find the architecture of the
8048 reported expedited registers. */
8049 if (event
->ptid
== null_ptid
)
8051 /* If there is no thread-id information then leave
8052 the event->ptid as null_ptid. Later in
8053 process_stop_reply we will pick a suitable
8055 const char *thr
= strstr (p1
+ 1, ";thread:");
8057 event
->ptid
= read_ptid (thr
+ strlen (";thread:"),
8064 = (event
->ptid
== null_ptid
8066 : find_inferior_ptid (this, event
->ptid
));
8067 /* If this is the first time we learn anything
8068 about this process, skip the registers
8069 included in this packet, since we don't yet
8070 know which architecture to use to parse them.
8071 We'll determine the architecture later when
8072 we process the stop reply and retrieve the
8073 target description, via
8074 remote_notice_new_inferior ->
8075 post_create_inferior. */
8078 p
= strchrnul (p1
+ 1, ';');
8083 event
->arch
= inf
->arch ();
8084 rsa
= event
->rs
->get_remote_arch_state (event
->arch
);
8088 = packet_reg_from_pnum (event
->arch
, rsa
, pnum
);
8089 cached_reg_t cached_reg
;
8092 error (_("Remote sent bad register number %s: %s\n\
8094 hex_string (pnum
), p
, buf
);
8096 cached_reg
.num
= reg
->regnum
;
8097 cached_reg
.data
= (gdb_byte
*)
8098 xmalloc (register_size (event
->arch
, reg
->regnum
));
8101 fieldsize
= hex2bin (p
, cached_reg
.data
,
8102 register_size (event
->arch
, reg
->regnum
));
8104 if (fieldsize
< register_size (event
->arch
, reg
->regnum
))
8105 warning (_("Remote reply is too short: %s"), buf
);
8107 event
->regcache
.push_back (cached_reg
);
8111 /* Not a number. Silently skip unknown optional
8113 p
= strchrnul (p1
+ 1, ';');
8118 error (_("Remote register badly formatted: %s\nhere: %s"),
8123 if (event
->ws
.kind () != TARGET_WAITKIND_IGNORE
)
8127 case 'S': /* Old style status, just signal only. */
8131 sig
= (fromhex (buf
[1]) << 4) + fromhex (buf
[2]);
8132 if (GDB_SIGNAL_FIRST
<= sig
&& sig
< GDB_SIGNAL_LAST
)
8133 event
->ws
.set_stopped ((enum gdb_signal
) sig
);
8135 event
->ws
.set_stopped (GDB_SIGNAL_UNKNOWN
);
8138 case 'w': /* Thread exited. */
8142 p
= unpack_varlen_hex (&buf
[1], &value
);
8143 event
->ws
.set_thread_exited (value
);
8145 error (_("stop reply packet badly formatted: %s"), buf
);
8146 event
->ptid
= read_ptid (++p
, NULL
);
8149 case 'W': /* Target exited. */
8154 /* GDB used to accept only 2 hex chars here. Stubs should
8155 only send more if they detect GDB supports multi-process
8157 p
= unpack_varlen_hex (&buf
[1], &value
);
8161 /* The remote process exited. */
8162 event
->ws
.set_exited (value
);
8166 /* The remote process exited with a signal. */
8167 if (GDB_SIGNAL_FIRST
<= value
&& value
< GDB_SIGNAL_LAST
)
8168 event
->ws
.set_signalled ((enum gdb_signal
) value
);
8170 event
->ws
.set_signalled (GDB_SIGNAL_UNKNOWN
);
8173 /* If no process is specified, return null_ptid, and let the
8174 caller figure out the right process to use. */
8184 else if (startswith (p
, "process:"))
8188 p
+= sizeof ("process:") - 1;
8189 unpack_varlen_hex (p
, &upid
);
8193 error (_("unknown stop reply packet: %s"), buf
);
8196 error (_("unknown stop reply packet: %s"), buf
);
8197 event
->ptid
= ptid_t (pid
);
8201 event
->ws
.set_no_resumed ();
8202 event
->ptid
= minus_one_ptid
;
8207 /* When the stub wants to tell GDB about a new notification reply, it
8208 sends a notification (%Stop, for example). Those can come it at
8209 any time, hence, we have to make sure that any pending
8210 putpkt/getpkt sequence we're making is finished, before querying
8211 the stub for more events with the corresponding ack command
8212 (vStopped, for example). E.g., if we started a vStopped sequence
8213 immediately upon receiving the notification, something like this
8221 1.6) <-- (registers reply to step #1.3)
8223 Obviously, the reply in step #1.6 would be unexpected to a vStopped
8226 To solve this, whenever we parse a %Stop notification successfully,
8227 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
8228 doing whatever we were doing:
8234 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
8235 2.5) <-- (registers reply to step #2.3)
8237 Eventually after step #2.5, we return to the event loop, which
8238 notices there's an event on the
8239 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
8240 associated callback --- the function below. At this point, we're
8241 always safe to start a vStopped sequence. :
8244 2.7) <-- T05 thread:2
8250 remote_target::remote_notif_get_pending_events (const notif_client
*nc
)
8252 struct remote_state
*rs
= get_remote_state ();
8254 if (rs
->notif_state
->pending_event
[nc
->id
] != NULL
)
8257 gdb_printf (gdb_stdlog
,
8258 "notif: process: '%s' ack pending event\n",
8262 nc
->ack (this, nc
, rs
->buf
.data (),
8263 rs
->notif_state
->pending_event
[nc
->id
]);
8264 rs
->notif_state
->pending_event
[nc
->id
] = NULL
;
8269 if (strcmp (rs
->buf
.data (), "OK") == 0)
8272 remote_notif_ack (this, nc
, rs
->buf
.data ());
8278 gdb_printf (gdb_stdlog
,
8279 "notif: process: '%s' no pending reply\n",
8284 /* Wrapper around remote_target::remote_notif_get_pending_events to
8285 avoid having to export the whole remote_target class. */
8288 remote_notif_get_pending_events (remote_target
*remote
, const notif_client
*nc
)
8290 remote
->remote_notif_get_pending_events (nc
);
8293 /* Called from process_stop_reply when the stop packet we are responding
8294 to didn't include a process-id or thread-id. STATUS is the stop event
8295 we are responding to.
8297 It is the task of this function to select a suitable thread (or process)
8298 and return its ptid, this is the thread (or process) we will assume the
8299 stop event came from.
8301 In some cases there isn't really any choice about which thread (or
8302 process) is selected, a basic remote with a single process containing a
8303 single thread might choose not to send any process-id or thread-id in
8304 its stop packets, this function will select and return the one and only
8307 However, if a target supports multiple threads (or processes) and still
8308 doesn't include a thread-id (or process-id) in its stop packet then
8309 first, this is a badly behaving target, and second, we're going to have
8310 to select a thread (or process) at random and use that. This function
8311 will print a warning to the user if it detects that there is the
8312 possibility that GDB is guessing which thread (or process) to
8315 Note that this is called before GDB fetches the updated thread list from the
8316 target. So it's possible for the stop reply to be ambiguous and for GDB to
8317 not realize it. For example, if there's initially one thread, the target
8318 spawns a second thread, and then sends a stop reply without an id that
8319 concerns the first thread. GDB will assume the stop reply is about the
8320 first thread - the only thread it knows about - without printing a warning.
8321 Anyway, if the remote meant for the stop reply to be about the second thread,
8322 then it would be really broken, because GDB doesn't know about that thread
8326 remote_target::select_thread_for_ambiguous_stop_reply
8327 (const target_waitstatus
&status
)
8329 REMOTE_SCOPED_DEBUG_ENTER_EXIT
;
8331 /* Some stop events apply to all threads in an inferior, while others
8332 only apply to a single thread. */
8333 bool process_wide_stop
8334 = (status
.kind () == TARGET_WAITKIND_EXITED
8335 || status
.kind () == TARGET_WAITKIND_SIGNALLED
);
8337 remote_debug_printf ("process_wide_stop = %d", process_wide_stop
);
8339 thread_info
*first_resumed_thread
= nullptr;
8340 bool ambiguous
= false;
8342 /* Consider all non-exited threads of the target, find the first resumed
8344 for (thread_info
*thr
: all_non_exited_threads (this))
8346 remote_thread_info
*remote_thr
= get_remote_thread_info (thr
);
8348 if (remote_thr
->get_resume_state () != resume_state::RESUMED
)
8351 if (first_resumed_thread
== nullptr)
8352 first_resumed_thread
= thr
;
8353 else if (!process_wide_stop
8354 || first_resumed_thread
->ptid
.pid () != thr
->ptid
.pid ())
8358 gdb_assert (first_resumed_thread
!= nullptr);
8360 remote_debug_printf ("first resumed thread is %s",
8361 pid_to_str (first_resumed_thread
->ptid
).c_str ());
8362 remote_debug_printf ("is this guess ambiguous? = %d", ambiguous
);
8364 /* Warn if the remote target is sending ambiguous stop replies. */
8367 static bool warned
= false;
8371 /* If you are seeing this warning then the remote target has
8372 stopped without specifying a thread-id, but the target
8373 does have multiple threads (or inferiors), and so GDB is
8374 having to guess which thread stopped.
8376 Examples of what might cause this are the target sending
8377 and 'S' stop packet, or a 'T' stop packet and not
8378 including a thread-id.
8380 Additionally, the target might send a 'W' or 'X packet
8381 without including a process-id, when the target has
8382 multiple running inferiors. */
8383 if (process_wide_stop
)
8384 warning (_("multi-inferior target stopped without "
8385 "sending a process-id, using first "
8386 "non-exited inferior"));
8388 warning (_("multi-threaded target stopped without "
8389 "sending a thread-id, using first "
8390 "non-exited thread"));
8395 /* If this is a stop for all threads then don't use a particular threads
8396 ptid, instead create a new ptid where only the pid field is set. */
8397 if (process_wide_stop
)
8398 return ptid_t (first_resumed_thread
->ptid
.pid ());
8400 return first_resumed_thread
->ptid
;
8403 /* Called when it is decided that STOP_REPLY holds the info of the
8404 event that is to be returned to the core. This function always
8405 destroys STOP_REPLY. */
8408 remote_target::process_stop_reply (struct stop_reply
*stop_reply
,
8409 struct target_waitstatus
*status
)
8411 *status
= stop_reply
->ws
;
8412 ptid_t ptid
= stop_reply
->ptid
;
8414 /* If no thread/process was reported by the stub then select a suitable
8416 if (ptid
== null_ptid
)
8417 ptid
= select_thread_for_ambiguous_stop_reply (*status
);
8418 gdb_assert (ptid
!= null_ptid
);
8420 if (status
->kind () != TARGET_WAITKIND_EXITED
8421 && status
->kind () != TARGET_WAITKIND_SIGNALLED
8422 && status
->kind () != TARGET_WAITKIND_NO_RESUMED
)
8424 remote_notice_new_inferior (ptid
, false);
8426 /* Expedited registers. */
8427 if (!stop_reply
->regcache
.empty ())
8429 /* 'w' stop replies don't cary expedited registers (which
8430 wouldn't make any sense for a thread that is gone
8432 gdb_assert (status
->kind () != TARGET_WAITKIND_THREAD_EXITED
);
8435 = get_thread_arch_regcache (find_inferior_ptid (this, ptid
), ptid
,
8438 for (cached_reg_t
®
: stop_reply
->regcache
)
8440 regcache
->raw_supply (reg
.num
, reg
.data
);
8444 stop_reply
->regcache
.clear ();
8447 remote_thread_info
*remote_thr
= get_remote_thread_info (this, ptid
);
8448 remote_thr
->core
= stop_reply
->core
;
8449 remote_thr
->stop_reason
= stop_reply
->stop_reason
;
8450 remote_thr
->watch_data_address
= stop_reply
->watch_data_address
;
8452 if (target_is_non_stop_p ())
8454 /* If the target works in non-stop mode, a stop-reply indicates that
8455 only this thread stopped. */
8456 remote_thr
->set_not_resumed ();
8460 /* If the target works in all-stop mode, a stop-reply indicates that
8461 all the target's threads stopped. */
8462 for (thread_info
*tp
: all_non_exited_threads (this))
8463 get_remote_thread_info (tp
)->set_not_resumed ();
8471 /* The non-stop mode version of target_wait. */
8474 remote_target::wait_ns (ptid_t ptid
, struct target_waitstatus
*status
,
8475 target_wait_flags options
)
8477 struct remote_state
*rs
= get_remote_state ();
8478 struct stop_reply
*stop_reply
;
8480 bool is_notif
= false;
8482 /* If in non-stop mode, get out of getpkt even if a
8483 notification is received. */
8485 ret
= getpkt (&rs
->buf
, false /* forever */, &is_notif
);
8488 if (ret
!= -1 && !is_notif
)
8491 case 'E': /* Error of some sort. */
8492 /* We're out of sync with the target now. Did it continue
8493 or not? We can't tell which thread it was in non-stop,
8494 so just ignore this. */
8495 warning (_("Remote failure reply: %s"), rs
->buf
.data ());
8497 case 'O': /* Console output. */
8498 remote_console_output (&rs
->buf
[1]);
8501 warning (_("Invalid remote reply: %s"), rs
->buf
.data ());
8505 /* Acknowledge a pending stop reply that may have arrived in the
8507 if (rs
->notif_state
->pending_event
[notif_client_stop
.id
] != NULL
)
8508 remote_notif_get_pending_events (¬if_client_stop
);
8510 /* If indeed we noticed a stop reply, we're done. */
8511 stop_reply
= queued_stop_reply (ptid
);
8512 if (stop_reply
!= NULL
)
8513 return process_stop_reply (stop_reply
, status
);
8515 /* Still no event. If we're just polling for an event, then
8516 return to the event loop. */
8517 if (options
& TARGET_WNOHANG
)
8519 status
->set_ignore ();
8520 return minus_one_ptid
;
8523 /* Otherwise do a blocking wait. */
8524 ret
= getpkt (&rs
->buf
, true /* forever */, &is_notif
);
8528 /* Return the first resumed thread. */
8531 first_remote_resumed_thread (remote_target
*target
)
8533 for (thread_info
*tp
: all_non_exited_threads (target
, minus_one_ptid
))
8539 /* Wait until the remote machine stops, then return, storing status in
8540 STATUS just as `wait' would. */
8543 remote_target::wait_as (ptid_t ptid
, target_waitstatus
*status
,
8544 target_wait_flags options
)
8546 struct remote_state
*rs
= get_remote_state ();
8547 ptid_t event_ptid
= null_ptid
;
8549 struct stop_reply
*stop_reply
;
8553 status
->set_ignore ();
8555 stop_reply
= queued_stop_reply (ptid
);
8556 if (stop_reply
!= NULL
)
8558 /* None of the paths that push a stop reply onto the queue should
8559 have set the waiting_for_stop_reply flag. */
8560 gdb_assert (!rs
->waiting_for_stop_reply
);
8561 event_ptid
= process_stop_reply (stop_reply
, status
);
8565 bool forever
= ((options
& TARGET_WNOHANG
) == 0
8566 && rs
->wait_forever_enabled_p
);
8568 if (!rs
->waiting_for_stop_reply
)
8570 status
->set_no_resumed ();
8571 return minus_one_ptid
;
8574 /* FIXME: cagney/1999-09-27: If we're in async mode we should
8575 _never_ wait for ever -> test on target_is_async_p().
8576 However, before we do that we need to ensure that the caller
8577 knows how to take the target into/out of async mode. */
8579 int ret
= getpkt (&rs
->buf
, forever
, &is_notif
);
8581 /* GDB gets a notification. Return to core as this event is
8583 if (ret
!= -1 && is_notif
)
8584 return minus_one_ptid
;
8586 if (ret
== -1 && (options
& TARGET_WNOHANG
) != 0)
8587 return minus_one_ptid
;
8589 buf
= rs
->buf
.data ();
8591 /* Assume that the target has acknowledged Ctrl-C unless we receive
8592 an 'F' or 'O' packet. */
8593 if (buf
[0] != 'F' && buf
[0] != 'O')
8594 rs
->ctrlc_pending_p
= 0;
8598 case 'E': /* Error of some sort. */
8599 /* We're out of sync with the target now. Did it continue or
8600 not? Not is more likely, so report a stop. */
8601 rs
->waiting_for_stop_reply
= 0;
8603 warning (_("Remote failure reply: %s"), buf
);
8604 status
->set_stopped (GDB_SIGNAL_0
);
8606 case 'F': /* File-I/O request. */
8607 /* GDB may access the inferior memory while handling the File-I/O
8608 request, but we don't want GDB accessing memory while waiting
8609 for a stop reply. See the comments in putpkt_binary. Set
8610 waiting_for_stop_reply to 0 temporarily. */
8611 rs
->waiting_for_stop_reply
= 0;
8612 remote_fileio_request (this, buf
, rs
->ctrlc_pending_p
);
8613 rs
->ctrlc_pending_p
= 0;
8614 /* GDB handled the File-I/O request, and the target is running
8615 again. Keep waiting for events. */
8616 rs
->waiting_for_stop_reply
= 1;
8618 case 'N': case 'T': case 'S': case 'X': case 'W': case 'w':
8620 /* There is a stop reply to handle. */
8621 rs
->waiting_for_stop_reply
= 0;
8624 = (struct stop_reply
*) remote_notif_parse (this,
8628 event_ptid
= process_stop_reply (stop_reply
, status
);
8631 case 'O': /* Console output. */
8632 remote_console_output (buf
+ 1);
8635 if (rs
->last_sent_signal
!= GDB_SIGNAL_0
)
8637 /* Zero length reply means that we tried 'S' or 'C' and the
8638 remote system doesn't support it. */
8639 target_terminal::ours_for_output ();
8641 ("Can't send signals to this remote system. %s not sent.\n",
8642 gdb_signal_to_name (rs
->last_sent_signal
));
8643 rs
->last_sent_signal
= GDB_SIGNAL_0
;
8644 target_terminal::inferior ();
8646 strcpy (buf
, rs
->last_sent_step
? "s" : "c");
8652 warning (_("Invalid remote reply: %s"), buf
);
8657 if (status
->kind () == TARGET_WAITKIND_NO_RESUMED
)
8658 return minus_one_ptid
;
8659 else if (status
->kind () == TARGET_WAITKIND_IGNORE
)
8661 /* Nothing interesting happened. If we're doing a non-blocking
8662 poll, we're done. Otherwise, go back to waiting. */
8663 if (options
& TARGET_WNOHANG
)
8664 return minus_one_ptid
;
8668 else if (status
->kind () != TARGET_WAITKIND_EXITED
8669 && status
->kind () != TARGET_WAITKIND_SIGNALLED
)
8671 if (event_ptid
!= null_ptid
)
8672 record_currthread (rs
, event_ptid
);
8674 event_ptid
= first_remote_resumed_thread (this);
8678 /* A process exit. Invalidate our notion of current thread. */
8679 record_currthread (rs
, minus_one_ptid
);
8680 /* It's possible that the packet did not include a pid. */
8681 if (event_ptid
== null_ptid
)
8682 event_ptid
= first_remote_resumed_thread (this);
8683 /* EVENT_PTID could still be NULL_PTID. Double-check. */
8684 if (event_ptid
== null_ptid
)
8685 event_ptid
= magic_null_ptid
;
8691 /* Wait until the remote machine stops, then return, storing status in
8692 STATUS just as `wait' would. */
8695 remote_target::wait (ptid_t ptid
, struct target_waitstatus
*status
,
8696 target_wait_flags options
)
8698 REMOTE_SCOPED_DEBUG_ENTER_EXIT
;
8700 remote_state
*rs
= get_remote_state ();
8702 /* Start by clearing the flag that asks for our wait method to be called,
8703 we'll mark it again at the end if needed. If the target is not in
8704 async mode then the async token should not be marked. */
8705 if (target_is_async_p ())
8706 rs
->clear_async_event_handler ();
8708 gdb_assert (!rs
->async_event_handler_marked ());
8712 if (target_is_non_stop_p ())
8713 event_ptid
= wait_ns (ptid
, status
, options
);
8715 event_ptid
= wait_as (ptid
, status
, options
);
8717 if (target_is_async_p ())
8719 /* If there are events left in the queue, or unacknowledged
8720 notifications, then tell the event loop to call us again. */
8721 if (!rs
->stop_reply_queue
.empty ()
8722 || rs
->notif_state
->pending_event
[notif_client_stop
.id
] != nullptr)
8723 rs
->mark_async_event_handler ();
8729 /* Fetch a single register using a 'p' packet. */
8732 remote_target::fetch_register_using_p (struct regcache
*regcache
,
8735 struct gdbarch
*gdbarch
= regcache
->arch ();
8736 struct remote_state
*rs
= get_remote_state ();
8738 gdb_byte
*regp
= (gdb_byte
*) alloca (register_size (gdbarch
, reg
->regnum
));
8741 if (m_features
.packet_support (PACKET_p
) == PACKET_DISABLE
)
8744 if (reg
->pnum
== -1)
8747 p
= rs
->buf
.data ();
8749 p
+= hexnumstr (p
, reg
->pnum
);
8754 buf
= rs
->buf
.data ();
8756 switch (m_features
.packet_ok (rs
->buf
, PACKET_p
))
8760 case PACKET_UNKNOWN
:
8763 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
8764 gdbarch_register_name (regcache
->arch (), reg
->regnum
),
8768 /* If this register is unfetchable, tell the regcache. */
8771 regcache
->raw_supply (reg
->regnum
, NULL
);
8775 /* Otherwise, parse and supply the value. */
8781 error (_("fetch_register_using_p: early buf termination"));
8783 regp
[i
++] = fromhex (p
[0]) * 16 + fromhex (p
[1]);
8786 regcache
->raw_supply (reg
->regnum
, regp
);
8790 /* Fetch the registers included in the target's 'g' packet. */
8793 remote_target::send_g_packet ()
8795 struct remote_state
*rs
= get_remote_state ();
8798 xsnprintf (rs
->buf
.data (), get_remote_packet_size (), "g");
8801 if (packet_check_result (rs
->buf
) == PACKET_ERROR
)
8802 error (_("Could not read registers; remote failure reply '%s'"),
8805 /* We can get out of synch in various cases. If the first character
8806 in the buffer is not a hex character, assume that has happened
8807 and try to fetch another packet to read. */
8808 while ((rs
->buf
[0] < '0' || rs
->buf
[0] > '9')
8809 && (rs
->buf
[0] < 'A' || rs
->buf
[0] > 'F')
8810 && (rs
->buf
[0] < 'a' || rs
->buf
[0] > 'f')
8811 && rs
->buf
[0] != 'x') /* New: unavailable register value. */
8813 remote_debug_printf ("Bad register packet; fetching a new packet");
8817 buf_len
= strlen (rs
->buf
.data ());
8819 /* Sanity check the received packet. */
8820 if (buf_len
% 2 != 0)
8821 error (_("Remote 'g' packet reply is of odd length: %s"), rs
->buf
.data ());
8827 remote_target::process_g_packet (struct regcache
*regcache
)
8829 struct gdbarch
*gdbarch
= regcache
->arch ();
8830 struct remote_state
*rs
= get_remote_state ();
8831 remote_arch_state
*rsa
= rs
->get_remote_arch_state (gdbarch
);
8836 buf_len
= strlen (rs
->buf
.data ());
8838 /* Further sanity checks, with knowledge of the architecture. */
8839 if (buf_len
> 2 * rsa
->sizeof_g_packet
)
8840 error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
8842 rsa
->sizeof_g_packet
, buf_len
/ 2,
8845 /* Save the size of the packet sent to us by the target. It is used
8846 as a heuristic when determining the max size of packets that the
8847 target can safely receive. */
8848 if (rsa
->actual_register_packet_size
== 0)
8849 rsa
->actual_register_packet_size
= buf_len
;
8851 /* If this is smaller than we guessed the 'g' packet would be,
8852 update our records. A 'g' reply that doesn't include a register's
8853 value implies either that the register is not available, or that
8854 the 'p' packet must be used. */
8855 if (buf_len
< 2 * rsa
->sizeof_g_packet
)
8857 long sizeof_g_packet
= buf_len
/ 2;
8859 for (i
= 0; i
< gdbarch_num_regs (gdbarch
); i
++)
8861 long offset
= rsa
->regs
[i
].offset
;
8862 long reg_size
= register_size (gdbarch
, i
);
8864 if (rsa
->regs
[i
].pnum
== -1)
8867 if (offset
>= sizeof_g_packet
)
8868 rsa
->regs
[i
].in_g_packet
= 0;
8869 else if (offset
+ reg_size
> sizeof_g_packet
)
8870 error (_("Truncated register %d in remote 'g' packet"), i
);
8872 rsa
->regs
[i
].in_g_packet
= 1;
8875 /* Looks valid enough, we can assume this is the correct length
8876 for a 'g' packet. It's important not to adjust
8877 rsa->sizeof_g_packet if we have truncated registers otherwise
8878 this "if" won't be run the next time the method is called
8879 with a packet of the same size and one of the internal errors
8880 below will trigger instead. */
8881 rsa
->sizeof_g_packet
= sizeof_g_packet
;
8884 regs
= (char *) alloca (rsa
->sizeof_g_packet
);
8886 /* Unimplemented registers read as all bits zero. */
8887 memset (regs
, 0, rsa
->sizeof_g_packet
);
8889 /* Reply describes registers byte by byte, each byte encoded as two
8890 hex characters. Suck them all up, then supply them to the
8891 register cacheing/storage mechanism. */
8893 p
= rs
->buf
.data ();
8894 for (i
= 0; i
< rsa
->sizeof_g_packet
; i
++)
8896 if (p
[0] == 0 || p
[1] == 0)
8897 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
8898 internal_error (_("unexpected end of 'g' packet reply"));
8900 if (p
[0] == 'x' && p
[1] == 'x')
8901 regs
[i
] = 0; /* 'x' */
8903 regs
[i
] = fromhex (p
[0]) * 16 + fromhex (p
[1]);
8907 for (i
= 0; i
< gdbarch_num_regs (gdbarch
); i
++)
8909 struct packet_reg
*r
= &rsa
->regs
[i
];
8910 long reg_size
= register_size (gdbarch
, i
);
8914 if ((r
->offset
+ reg_size
) * 2 > strlen (rs
->buf
.data ()))
8915 /* This shouldn't happen - we adjusted in_g_packet above. */
8916 internal_error (_("unexpected end of 'g' packet reply"));
8917 else if (rs
->buf
[r
->offset
* 2] == 'x')
8919 gdb_assert (r
->offset
* 2 < strlen (rs
->buf
.data ()));
8920 /* The register isn't available, mark it as such (at
8921 the same time setting the value to zero). */
8922 regcache
->raw_supply (r
->regnum
, NULL
);
8925 regcache
->raw_supply (r
->regnum
, regs
+ r
->offset
);
8931 remote_target::fetch_registers_using_g (struct regcache
*regcache
)
8934 process_g_packet (regcache
);
8937 /* Make the remote selected traceframe match GDB's selected
8941 remote_target::set_remote_traceframe ()
8944 struct remote_state
*rs
= get_remote_state ();
8946 if (rs
->remote_traceframe_number
== get_traceframe_number ())
8949 /* Avoid recursion, remote_trace_find calls us again. */
8950 rs
->remote_traceframe_number
= get_traceframe_number ();
8952 newnum
= target_trace_find (tfind_number
,
8953 get_traceframe_number (), 0, 0, NULL
);
8955 /* Should not happen. If it does, all bets are off. */
8956 if (newnum
!= get_traceframe_number ())
8957 warning (_("could not set remote traceframe"));
8961 remote_target::fetch_registers (struct regcache
*regcache
, int regnum
)
8963 struct gdbarch
*gdbarch
= regcache
->arch ();
8964 struct remote_state
*rs
= get_remote_state ();
8965 remote_arch_state
*rsa
= rs
->get_remote_arch_state (gdbarch
);
8968 set_remote_traceframe ();
8969 set_general_thread (regcache
->ptid ());
8973 packet_reg
*reg
= packet_reg_from_regnum (gdbarch
, rsa
, regnum
);
8975 gdb_assert (reg
!= NULL
);
8977 /* If this register might be in the 'g' packet, try that first -
8978 we are likely to read more than one register. If this is the
8979 first 'g' packet, we might be overly optimistic about its
8980 contents, so fall back to 'p'. */
8981 if (reg
->in_g_packet
)
8983 fetch_registers_using_g (regcache
);
8984 if (reg
->in_g_packet
)
8988 if (fetch_register_using_p (regcache
, reg
))
8991 /* This register is not available. */
8992 regcache
->raw_supply (reg
->regnum
, NULL
);
8997 fetch_registers_using_g (regcache
);
8999 for (i
= 0; i
< gdbarch_num_regs (gdbarch
); i
++)
9000 if (!rsa
->regs
[i
].in_g_packet
)
9001 if (!fetch_register_using_p (regcache
, &rsa
->regs
[i
]))
9003 /* This register is not available. */
9004 regcache
->raw_supply (i
, NULL
);
9008 /* Prepare to store registers. Since we may send them all (using a
9009 'G' request), we have to read out the ones we don't want to change
9013 remote_target::prepare_to_store (struct regcache
*regcache
)
9015 struct remote_state
*rs
= get_remote_state ();
9016 remote_arch_state
*rsa
= rs
->get_remote_arch_state (regcache
->arch ());
9019 /* Make sure the entire registers array is valid. */
9020 switch (m_features
.packet_support (PACKET_P
))
9022 case PACKET_DISABLE
:
9023 case PACKET_SUPPORT_UNKNOWN
:
9024 /* Make sure all the necessary registers are cached. */
9025 for (i
= 0; i
< gdbarch_num_regs (regcache
->arch ()); i
++)
9026 if (rsa
->regs
[i
].in_g_packet
)
9027 regcache
->raw_update (rsa
->regs
[i
].regnum
);
9034 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
9035 packet was not recognized. */
9038 remote_target::store_register_using_P (const struct regcache
*regcache
,
9041 struct gdbarch
*gdbarch
= regcache
->arch ();
9042 struct remote_state
*rs
= get_remote_state ();
9043 /* Try storing a single register. */
9044 char *buf
= rs
->buf
.data ();
9045 gdb_byte
*regp
= (gdb_byte
*) alloca (register_size (gdbarch
, reg
->regnum
));
9048 if (m_features
.packet_support (PACKET_P
) == PACKET_DISABLE
)
9051 if (reg
->pnum
== -1)
9054 xsnprintf (buf
, get_remote_packet_size (), "P%s=", phex_nz (reg
->pnum
, 0));
9055 p
= buf
+ strlen (buf
);
9056 regcache
->raw_collect (reg
->regnum
, regp
);
9057 bin2hex (regp
, p
, register_size (gdbarch
, reg
->regnum
));
9061 switch (m_features
.packet_ok (rs
->buf
, PACKET_P
))
9066 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
9067 gdbarch_register_name (gdbarch
, reg
->regnum
), rs
->buf
.data ());
9068 case PACKET_UNKNOWN
:
9071 internal_error (_("Bad result from packet_ok"));
9075 /* Store register REGNUM, or all registers if REGNUM == -1, from the
9076 contents of the register cache buffer. FIXME: ignores errors. */
9079 remote_target::store_registers_using_G (const struct regcache
*regcache
)
9081 struct remote_state
*rs
= get_remote_state ();
9082 remote_arch_state
*rsa
= rs
->get_remote_arch_state (regcache
->arch ());
9086 /* Extract all the registers in the regcache copying them into a
9091 regs
= (gdb_byte
*) alloca (rsa
->sizeof_g_packet
);
9092 memset (regs
, 0, rsa
->sizeof_g_packet
);
9093 for (i
= 0; i
< gdbarch_num_regs (regcache
->arch ()); i
++)
9095 struct packet_reg
*r
= &rsa
->regs
[i
];
9098 regcache
->raw_collect (r
->regnum
, regs
+ r
->offset
);
9102 /* Command describes registers byte by byte,
9103 each byte encoded as two hex characters. */
9104 p
= rs
->buf
.data ();
9106 bin2hex (regs
, p
, rsa
->sizeof_g_packet
);
9109 if (packet_check_result (rs
->buf
) == PACKET_ERROR
)
9110 error (_("Could not write registers; remote failure reply '%s'"),
9114 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
9115 of the register cache buffer. FIXME: ignores errors. */
9118 remote_target::store_registers (struct regcache
*regcache
, int regnum
)
9120 struct gdbarch
*gdbarch
= regcache
->arch ();
9121 struct remote_state
*rs
= get_remote_state ();
9122 remote_arch_state
*rsa
= rs
->get_remote_arch_state (gdbarch
);
9125 set_remote_traceframe ();
9126 set_general_thread (regcache
->ptid ());
9130 packet_reg
*reg
= packet_reg_from_regnum (gdbarch
, rsa
, regnum
);
9132 gdb_assert (reg
!= NULL
);
9134 /* Always prefer to store registers using the 'P' packet if
9135 possible; we often change only a small number of registers.
9136 Sometimes we change a larger number; we'd need help from a
9137 higher layer to know to use 'G'. */
9138 if (store_register_using_P (regcache
, reg
))
9141 /* For now, don't complain if we have no way to write the
9142 register. GDB loses track of unavailable registers too
9143 easily. Some day, this may be an error. We don't have
9144 any way to read the register, either... */
9145 if (!reg
->in_g_packet
)
9148 store_registers_using_G (regcache
);
9152 store_registers_using_G (regcache
);
9154 for (i
= 0; i
< gdbarch_num_regs (gdbarch
); i
++)
9155 if (!rsa
->regs
[i
].in_g_packet
)
9156 if (!store_register_using_P (regcache
, &rsa
->regs
[i
]))
9157 /* See above for why we do not issue an error here. */
9162 /* Return the number of hex digits in num. */
9165 hexnumlen (ULONGEST num
)
9169 for (i
= 0; num
!= 0; i
++)
9172 return std::max (i
, 1);
9175 /* Set BUF to the minimum number of hex digits representing NUM. */
9178 hexnumstr (char *buf
, ULONGEST num
)
9180 int len
= hexnumlen (num
);
9182 return hexnumnstr (buf
, num
, len
);
9186 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
9189 hexnumnstr (char *buf
, ULONGEST num
, int width
)
9195 for (i
= width
- 1; i
>= 0; i
--)
9197 buf
[i
] = "0123456789abcdef"[(num
& 0xf)];
9204 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
9207 remote_address_masked (CORE_ADDR addr
)
9209 unsigned int address_size
= remote_address_size
;
9211 /* If "remoteaddresssize" was not set, default to target address size. */
9213 address_size
= gdbarch_addr_bit (current_inferior ()->arch ());
9215 if (address_size
> 0
9216 && address_size
< (sizeof (ULONGEST
) * 8))
9218 /* Only create a mask when that mask can safely be constructed
9219 in a ULONGEST variable. */
9222 mask
= (mask
<< address_size
) - 1;
9228 /* Determine whether the remote target supports binary downloading.
9229 This is accomplished by sending a no-op memory write of zero length
9230 to the target at the specified address. It does not suffice to send
9231 the whole packet, since many stubs strip the eighth bit and
9232 subsequently compute a wrong checksum, which causes real havoc with
9235 NOTE: This can still lose if the serial line is not eight-bit
9236 clean. In cases like this, the user should clear "remote
9240 remote_target::check_binary_download (CORE_ADDR addr
)
9242 struct remote_state
*rs
= get_remote_state ();
9244 switch (m_features
.packet_support (PACKET_X
))
9246 case PACKET_DISABLE
:
9250 case PACKET_SUPPORT_UNKNOWN
:
9254 p
= rs
->buf
.data ();
9256 p
+= hexnumstr (p
, (ULONGEST
) addr
);
9258 p
+= hexnumstr (p
, (ULONGEST
) 0);
9262 putpkt_binary (rs
->buf
.data (), (int) (p
- rs
->buf
.data ()));
9265 if (rs
->buf
[0] == '\0')
9267 remote_debug_printf ("binary downloading NOT supported by target");
9268 m_features
.m_protocol_packets
[PACKET_X
].support
= PACKET_DISABLE
;
9272 remote_debug_printf ("binary downloading supported by target");
9273 m_features
.m_protocol_packets
[PACKET_X
].support
= PACKET_ENABLE
;
9280 /* Helper function to resize the payload in order to try to get a good
9281 alignment. We try to write an amount of data such that the next write will
9282 start on an address aligned on REMOTE_ALIGN_WRITES. */
9285 align_for_efficient_write (int todo
, CORE_ADDR memaddr
)
9287 return ((memaddr
+ todo
) & ~(REMOTE_ALIGN_WRITES
- 1)) - memaddr
;
9290 /* Write memory data directly to the remote machine.
9291 This does not inform the data cache; the data cache uses this.
9292 HEADER is the starting part of the packet.
9293 MEMADDR is the address in the remote memory space.
9294 MYADDR is the address of the buffer in our space.
9295 LEN_UNITS is the number of addressable units to write.
9296 UNIT_SIZE is the length in bytes of an addressable unit.
9297 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
9298 should send data as binary ('X'), or hex-encoded ('M').
9300 The function creates packet of the form
9301 <HEADER><ADDRESS>,<LENGTH>:<DATA>
9303 where encoding of <DATA> is terminated by PACKET_FORMAT.
9305 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
9308 Return the transferred status, error or OK (an
9309 'enum target_xfer_status' value). Save the number of addressable units
9310 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
9312 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
9313 exchange between gdb and the stub could look like (?? in place of the
9319 -> $M1000,3:eeeeffffeeee#??
9323 <- eeeeffffeeeedddd */
9326 remote_target::remote_write_bytes_aux (const char *header
, CORE_ADDR memaddr
,
9327 const gdb_byte
*myaddr
,
9330 ULONGEST
*xfered_len_units
,
9331 char packet_format
, int use_length
)
9333 struct remote_state
*rs
= get_remote_state ();
9339 int payload_capacity_bytes
;
9340 int payload_length_bytes
;
9342 if (packet_format
!= 'X' && packet_format
!= 'M')
9343 internal_error (_("remote_write_bytes_aux: bad packet format"));
9346 return TARGET_XFER_EOF
;
9348 payload_capacity_bytes
= get_memory_write_packet_size ();
9350 /* The packet buffer will be large enough for the payload;
9351 get_memory_packet_size ensures this. */
9354 /* Compute the size of the actual payload by subtracting out the
9355 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
9357 payload_capacity_bytes
-= strlen ("$,:#NN");
9359 /* The comma won't be used. */
9360 payload_capacity_bytes
+= 1;
9361 payload_capacity_bytes
-= strlen (header
);
9362 payload_capacity_bytes
-= hexnumlen (memaddr
);
9364 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
9366 strcat (rs
->buf
.data (), header
);
9367 p
= rs
->buf
.data () + strlen (header
);
9369 /* Compute a best guess of the number of bytes actually transfered. */
9370 if (packet_format
== 'X')
9372 /* Best guess at number of bytes that will fit. */
9373 todo_units
= std::min (len_units
,
9374 (ULONGEST
) payload_capacity_bytes
/ unit_size
);
9376 payload_capacity_bytes
-= hexnumlen (todo_units
);
9377 todo_units
= std::min (todo_units
, payload_capacity_bytes
/ unit_size
);
9381 /* Number of bytes that will fit. */
9383 = std::min (len_units
,
9384 (ULONGEST
) (payload_capacity_bytes
/ unit_size
) / 2);
9386 payload_capacity_bytes
-= hexnumlen (todo_units
);
9387 todo_units
= std::min (todo_units
,
9388 (payload_capacity_bytes
/ unit_size
) / 2);
9391 if (todo_units
<= 0)
9392 internal_error (_("minimum packet size too small to write data"));
9394 /* If we already need another packet, then try to align the end
9395 of this packet to a useful boundary. */
9396 if (todo_units
> 2 * REMOTE_ALIGN_WRITES
&& todo_units
< len_units
)
9397 todo_units
= align_for_efficient_write (todo_units
, memaddr
);
9399 /* Append "<memaddr>". */
9400 memaddr
= remote_address_masked (memaddr
);
9401 p
+= hexnumstr (p
, (ULONGEST
) memaddr
);
9408 /* Append the length and retain its location and size. It may need to be
9409 adjusted once the packet body has been created. */
9411 plenlen
= hexnumstr (p
, (ULONGEST
) todo_units
);
9419 /* Append the packet body. */
9420 if (packet_format
== 'X')
9422 /* Binary mode. Send target system values byte by byte, in
9423 increasing byte addresses. Only escape certain critical
9425 payload_length_bytes
=
9426 remote_escape_output (myaddr
, todo_units
, unit_size
, (gdb_byte
*) p
,
9427 &units_written
, payload_capacity_bytes
);
9429 /* If not all TODO units fit, then we'll need another packet. Make
9430 a second try to keep the end of the packet aligned. Don't do
9431 this if the packet is tiny. */
9432 if (units_written
< todo_units
&& units_written
> 2 * REMOTE_ALIGN_WRITES
)
9436 new_todo_units
= align_for_efficient_write (units_written
, memaddr
);
9438 if (new_todo_units
!= units_written
)
9439 payload_length_bytes
=
9440 remote_escape_output (myaddr
, new_todo_units
, unit_size
,
9441 (gdb_byte
*) p
, &units_written
,
9442 payload_capacity_bytes
);
9445 p
+= payload_length_bytes
;
9446 if (use_length
&& units_written
< todo_units
)
9448 /* Escape chars have filled up the buffer prematurely,
9449 and we have actually sent fewer units than planned.
9450 Fix-up the length field of the packet. Use the same
9451 number of characters as before. */
9452 plen
+= hexnumnstr (plen
, (ULONGEST
) units_written
,
9454 *plen
= ':'; /* overwrite \0 from hexnumnstr() */
9459 /* Normal mode: Send target system values byte by byte, in
9460 increasing byte addresses. Each byte is encoded as a two hex
9462 p
+= 2 * bin2hex (myaddr
, p
, todo_units
* unit_size
);
9463 units_written
= todo_units
;
9466 putpkt_binary (rs
->buf
.data (), (int) (p
- rs
->buf
.data ()));
9469 if (rs
->buf
[0] == 'E')
9470 return TARGET_XFER_E_IO
;
9472 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
9473 send fewer units than we'd planned. */
9474 *xfered_len_units
= (ULONGEST
) units_written
;
9475 return (*xfered_len_units
!= 0) ? TARGET_XFER_OK
: TARGET_XFER_EOF
;
9478 /* Write memory data directly to the remote machine.
9479 This does not inform the data cache; the data cache uses this.
9480 MEMADDR is the address in the remote memory space.
9481 MYADDR is the address of the buffer in our space.
9482 LEN is the number of bytes.
9484 Return the transferred status, error or OK (an
9485 'enum target_xfer_status' value). Save the number of bytes
9486 transferred in *XFERED_LEN. Only transfer a single packet. */
9489 remote_target::remote_write_bytes (CORE_ADDR memaddr
, const gdb_byte
*myaddr
,
9490 ULONGEST len
, int unit_size
,
9491 ULONGEST
*xfered_len
)
9493 const char *packet_format
= NULL
;
9495 /* Check whether the target supports binary download. */
9496 check_binary_download (memaddr
);
9498 switch (m_features
.packet_support (PACKET_X
))
9501 packet_format
= "X";
9503 case PACKET_DISABLE
:
9504 packet_format
= "M";
9506 case PACKET_SUPPORT_UNKNOWN
:
9507 internal_error (_("remote_write_bytes: bad internal state"));
9509 internal_error (_("bad switch"));
9512 return remote_write_bytes_aux (packet_format
,
9513 memaddr
, myaddr
, len
, unit_size
, xfered_len
,
9514 packet_format
[0], 1);
9517 /* Read memory data directly from the remote machine.
9518 This does not use the data cache; the data cache uses this.
9519 MEMADDR is the address in the remote memory space.
9520 MYADDR is the address of the buffer in our space.
9521 LEN_UNITS is the number of addressable memory units to read..
9522 UNIT_SIZE is the length in bytes of an addressable unit.
9524 Return the transferred status, error or OK (an
9525 'enum target_xfer_status' value). Save the number of bytes
9526 transferred in *XFERED_LEN_UNITS.
9528 See the comment of remote_write_bytes_aux for an example of
9529 memory read/write exchange between gdb and the stub. */
9532 remote_target::remote_read_bytes_1 (CORE_ADDR memaddr
, gdb_byte
*myaddr
,
9534 int unit_size
, ULONGEST
*xfered_len_units
)
9536 struct remote_state
*rs
= get_remote_state ();
9537 int buf_size_bytes
; /* Max size of packet output buffer. */
9542 buf_size_bytes
= get_memory_read_packet_size ();
9543 /* The packet buffer will be large enough for the payload;
9544 get_memory_packet_size ensures this. */
9546 /* Number of units that will fit. */
9547 todo_units
= std::min (len_units
,
9548 (ULONGEST
) (buf_size_bytes
/ unit_size
) / 2);
9550 /* Construct "m"<memaddr>","<len>". */
9551 memaddr
= remote_address_masked (memaddr
);
9552 p
= rs
->buf
.data ();
9554 p
+= hexnumstr (p
, (ULONGEST
) memaddr
);
9556 p
+= hexnumstr (p
, (ULONGEST
) todo_units
);
9560 if (rs
->buf
[0] == 'E'
9561 && isxdigit (rs
->buf
[1]) && isxdigit (rs
->buf
[2])
9562 && rs
->buf
[3] == '\0')
9563 return TARGET_XFER_E_IO
;
9564 /* Reply describes memory byte by byte, each byte encoded as two hex
9566 p
= rs
->buf
.data ();
9567 decoded_bytes
= hex2bin (p
, myaddr
, todo_units
* unit_size
);
9568 /* Return what we have. Let higher layers handle partial reads. */
9569 *xfered_len_units
= (ULONGEST
) (decoded_bytes
/ unit_size
);
9570 return (*xfered_len_units
!= 0) ? TARGET_XFER_OK
: TARGET_XFER_EOF
;
9573 /* Using the set of read-only target sections of remote, read live
9576 For interface/parameters/return description see target.h,
9580 remote_target::remote_xfer_live_readonly_partial (gdb_byte
*readbuf
,
9584 ULONGEST
*xfered_len
)
9586 const struct target_section
*secp
;
9588 secp
= target_section_by_addr (this, memaddr
);
9590 && (bfd_section_flags (secp
->the_bfd_section
) & SEC_READONLY
))
9592 ULONGEST memend
= memaddr
+ len
;
9594 const std::vector
<target_section
> *table
9595 = target_get_section_table (this);
9596 for (const target_section
&p
: *table
)
9598 if (memaddr
>= p
.addr
)
9600 if (memend
<= p
.endaddr
)
9602 /* Entire transfer is within this section. */
9603 return remote_read_bytes_1 (memaddr
, readbuf
, len
, unit_size
,
9606 else if (memaddr
>= p
.endaddr
)
9608 /* This section ends before the transfer starts. */
9613 /* This section overlaps the transfer. Just do half. */
9614 len
= p
.endaddr
- memaddr
;
9615 return remote_read_bytes_1 (memaddr
, readbuf
, len
, unit_size
,
9622 return TARGET_XFER_EOF
;
9625 /* Similar to remote_read_bytes_1, but it reads from the remote stub
9626 first if the requested memory is unavailable in traceframe.
9627 Otherwise, fall back to remote_read_bytes_1. */
9630 remote_target::remote_read_bytes (CORE_ADDR memaddr
,
9631 gdb_byte
*myaddr
, ULONGEST len
, int unit_size
,
9632 ULONGEST
*xfered_len
)
9635 return TARGET_XFER_EOF
;
9637 if (get_traceframe_number () != -1)
9639 std::vector
<mem_range
> available
;
9641 /* If we fail to get the set of available memory, then the
9642 target does not support querying traceframe info, and so we
9643 attempt reading from the traceframe anyway (assuming the
9644 target implements the old QTro packet then). */
9645 if (traceframe_available_memory (&available
, memaddr
, len
))
9647 if (available
.empty () || available
[0].start
!= memaddr
)
9649 enum target_xfer_status res
;
9651 /* Don't read into the traceframe's available
9653 if (!available
.empty ())
9655 LONGEST oldlen
= len
;
9657 len
= available
[0].start
- memaddr
;
9658 gdb_assert (len
<= oldlen
);
9661 /* This goes through the topmost target again. */
9662 res
= remote_xfer_live_readonly_partial (myaddr
, memaddr
,
9663 len
, unit_size
, xfered_len
);
9664 if (res
== TARGET_XFER_OK
)
9665 return TARGET_XFER_OK
;
9668 /* No use trying further, we know some memory starting
9669 at MEMADDR isn't available. */
9671 return (*xfered_len
!= 0) ?
9672 TARGET_XFER_UNAVAILABLE
: TARGET_XFER_EOF
;
9676 /* Don't try to read more than how much is available, in
9677 case the target implements the deprecated QTro packet to
9678 cater for older GDBs (the target's knowledge of read-only
9679 sections may be outdated by now). */
9680 len
= available
[0].length
;
9684 return remote_read_bytes_1 (memaddr
, myaddr
, len
, unit_size
, xfered_len
);
9689 /* Sends a packet with content determined by the printf format string
9690 FORMAT and the remaining arguments, then gets the reply. Returns
9691 whether the packet was a success, a failure, or unknown. */
9694 remote_target::remote_send_printf (const char *format
, ...)
9696 struct remote_state
*rs
= get_remote_state ();
9697 int max_size
= get_remote_packet_size ();
9700 va_start (ap
, format
);
9703 int size
= vsnprintf (rs
->buf
.data (), max_size
, format
, ap
);
9707 if (size
>= max_size
)
9708 internal_error (_("Too long remote packet."));
9710 if (putpkt (rs
->buf
) < 0)
9711 error (_("Communication problem with target."));
9716 return packet_check_result (rs
->buf
);
9719 /* Flash writing can take quite some time. We'll set
9720 effectively infinite timeout for flash operations.
9721 In future, we'll need to decide on a better approach. */
9722 static const int remote_flash_timeout
= 1000;
9725 remote_target::flash_erase (ULONGEST address
, LONGEST length
)
9727 int addr_size
= gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
9728 enum packet_result ret
;
9729 scoped_restore restore_timeout
9730 = make_scoped_restore (&remote_timeout
, remote_flash_timeout
);
9732 ret
= remote_send_printf ("vFlashErase:%s,%s",
9733 phex (address
, addr_size
),
9737 case PACKET_UNKNOWN
:
9738 error (_("Remote target does not support flash erase"));
9740 error (_("Error erasing flash with vFlashErase packet"));
9747 remote_target::remote_flash_write (ULONGEST address
,
9748 ULONGEST length
, ULONGEST
*xfered_len
,
9749 const gdb_byte
*data
)
9751 scoped_restore restore_timeout
9752 = make_scoped_restore (&remote_timeout
, remote_flash_timeout
);
9753 return remote_write_bytes_aux ("vFlashWrite:", address
, data
, length
, 1,
9758 remote_target::flash_done ()
9762 scoped_restore restore_timeout
9763 = make_scoped_restore (&remote_timeout
, remote_flash_timeout
);
9765 ret
= remote_send_printf ("vFlashDone");
9769 case PACKET_UNKNOWN
:
9770 error (_("Remote target does not support vFlashDone"));
9772 error (_("Error finishing flash operation"));
9779 /* Stuff for dealing with the packets which are part of this protocol.
9780 See comment at top of file for details. */
9782 /* Read a single character from the remote end. The current quit
9783 handler is overridden to avoid quitting in the middle of packet
9784 sequence, as that would break communication with the remote server.
9785 See remote_serial_quit_handler for more detail. */
9788 remote_target::readchar (int timeout
)
9791 struct remote_state
*rs
= get_remote_state ();
9795 scoped_restore restore_quit_target
9796 = make_scoped_restore (&curr_quit_handler_target
, this);
9797 scoped_restore restore_quit
9798 = make_scoped_restore (&quit_handler
, ::remote_serial_quit_handler
);
9800 rs
->got_ctrlc_during_io
= 0;
9802 ch
= serial_readchar (rs
->remote_desc
, timeout
);
9804 if (rs
->got_ctrlc_during_io
)
9807 catch (const gdb_exception_error
&ex
)
9809 remote_unpush_target (this);
9810 throw_error (TARGET_CLOSE_ERROR
,
9811 _("Remote communication error. "
9812 "Target disconnected: %s"),
9819 if (ch
== SERIAL_EOF
)
9821 remote_unpush_target (this);
9822 throw_error (TARGET_CLOSE_ERROR
, _("Remote connection closed"));
9828 /* Wrapper for serial_write that closes the target and throws if
9829 writing fails. The current quit handler is overridden to avoid
9830 quitting in the middle of packet sequence, as that would break
9831 communication with the remote server. See
9832 remote_serial_quit_handler for more detail. */
9835 remote_target::remote_serial_write (const char *str
, int len
)
9837 struct remote_state
*rs
= get_remote_state ();
9839 scoped_restore restore_quit_target
9840 = make_scoped_restore (&curr_quit_handler_target
, this);
9841 scoped_restore restore_quit
9842 = make_scoped_restore (&quit_handler
, ::remote_serial_quit_handler
);
9844 rs
->got_ctrlc_during_io
= 0;
9848 serial_write (rs
->remote_desc
, str
, len
);
9850 catch (const gdb_exception_error
&ex
)
9852 remote_unpush_target (this);
9853 throw_error (TARGET_CLOSE_ERROR
,
9854 _("Remote communication error. "
9855 "Target disconnected: %s"),
9859 if (rs
->got_ctrlc_during_io
)
9864 remote_target::remote_serial_send_break ()
9866 struct remote_state
*rs
= get_remote_state ();
9870 serial_send_break (rs
->remote_desc
);
9872 catch (const gdb_exception_error
&ex
)
9874 remote_unpush_target (this);
9875 throw_error (TARGET_CLOSE_ERROR
,
9876 _("Remote communication error. "
9877 "Target disconnected: %s"),
9882 /* Return a string representing an escaped version of BUF, of len N.
9883 E.g. \n is converted to \\n, \t to \\t, etc. */
9886 escape_buffer (const char *buf
, int n
)
9890 stb
.putstrn (buf
, n
, '\\');
9891 return stb
.release ();
9895 remote_target::putpkt (const char *buf
)
9897 return putpkt_binary (buf
, strlen (buf
));
9900 /* Wrapper around remote_target::putpkt to avoid exporting
9904 putpkt (remote_target
*remote
, const char *buf
)
9906 return remote
->putpkt (buf
);
9909 /* Send a packet to the remote machine, with error checking. The data
9910 of the packet is in BUF. The string in BUF can be at most
9911 get_remote_packet_size () - 5 to account for the $, # and checksum,
9912 and for a possible /0 if we are debugging (remote_debug) and want
9913 to print the sent packet as a string. */
9916 remote_target::putpkt_binary (const char *buf
, int cnt
)
9918 struct remote_state
*rs
= get_remote_state ();
9920 unsigned char csum
= 0;
9921 gdb::def_vector
<char> data (cnt
+ 6);
9922 char *buf2
= data
.data ();
9928 /* Catch cases like trying to read memory or listing threads while
9929 we're waiting for a stop reply. The remote server wouldn't be
9930 ready to handle this request, so we'd hang and timeout. We don't
9931 have to worry about this in synchronous mode, because in that
9932 case it's not possible to issue a command while the target is
9933 running. This is not a problem in non-stop mode, because in that
9934 case, the stub is always ready to process serial input. */
9935 if (!target_is_non_stop_p ()
9936 && target_is_async_p ()
9937 && rs
->waiting_for_stop_reply
)
9939 error (_("Cannot execute this command while the target is running.\n"
9940 "Use the \"interrupt\" command to stop the target\n"
9941 "and then try again."));
9944 /* Copy the packet into buffer BUF2, encapsulating it
9945 and giving it a checksum. */
9950 for (i
= 0; i
< cnt
; i
++)
9956 *p
++ = tohex ((csum
>> 4) & 0xf);
9957 *p
++ = tohex (csum
& 0xf);
9959 /* Send it over and over until we get a positive ack. */
9967 int len
= (int) (p
- buf2
);
9970 if (remote_packet_max_chars
< 0)
9973 max_chars
= remote_packet_max_chars
;
9976 = escape_buffer (buf2
, std::min (len
, max_chars
));
9978 if (len
> max_chars
)
9979 remote_debug_printf_nofunc
9980 ("Sending packet: %s [%d bytes omitted]", str
.c_str (),
9983 remote_debug_printf_nofunc ("Sending packet: %s", str
.c_str ());
9985 remote_serial_write (buf2
, p
- buf2
);
9987 /* If this is a no acks version of the remote protocol, send the
9988 packet and move on. */
9992 /* Read until either a timeout occurs (-2) or '+' is read.
9993 Handle any notification that arrives in the mean time. */
9996 ch
= readchar (remote_timeout
);
10001 remote_debug_printf_nofunc ("Received Ack");
10004 remote_debug_printf_nofunc ("Received Nak");
10006 case SERIAL_TIMEOUT
:
10010 break; /* Retransmit buffer. */
10013 remote_debug_printf ("Packet instead of Ack, ignoring it");
10014 /* It's probably an old response sent because an ACK
10015 was lost. Gobble up the packet and ack it so it
10016 doesn't get retransmitted when we resend this
10019 remote_serial_write ("+", 1);
10020 continue; /* Now, go look for +. */
10027 /* If we got a notification, handle it, and go back to looking
10029 /* We've found the start of a notification. Now
10030 collect the data. */
10031 val
= read_frame (&rs
->buf
);
10034 remote_debug_printf_nofunc
10035 (" Notification received: %s",
10036 escape_buffer (rs
->buf
.data (), val
).c_str ());
10038 handle_notification (rs
->notif_state
, rs
->buf
.data ());
10039 /* We're in sync now, rewait for the ack. */
10043 remote_debug_printf_nofunc ("Junk: %c%s", ch
& 0177,
10048 remote_debug_printf_nofunc ("Junk: %c%s", ch
& 0177,
10052 break; /* Here to retransmit. */
10056 /* This is wrong. If doing a long backtrace, the user should be
10057 able to get out next time we call QUIT, without anything as
10058 violent as interrupt_query. If we want to provide a way out of
10059 here without getting to the next QUIT, it should be based on
10060 hitting ^C twice as in remote_wait. */
10064 interrupt_query ();
10072 /* Come here after finding the start of a frame when we expected an
10073 ack. Do our best to discard the rest of this packet. */
10076 remote_target::skip_frame ()
10082 c
= readchar (remote_timeout
);
10085 case SERIAL_TIMEOUT
:
10086 /* Nothing we can do. */
10089 /* Discard the two bytes of checksum and stop. */
10090 c
= readchar (remote_timeout
);
10092 c
= readchar (remote_timeout
);
10095 case '*': /* Run length encoding. */
10096 /* Discard the repeat count. */
10097 c
= readchar (remote_timeout
);
10102 /* A regular character. */
10108 /* Come here after finding the start of the frame. Collect the rest
10109 into *BUF, verifying the checksum, length, and handling run-length
10110 compression. NUL terminate the buffer. If there is not enough room,
10113 Returns -1 on error, number of characters in buffer (ignoring the
10114 trailing NULL) on success. (could be extended to return one of the
10115 SERIAL status indications). */
10118 remote_target::read_frame (gdb::char_vector
*buf_p
)
10120 unsigned char csum
;
10123 char *buf
= buf_p
->data ();
10124 struct remote_state
*rs
= get_remote_state ();
10131 c
= readchar (remote_timeout
);
10134 case SERIAL_TIMEOUT
:
10135 remote_debug_printf ("Timeout in mid-packet, retrying");
10139 remote_debug_printf ("Saw new packet start in middle of old one");
10140 return -1; /* Start a new packet, count retries. */
10144 unsigned char pktcsum
;
10150 check_0
= readchar (remote_timeout
);
10152 check_1
= readchar (remote_timeout
);
10154 if (check_0
== SERIAL_TIMEOUT
|| check_1
== SERIAL_TIMEOUT
)
10156 remote_debug_printf ("Timeout in checksum, retrying");
10159 else if (check_0
< 0 || check_1
< 0)
10161 remote_debug_printf ("Communication error in checksum");
10165 /* Don't recompute the checksum; with no ack packets we
10166 don't have any way to indicate a packet retransmission
10168 if (rs
->noack_mode
)
10171 pktcsum
= (fromhex (check_0
) << 4) | fromhex (check_1
);
10172 if (csum
== pktcsum
)
10175 remote_debug_printf
10176 ("Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s",
10177 pktcsum
, csum
, escape_buffer (buf
, bc
).c_str ());
10179 /* Number of characters in buffer ignoring trailing
10183 case '*': /* Run length encoding. */
10188 c
= readchar (remote_timeout
);
10190 repeat
= c
- ' ' + 3; /* Compute repeat count. */
10192 /* The character before ``*'' is repeated. */
10194 if (repeat
> 0 && repeat
<= 255 && bc
> 0)
10196 if (bc
+ repeat
- 1 >= buf_p
->size () - 1)
10198 /* Make some more room in the buffer. */
10199 buf_p
->resize (buf_p
->size () + repeat
);
10200 buf
= buf_p
->data ();
10203 memset (&buf
[bc
], buf
[bc
- 1], repeat
);
10209 gdb_printf (_("Invalid run length encoding: %s\n"), buf
);
10213 if (bc
>= buf_p
->size () - 1)
10215 /* Make some more room in the buffer. */
10216 buf_p
->resize (buf_p
->size () * 2);
10217 buf
= buf_p
->data ();
10227 /* Set this to the maximum number of seconds to wait instead of waiting forever
10228 in target_wait(). If this timer times out, then it generates an error and
10229 the command is aborted. This replaces most of the need for timeouts in the
10230 GDB test suite, and makes it possible to distinguish between a hung target
10231 and one with slow communications. */
10233 static int watchdog
= 0;
10235 show_watchdog (struct ui_file
*file
, int from_tty
,
10236 struct cmd_list_element
*c
, const char *value
)
10238 gdb_printf (file
, _("Watchdog timer is %s.\n"), value
);
10241 /* Read a packet from the remote machine, with error checking, and
10242 store it in *BUF. Resize *BUF if necessary to hold the result. If
10243 FOREVER, wait forever rather than timing out; this is used (in
10244 synchronous mode) to wait for a target that is is executing user
10245 code to stop. If FOREVER == false, this function is allowed to time
10246 out gracefully and return an indication of this to the caller.
10247 Otherwise return the number of bytes read. If IS_NOTIF is not
10248 NULL, then consider receiving a notification enough reason to
10249 return to the caller. In this case, *IS_NOTIF is an output boolean
10250 that indicates whether *BUF holds a notification or not (a regular
10254 remote_target::getpkt (gdb::char_vector
*buf
, bool forever
, bool *is_notif
)
10256 struct remote_state
*rs
= get_remote_state ();
10262 strcpy (buf
->data (), "timeout");
10265 timeout
= watchdog
> 0 ? watchdog
: -1;
10266 else if (is_notif
!= nullptr)
10267 timeout
= 0; /* There should already be a char in the buffer. If
10270 timeout
= remote_timeout
;
10272 #define MAX_TRIES 3
10274 /* Process any number of notifications, and then return when
10275 we get a packet. */
10278 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
10280 for (tries
= 1; tries
<= MAX_TRIES
; tries
++)
10282 /* This can loop forever if the remote side sends us
10283 characters continuously, but if it pauses, we'll get
10284 SERIAL_TIMEOUT from readchar because of timeout. Then
10285 we'll count that as a retry.
10287 Note that even when forever is set, we will only wait
10288 forever prior to the start of a packet. After that, we
10289 expect characters to arrive at a brisk pace. They should
10290 show up within remote_timeout intervals. */
10292 c
= readchar (timeout
);
10293 while (c
!= SERIAL_TIMEOUT
&& c
!= '$' && c
!= '%');
10295 if (c
== SERIAL_TIMEOUT
)
10297 if (is_notif
!= nullptr)
10298 return -1; /* Don't complain, it's normal to not get
10299 anything in this case. */
10301 if (forever
) /* Watchdog went off? Kill the target. */
10303 remote_unpush_target (this);
10304 throw_error (TARGET_CLOSE_ERROR
,
10305 _("Watchdog timeout has expired. "
10306 "Target detached."));
10309 remote_debug_printf ("Timed out.");
10313 /* We've found the start of a packet or notification.
10314 Now collect the data. */
10315 val
= read_frame (buf
);
10320 remote_serial_write ("-", 1);
10323 if (tries
> MAX_TRIES
)
10325 /* We have tried hard enough, and just can't receive the
10326 packet/notification. Give up. */
10327 gdb_printf (_("Ignoring packet error, continuing...\n"));
10329 /* Skip the ack char if we're in no-ack mode. */
10330 if (!rs
->noack_mode
)
10331 remote_serial_write ("+", 1);
10335 /* If we got an ordinary packet, return that to our caller. */
10342 if (remote_packet_max_chars
< 0)
10345 max_chars
= remote_packet_max_chars
;
10348 = escape_buffer (buf
->data (),
10349 std::min (val
, max_chars
));
10351 if (val
> max_chars
)
10352 remote_debug_printf_nofunc
10353 ("Packet received: %s [%d bytes omitted]", str
.c_str (),
10356 remote_debug_printf_nofunc ("Packet received: %s",
10360 /* Skip the ack char if we're in no-ack mode. */
10361 if (!rs
->noack_mode
)
10362 remote_serial_write ("+", 1);
10363 if (is_notif
!= NULL
)
10368 /* If we got a notification, handle it, and go back to looking
10372 gdb_assert (c
== '%');
10374 remote_debug_printf_nofunc
10375 (" Notification received: %s",
10376 escape_buffer (buf
->data (), val
).c_str ());
10378 if (is_notif
!= NULL
)
10381 handle_notification (rs
->notif_state
, buf
->data ());
10383 /* Notifications require no acknowledgement. */
10385 if (is_notif
!= nullptr)
10391 /* Kill any new fork children of inferior INF that haven't been
10392 processed by follow_fork. */
10395 remote_target::kill_new_fork_children (inferior
*inf
)
10397 remote_state
*rs
= get_remote_state ();
10398 const notif_client
*notif
= ¬if_client_stop
;
10400 /* Kill the fork child threads of any threads in inferior INF that are stopped
10401 at a fork event. */
10402 for (thread_info
*thread
: inf
->non_exited_threads ())
10404 const target_waitstatus
*ws
= thread_pending_fork_status (thread
);
10409 int child_pid
= ws
->child_ptid ().pid ();
10410 int res
= remote_vkill (child_pid
);
10413 error (_("Can't kill fork child process %d"), child_pid
);
10416 /* Check for any pending fork events (not reported or processed yet)
10417 in inferior INF and kill those fork child threads as well. */
10418 remote_notif_get_pending_events (notif
);
10419 for (auto &event
: rs
->stop_reply_queue
)
10421 if (event
->ptid
.pid () != inf
->pid
)
10424 if (!is_fork_status (event
->ws
.kind ()))
10427 int child_pid
= event
->ws
.child_ptid ().pid ();
10428 int res
= remote_vkill (child_pid
);
10431 error (_("Can't kill fork child process %d"), child_pid
);
10436 /* Target hook to kill the current inferior. */
10439 remote_target::kill ()
10442 inferior
*inf
= find_inferior_pid (this, inferior_ptid
.pid ());
10444 gdb_assert (inf
!= nullptr);
10446 if (m_features
.packet_support (PACKET_vKill
) != PACKET_DISABLE
)
10448 /* If we're stopped while forking and we haven't followed yet,
10449 kill the child task. We need to do this before killing the
10450 parent task because if this is a vfork then the parent will
10452 kill_new_fork_children (inf
);
10454 res
= remote_vkill (inf
->pid
);
10457 target_mourn_inferior (inferior_ptid
);
10462 /* If we are in 'target remote' mode and we are killing the only
10463 inferior, then we will tell gdbserver to exit and unpush the
10465 if (res
== -1 && !m_features
.remote_multi_process_p ()
10466 && number_of_live_inferiors (this) == 1)
10470 /* We've killed the remote end, we get to mourn it. If we are
10471 not in extended mode, mourning the inferior also unpushes
10472 remote_ops from the target stack, which closes the remote
10474 target_mourn_inferior (inferior_ptid
);
10479 error (_("Can't kill process"));
10482 /* Send a kill request to the target using the 'vKill' packet. */
10485 remote_target::remote_vkill (int pid
)
10487 if (m_features
.packet_support (PACKET_vKill
) == PACKET_DISABLE
)
10490 remote_state
*rs
= get_remote_state ();
10492 /* Tell the remote target to detach. */
10493 xsnprintf (rs
->buf
.data (), get_remote_packet_size (), "vKill;%x", pid
);
10497 switch (m_features
.packet_ok (rs
->buf
, PACKET_vKill
))
10503 case PACKET_UNKNOWN
:
10506 internal_error (_("Bad result from packet_ok"));
10510 /* Send a kill request to the target using the 'k' packet. */
10513 remote_target::remote_kill_k ()
10515 /* Catch errors so the user can quit from gdb even when we
10516 aren't on speaking terms with the remote system. */
10521 catch (const gdb_exception_error
&ex
)
10523 if (ex
.error
== TARGET_CLOSE_ERROR
)
10525 /* If we got an (EOF) error that caused the target
10526 to go away, then we're done, that's what we wanted.
10527 "k" is susceptible to cause a premature EOF, given
10528 that the remote server isn't actually required to
10529 reply to "k", and it can happen that it doesn't
10530 even get to reply ACK to the "k". */
10534 /* Otherwise, something went wrong. We didn't actually kill
10535 the target. Just propagate the exception, and let the
10536 user or higher layers decide what to do. */
10542 remote_target::mourn_inferior ()
10544 struct remote_state
*rs
= get_remote_state ();
10546 /* We're no longer interested in notification events of an inferior
10547 that exited or was killed/detached. */
10548 discard_pending_stop_replies (current_inferior ());
10550 /* In 'target remote' mode with one inferior, we close the connection. */
10551 if (!rs
->extended
&& number_of_live_inferiors (this) <= 1)
10553 remote_unpush_target (this);
10557 /* In case we got here due to an error, but we're going to stay
10559 rs
->waiting_for_stop_reply
= 0;
10561 /* If the current general thread belonged to the process we just
10562 detached from or has exited, the remote side current general
10563 thread becomes undefined. Considering a case like this:
10565 - We just got here due to a detach.
10566 - The process that we're detaching from happens to immediately
10567 report a global breakpoint being hit in non-stop mode, in the
10568 same thread we had selected before.
10569 - GDB attaches to this process again.
10570 - This event happens to be the next event we handle.
10572 GDB would consider that the current general thread didn't need to
10573 be set on the stub side (with Hg), since for all it knew,
10574 GENERAL_THREAD hadn't changed.
10576 Notice that although in all-stop mode, the remote server always
10577 sets the current thread to the thread reporting the stop event,
10578 that doesn't happen in non-stop mode; in non-stop, the stub *must
10579 not* change the current thread when reporting a breakpoint hit,
10580 due to the decoupling of event reporting and event handling.
10582 To keep things simple, we always invalidate our notion of the
10584 record_currthread (rs
, minus_one_ptid
);
10586 /* Call common code to mark the inferior as not running. */
10587 generic_mourn_inferior ();
10591 extended_remote_target::supports_disable_randomization ()
10593 return (m_features
.packet_support (PACKET_QDisableRandomization
)
10598 remote_target::extended_remote_disable_randomization (int val
)
10600 struct remote_state
*rs
= get_remote_state ();
10603 xsnprintf (rs
->buf
.data (), get_remote_packet_size (),
10604 "QDisableRandomization:%x", val
);
10606 reply
= remote_get_noisy_reply ();
10607 if (*reply
== '\0')
10608 error (_("Target does not support QDisableRandomization."));
10609 if (strcmp (reply
, "OK") != 0)
10610 error (_("Bogus QDisableRandomization reply from target: %s"), reply
);
10614 remote_target::extended_remote_run (const std::string
&args
)
10616 struct remote_state
*rs
= get_remote_state ();
10618 const char *remote_exec_file
= get_remote_exec_file ();
10620 /* If the user has disabled vRun support, or we have detected that
10621 support is not available, do not try it. */
10622 if (m_features
.packet_support (PACKET_vRun
) == PACKET_DISABLE
)
10625 strcpy (rs
->buf
.data (), "vRun;");
10626 len
= strlen (rs
->buf
.data ());
10628 if (strlen (remote_exec_file
) * 2 + len
>= get_remote_packet_size ())
10629 error (_("Remote file name too long for run packet"));
10630 len
+= 2 * bin2hex ((gdb_byte
*) remote_exec_file
, rs
->buf
.data () + len
,
10631 strlen (remote_exec_file
));
10633 if (!args
.empty ())
10637 gdb_argv
argv (args
.c_str ());
10638 for (i
= 0; argv
[i
] != NULL
; i
++)
10640 if (strlen (argv
[i
]) * 2 + 1 + len
>= get_remote_packet_size ())
10641 error (_("Argument list too long for run packet"));
10642 rs
->buf
[len
++] = ';';
10643 len
+= 2 * bin2hex ((gdb_byte
*) argv
[i
], rs
->buf
.data () + len
,
10648 rs
->buf
[len
++] = '\0';
10653 switch (m_features
.packet_ok (rs
->buf
, PACKET_vRun
))
10656 /* We have a wait response. All is well. */
10658 case PACKET_UNKNOWN
:
10661 if (remote_exec_file
[0] == '\0')
10662 error (_("Running the default executable on the remote target failed; "
10663 "try \"set remote exec-file\"?"));
10665 error (_("Running \"%s\" on the remote target failed"),
10668 gdb_assert_not_reached ("bad switch");
10672 /* Helper function to send set/unset environment packets. ACTION is
10673 either "set" or "unset". PACKET is either "QEnvironmentHexEncoded"
10674 or "QEnvironmentUnsetVariable". VALUE is the variable to be
10678 remote_target::send_environment_packet (const char *action
,
10679 const char *packet
,
10682 remote_state
*rs
= get_remote_state ();
10684 /* Convert the environment variable to an hex string, which
10685 is the best format to be transmitted over the wire. */
10686 std::string encoded_value
= bin2hex ((const gdb_byte
*) value
,
10689 xsnprintf (rs
->buf
.data (), get_remote_packet_size (),
10690 "%s:%s", packet
, encoded_value
.c_str ());
10694 if (strcmp (rs
->buf
.data (), "OK") != 0)
10695 warning (_("Unable to %s environment variable '%s' on remote."),
10699 /* Helper function to handle the QEnvironment* packets. */
10702 remote_target::extended_remote_environment_support ()
10704 remote_state
*rs
= get_remote_state ();
10706 if (m_features
.packet_support (PACKET_QEnvironmentReset
) != PACKET_DISABLE
)
10708 putpkt ("QEnvironmentReset");
10710 if (strcmp (rs
->buf
.data (), "OK") != 0)
10711 warning (_("Unable to reset environment on remote."));
10714 gdb_environ
*e
= ¤t_inferior ()->environment
;
10716 if (m_features
.packet_support (PACKET_QEnvironmentHexEncoded
)
10719 for (const std::string
&el
: e
->user_set_env ())
10720 send_environment_packet ("set", "QEnvironmentHexEncoded",
10725 if (m_features
.packet_support (PACKET_QEnvironmentUnset
) != PACKET_DISABLE
)
10726 for (const std::string
&el
: e
->user_unset_env ())
10727 send_environment_packet ("unset", "QEnvironmentUnset", el
.c_str ());
10730 /* Helper function to set the current working directory for the
10731 inferior in the remote target. */
10734 remote_target::extended_remote_set_inferior_cwd ()
10736 if (m_features
.packet_support (PACKET_QSetWorkingDir
) != PACKET_DISABLE
)
10738 const std::string
&inferior_cwd
= current_inferior ()->cwd ();
10739 remote_state
*rs
= get_remote_state ();
10741 if (!inferior_cwd
.empty ())
10743 std::string hexpath
10744 = bin2hex ((const gdb_byte
*) inferior_cwd
.data (),
10745 inferior_cwd
.size ());
10747 xsnprintf (rs
->buf
.data (), get_remote_packet_size (),
10748 "QSetWorkingDir:%s", hexpath
.c_str ());
10752 /* An empty inferior_cwd means that the user wants us to
10753 reset the remote server's inferior's cwd. */
10754 xsnprintf (rs
->buf
.data (), get_remote_packet_size (),
10755 "QSetWorkingDir:");
10760 if (m_features
.packet_ok (rs
->buf
, PACKET_QSetWorkingDir
) != PACKET_OK
)
10762 Remote replied unexpectedly while setting the inferior's working\n\
10769 /* In the extended protocol we want to be able to do things like
10770 "run" and have them basically work as expected. So we need
10771 a special create_inferior function. We support changing the
10772 executable file and the command line arguments, but not the
10776 extended_remote_target::create_inferior (const char *exec_file
,
10777 const std::string
&args
,
10778 char **env
, int from_tty
)
10782 struct remote_state
*rs
= get_remote_state ();
10783 const char *remote_exec_file
= get_remote_exec_file ();
10785 /* If running asynchronously, register the target file descriptor
10786 with the event loop. */
10787 if (target_can_async_p ())
10788 target_async (true);
10790 /* Disable address space randomization if requested (and supported). */
10791 if (supports_disable_randomization ())
10792 extended_remote_disable_randomization (disable_randomization
);
10794 /* If startup-with-shell is on, we inform gdbserver to start the
10795 remote inferior using a shell. */
10796 if (m_features
.packet_support (PACKET_QStartupWithShell
) != PACKET_DISABLE
)
10798 xsnprintf (rs
->buf
.data (), get_remote_packet_size (),
10799 "QStartupWithShell:%d", startup_with_shell
? 1 : 0);
10802 if (strcmp (rs
->buf
.data (), "OK") != 0)
10804 Remote replied unexpectedly while setting startup-with-shell: %s"),
10808 extended_remote_environment_support ();
10810 extended_remote_set_inferior_cwd ();
10812 /* Now restart the remote server. */
10813 run_worked
= extended_remote_run (args
) != -1;
10816 /* vRun was not supported. Fail if we need it to do what the
10818 if (remote_exec_file
[0])
10819 error (_("Remote target does not support \"set remote exec-file\""));
10820 if (!args
.empty ())
10821 error (_("Remote target does not support \"set args\" or run ARGS"));
10823 /* Fall back to "R". */
10824 extended_remote_restart ();
10827 /* vRun's success return is a stop reply. */
10828 stop_reply
= run_worked
? rs
->buf
.data () : NULL
;
10829 add_current_inferior_and_thread (stop_reply
);
10831 /* Get updated offsets, if the stub uses qOffsets. */
10836 /* Given a location's target info BP_TGT and the packet buffer BUF, output
10837 the list of conditions (in agent expression bytecode format), if any, the
10838 target needs to evaluate. The output is placed into the packet buffer
10839 started from BUF and ended at BUF_END. */
10842 remote_add_target_side_condition (struct gdbarch
*gdbarch
,
10843 struct bp_target_info
*bp_tgt
, char *buf
,
10846 if (bp_tgt
->conditions
.empty ())
10849 buf
+= strlen (buf
);
10850 xsnprintf (buf
, buf_end
- buf
, "%s", ";");
10853 /* Send conditions to the target. */
10854 for (agent_expr
*aexpr
: bp_tgt
->conditions
)
10856 xsnprintf (buf
, buf_end
- buf
, "X%x,", (int) aexpr
->buf
.size ());
10857 buf
+= strlen (buf
);
10858 for (int i
= 0; i
< aexpr
->buf
.size (); ++i
)
10859 buf
= pack_hex_byte (buf
, aexpr
->buf
[i
]);
10866 remote_add_target_side_commands (struct gdbarch
*gdbarch
,
10867 struct bp_target_info
*bp_tgt
, char *buf
)
10869 if (bp_tgt
->tcommands
.empty ())
10872 buf
+= strlen (buf
);
10874 sprintf (buf
, ";cmds:%x,", bp_tgt
->persist
);
10875 buf
+= strlen (buf
);
10877 /* Concatenate all the agent expressions that are commands into the
10879 for (agent_expr
*aexpr
: bp_tgt
->tcommands
)
10881 sprintf (buf
, "X%x,", (int) aexpr
->buf
.size ());
10882 buf
+= strlen (buf
);
10883 for (int i
= 0; i
< aexpr
->buf
.size (); ++i
)
10884 buf
= pack_hex_byte (buf
, aexpr
->buf
[i
]);
10889 /* Insert a breakpoint. On targets that have software breakpoint
10890 support, we ask the remote target to do the work; on targets
10891 which don't, we insert a traditional memory breakpoint. */
10894 remote_target::insert_breakpoint (struct gdbarch
*gdbarch
,
10895 struct bp_target_info
*bp_tgt
)
10897 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
10898 If it succeeds, then set the support to PACKET_ENABLE. If it
10899 fails, and the user has explicitly requested the Z support then
10900 report an error, otherwise, mark it disabled and go on. */
10902 if (m_features
.packet_support (PACKET_Z0
) != PACKET_DISABLE
)
10904 CORE_ADDR addr
= bp_tgt
->reqstd_address
;
10905 struct remote_state
*rs
;
10908 /* Make sure the remote is pointing at the right process, if
10910 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
10911 set_general_process ();
10913 rs
= get_remote_state ();
10914 p
= rs
->buf
.data ();
10915 endbuf
= p
+ get_remote_packet_size ();
10920 addr
= (ULONGEST
) remote_address_masked (addr
);
10921 p
+= hexnumstr (p
, addr
);
10922 xsnprintf (p
, endbuf
- p
, ",%d", bp_tgt
->kind
);
10924 if (supports_evaluation_of_breakpoint_conditions ())
10925 remote_add_target_side_condition (gdbarch
, bp_tgt
, p
, endbuf
);
10927 if (can_run_breakpoint_commands ())
10928 remote_add_target_side_commands (gdbarch
, bp_tgt
, p
);
10933 switch (m_features
.packet_ok (rs
->buf
, PACKET_Z0
))
10939 case PACKET_UNKNOWN
:
10944 /* If this breakpoint has target-side commands but this stub doesn't
10945 support Z0 packets, throw error. */
10946 if (!bp_tgt
->tcommands
.empty ())
10947 throw_error (NOT_SUPPORTED_ERROR
, _("\
10948 Target doesn't support breakpoints that have target side commands."));
10950 return memory_insert_breakpoint (this, gdbarch
, bp_tgt
);
10954 remote_target::remove_breakpoint (struct gdbarch
*gdbarch
,
10955 struct bp_target_info
*bp_tgt
,
10956 enum remove_bp_reason reason
)
10958 CORE_ADDR addr
= bp_tgt
->placed_address
;
10959 struct remote_state
*rs
= get_remote_state ();
10961 if (m_features
.packet_support (PACKET_Z0
) != PACKET_DISABLE
)
10963 char *p
= rs
->buf
.data ();
10964 char *endbuf
= p
+ get_remote_packet_size ();
10966 /* Make sure the remote is pointing at the right process, if
10968 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
10969 set_general_process ();
10975 addr
= (ULONGEST
) remote_address_masked (bp_tgt
->placed_address
);
10976 p
+= hexnumstr (p
, addr
);
10977 xsnprintf (p
, endbuf
- p
, ",%d", bp_tgt
->kind
);
10982 return (rs
->buf
[0] == 'E');
10985 return memory_remove_breakpoint (this, gdbarch
, bp_tgt
, reason
);
10988 static enum Z_packet_type
10989 watchpoint_to_Z_packet (int type
)
10994 return Z_PACKET_WRITE_WP
;
10997 return Z_PACKET_READ_WP
;
11000 return Z_PACKET_ACCESS_WP
;
11003 internal_error (_("hw_bp_to_z: bad watchpoint type %d"), type
);
11008 remote_target::insert_watchpoint (CORE_ADDR addr
, int len
,
11009 enum target_hw_bp_type type
, struct expression
*cond
)
11011 struct remote_state
*rs
= get_remote_state ();
11012 char *endbuf
= rs
->buf
.data () + get_remote_packet_size ();
11014 enum Z_packet_type packet
= watchpoint_to_Z_packet (type
);
11016 if (m_features
.packet_support ((to_underlying (PACKET_Z0
)
11017 + to_underlying (packet
))) == PACKET_DISABLE
)
11020 /* Make sure the remote is pointing at the right process, if
11022 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
11023 set_general_process ();
11025 xsnprintf (rs
->buf
.data (), endbuf
- rs
->buf
.data (), "Z%x,", packet
);
11026 p
= strchr (rs
->buf
.data (), '\0');
11027 addr
= remote_address_masked (addr
);
11028 p
+= hexnumstr (p
, (ULONGEST
) addr
);
11029 xsnprintf (p
, endbuf
- p
, ",%x", len
);
11034 switch (m_features
.packet_ok (rs
->buf
, (to_underlying (PACKET_Z0
)
11035 + to_underlying (packet
))))
11039 case PACKET_UNKNOWN
:
11044 internal_error (_("remote_insert_watchpoint: reached end of function"));
11048 remote_target::watchpoint_addr_within_range (CORE_ADDR addr
,
11049 CORE_ADDR start
, int length
)
11051 CORE_ADDR diff
= remote_address_masked (addr
- start
);
11053 return diff
< length
;
11058 remote_target::remove_watchpoint (CORE_ADDR addr
, int len
,
11059 enum target_hw_bp_type type
, struct expression
*cond
)
11061 struct remote_state
*rs
= get_remote_state ();
11062 char *endbuf
= rs
->buf
.data () + get_remote_packet_size ();
11064 enum Z_packet_type packet
= watchpoint_to_Z_packet (type
);
11066 if (m_features
.packet_support ((to_underlying (PACKET_Z0
)
11067 + to_underlying (packet
))) == PACKET_DISABLE
)
11070 /* Make sure the remote is pointing at the right process, if
11072 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
11073 set_general_process ();
11075 xsnprintf (rs
->buf
.data (), endbuf
- rs
->buf
.data (), "z%x,", packet
);
11076 p
= strchr (rs
->buf
.data (), '\0');
11077 addr
= remote_address_masked (addr
);
11078 p
+= hexnumstr (p
, (ULONGEST
) addr
);
11079 xsnprintf (p
, endbuf
- p
, ",%x", len
);
11083 switch (m_features
.packet_ok (rs
->buf
, (to_underlying (PACKET_Z0
)
11084 + to_underlying (packet
))))
11087 case PACKET_UNKNOWN
:
11092 internal_error (_("remote_remove_watchpoint: reached end of function"));
11096 static int remote_hw_watchpoint_limit
= -1;
11097 static int remote_hw_watchpoint_length_limit
= -1;
11098 static int remote_hw_breakpoint_limit
= -1;
11101 remote_target::region_ok_for_hw_watchpoint (CORE_ADDR addr
, int len
)
11103 if (remote_hw_watchpoint_length_limit
== 0)
11105 else if (remote_hw_watchpoint_length_limit
< 0)
11107 else if (len
<= remote_hw_watchpoint_length_limit
)
11114 remote_target::can_use_hw_breakpoint (enum bptype type
, int cnt
, int ot
)
11116 if (type
== bp_hardware_breakpoint
)
11118 if (remote_hw_breakpoint_limit
== 0)
11120 else if (remote_hw_breakpoint_limit
< 0)
11122 else if (cnt
<= remote_hw_breakpoint_limit
)
11127 if (remote_hw_watchpoint_limit
== 0)
11129 else if (remote_hw_watchpoint_limit
< 0)
11133 else if (cnt
<= remote_hw_watchpoint_limit
)
11139 /* The to_stopped_by_sw_breakpoint method of target remote. */
11142 remote_target::stopped_by_sw_breakpoint ()
11144 struct thread_info
*thread
= inferior_thread ();
11146 return (thread
->priv
!= NULL
11147 && (get_remote_thread_info (thread
)->stop_reason
11148 == TARGET_STOPPED_BY_SW_BREAKPOINT
));
11151 /* The to_supports_stopped_by_sw_breakpoint method of target
11155 remote_target::supports_stopped_by_sw_breakpoint ()
11157 return (m_features
.packet_support (PACKET_swbreak_feature
) == PACKET_ENABLE
);
11160 /* The to_stopped_by_hw_breakpoint method of target remote. */
11163 remote_target::stopped_by_hw_breakpoint ()
11165 struct thread_info
*thread
= inferior_thread ();
11167 return (thread
->priv
!= NULL
11168 && (get_remote_thread_info (thread
)->stop_reason
11169 == TARGET_STOPPED_BY_HW_BREAKPOINT
));
11172 /* The to_supports_stopped_by_hw_breakpoint method of target
11176 remote_target::supports_stopped_by_hw_breakpoint ()
11178 return (m_features
.packet_support (PACKET_hwbreak_feature
) == PACKET_ENABLE
);
11182 remote_target::stopped_by_watchpoint ()
11184 struct thread_info
*thread
= inferior_thread ();
11186 return (thread
->priv
!= NULL
11187 && (get_remote_thread_info (thread
)->stop_reason
11188 == TARGET_STOPPED_BY_WATCHPOINT
));
11192 remote_target::stopped_data_address (CORE_ADDR
*addr_p
)
11194 struct thread_info
*thread
= inferior_thread ();
11196 if (thread
->priv
!= NULL
11197 && (get_remote_thread_info (thread
)->stop_reason
11198 == TARGET_STOPPED_BY_WATCHPOINT
))
11200 *addr_p
= get_remote_thread_info (thread
)->watch_data_address
;
11209 remote_target::insert_hw_breakpoint (struct gdbarch
*gdbarch
,
11210 struct bp_target_info
*bp_tgt
)
11212 CORE_ADDR addr
= bp_tgt
->reqstd_address
;
11213 struct remote_state
*rs
;
11217 if (m_features
.packet_support (PACKET_Z1
) == PACKET_DISABLE
)
11220 /* Make sure the remote is pointing at the right process, if
11222 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
11223 set_general_process ();
11225 rs
= get_remote_state ();
11226 p
= rs
->buf
.data ();
11227 endbuf
= p
+ get_remote_packet_size ();
11233 addr
= remote_address_masked (addr
);
11234 p
+= hexnumstr (p
, (ULONGEST
) addr
);
11235 xsnprintf (p
, endbuf
- p
, ",%x", bp_tgt
->kind
);
11237 if (supports_evaluation_of_breakpoint_conditions ())
11238 remote_add_target_side_condition (gdbarch
, bp_tgt
, p
, endbuf
);
11240 if (can_run_breakpoint_commands ())
11241 remote_add_target_side_commands (gdbarch
, bp_tgt
, p
);
11246 switch (m_features
.packet_ok (rs
->buf
, PACKET_Z1
))
11249 if (rs
->buf
[1] == '.')
11251 message
= strchr (&rs
->buf
[2], '.');
11253 error (_("Remote failure reply: %s"), message
+ 1);
11256 case PACKET_UNKNOWN
:
11261 internal_error (_("remote_insert_hw_breakpoint: reached end of function"));
11266 remote_target::remove_hw_breakpoint (struct gdbarch
*gdbarch
,
11267 struct bp_target_info
*bp_tgt
)
11270 struct remote_state
*rs
= get_remote_state ();
11271 char *p
= rs
->buf
.data ();
11272 char *endbuf
= p
+ get_remote_packet_size ();
11274 if (m_features
.packet_support (PACKET_Z1
) == PACKET_DISABLE
)
11277 /* Make sure the remote is pointing at the right process, if
11279 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
11280 set_general_process ();
11286 addr
= remote_address_masked (bp_tgt
->placed_address
);
11287 p
+= hexnumstr (p
, (ULONGEST
) addr
);
11288 xsnprintf (p
, endbuf
- p
, ",%x", bp_tgt
->kind
);
11293 switch (m_features
.packet_ok (rs
->buf
, PACKET_Z1
))
11296 case PACKET_UNKNOWN
:
11301 internal_error (_("remote_remove_hw_breakpoint: reached end of function"));
11304 /* Verify memory using the "qCRC:" request. */
11307 remote_target::verify_memory (const gdb_byte
*data
, CORE_ADDR lma
, ULONGEST size
)
11309 struct remote_state
*rs
= get_remote_state ();
11310 unsigned long host_crc
, target_crc
;
11313 /* It doesn't make sense to use qCRC if the remote target is
11314 connected but not running. */
11315 if (target_has_execution ()
11316 && m_features
.packet_support (PACKET_qCRC
) != PACKET_DISABLE
)
11318 enum packet_result result
;
11320 /* Make sure the remote is pointing at the right process. */
11321 set_general_process ();
11323 /* FIXME: assumes lma can fit into long. */
11324 xsnprintf (rs
->buf
.data (), get_remote_packet_size (), "qCRC:%lx,%lx",
11325 (long) lma
, (long) size
);
11328 /* Be clever; compute the host_crc before waiting for target
11330 host_crc
= xcrc32 (data
, size
, 0xffffffff);
11334 result
= m_features
.packet_ok (rs
->buf
, PACKET_qCRC
);
11335 if (result
== PACKET_ERROR
)
11337 else if (result
== PACKET_OK
)
11339 for (target_crc
= 0, tmp
= &rs
->buf
[1]; *tmp
; tmp
++)
11340 target_crc
= target_crc
* 16 + fromhex (*tmp
);
11342 return (host_crc
== target_crc
);
11346 return simple_verify_memory (this, data
, lma
, size
);
11349 /* compare-sections command
11351 With no arguments, compares each loadable section in the exec bfd
11352 with the same memory range on the target, and reports mismatches.
11353 Useful for verifying the image on the target against the exec file. */
11356 compare_sections_command (const char *args
, int from_tty
)
11359 const char *sectname
;
11360 bfd_size_type size
;
11363 int mismatched
= 0;
11367 if (!current_program_space
->exec_bfd ())
11368 error (_("command cannot be used without an exec file"));
11370 if (args
!= NULL
&& strcmp (args
, "-r") == 0)
11376 for (s
= current_program_space
->exec_bfd ()->sections
; s
; s
= s
->next
)
11378 if (!(s
->flags
& SEC_LOAD
))
11379 continue; /* Skip non-loadable section. */
11381 if (read_only
&& (s
->flags
& SEC_READONLY
) == 0)
11382 continue; /* Skip writeable sections */
11384 size
= bfd_section_size (s
);
11386 continue; /* Skip zero-length section. */
11388 sectname
= bfd_section_name (s
);
11389 if (args
&& strcmp (args
, sectname
) != 0)
11390 continue; /* Not the section selected by user. */
11392 matched
= 1; /* Do this section. */
11395 gdb::byte_vector
sectdata (size
);
11396 bfd_get_section_contents (current_program_space
->exec_bfd (), s
,
11397 sectdata
.data (), 0, size
);
11399 res
= target_verify_memory (sectdata
.data (), lma
, size
);
11402 error (_("target memory fault, section %s, range %s -- %s"), sectname
,
11403 paddress (current_inferior ()->arch (), lma
),
11404 paddress (current_inferior ()->arch (), lma
+ size
));
11406 gdb_printf ("Section %s, range %s -- %s: ", sectname
,
11407 paddress (current_inferior ()->arch (), lma
),
11408 paddress (current_inferior ()->arch (), lma
+ size
));
11410 gdb_printf ("matched.\n");
11413 gdb_printf ("MIS-MATCHED!\n");
11417 if (mismatched
> 0)
11418 warning (_("One or more sections of the target image does "
11419 "not match the loaded file"));
11420 if (args
&& !matched
)
11421 gdb_printf (_("No loaded section named '%s'.\n"), args
);
11424 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
11425 into remote target. The number of bytes written to the remote
11426 target is returned, or -1 for error. */
11429 remote_target::remote_write_qxfer (const char *object_name
,
11430 const char *annex
, const gdb_byte
*writebuf
,
11431 ULONGEST offset
, LONGEST len
,
11432 ULONGEST
*xfered_len
,
11433 const unsigned int which_packet
)
11437 struct remote_state
*rs
= get_remote_state ();
11438 int max_size
= get_memory_write_packet_size ();
11440 if (m_features
.packet_support (which_packet
) == PACKET_DISABLE
)
11441 return TARGET_XFER_E_IO
;
11443 /* Insert header. */
11444 i
= snprintf (rs
->buf
.data (), max_size
,
11445 "qXfer:%s:write:%s:%s:",
11446 object_name
, annex
? annex
: "",
11447 phex_nz (offset
, sizeof offset
));
11448 max_size
-= (i
+ 1);
11450 /* Escape as much data as fits into rs->buf. */
11451 buf_len
= remote_escape_output
11452 (writebuf
, len
, 1, (gdb_byte
*) rs
->buf
.data () + i
, &max_size
, max_size
);
11454 if (putpkt_binary (rs
->buf
.data (), i
+ buf_len
) < 0
11455 || getpkt (&rs
->buf
) < 0
11456 || m_features
.packet_ok (rs
->buf
, which_packet
) != PACKET_OK
)
11457 return TARGET_XFER_E_IO
;
11459 unpack_varlen_hex (rs
->buf
.data (), &n
);
11462 return (*xfered_len
!= 0) ? TARGET_XFER_OK
: TARGET_XFER_EOF
;
11465 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
11466 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
11467 number of bytes read is returned, or 0 for EOF, or -1 for error.
11468 The number of bytes read may be less than LEN without indicating an
11469 EOF. PACKET is checked and updated to indicate whether the remote
11470 target supports this object. */
11473 remote_target::remote_read_qxfer (const char *object_name
,
11475 gdb_byte
*readbuf
, ULONGEST offset
,
11477 ULONGEST
*xfered_len
,
11478 const unsigned int which_packet
)
11480 struct remote_state
*rs
= get_remote_state ();
11481 LONGEST i
, n
, packet_len
;
11483 if (m_features
.packet_support (which_packet
) == PACKET_DISABLE
)
11484 return TARGET_XFER_E_IO
;
11486 /* Check whether we've cached an end-of-object packet that matches
11488 if (rs
->finished_object
)
11490 if (strcmp (object_name
, rs
->finished_object
) == 0
11491 && strcmp (annex
? annex
: "", rs
->finished_annex
) == 0
11492 && offset
== rs
->finished_offset
)
11493 return TARGET_XFER_EOF
;
11496 /* Otherwise, we're now reading something different. Discard
11498 xfree (rs
->finished_object
);
11499 xfree (rs
->finished_annex
);
11500 rs
->finished_object
= NULL
;
11501 rs
->finished_annex
= NULL
;
11504 /* Request only enough to fit in a single packet. The actual data
11505 may not, since we don't know how much of it will need to be escaped;
11506 the target is free to respond with slightly less data. We subtract
11507 five to account for the response type and the protocol frame. */
11508 n
= std::min
<LONGEST
> (get_remote_packet_size () - 5, len
);
11509 snprintf (rs
->buf
.data (), get_remote_packet_size () - 4,
11510 "qXfer:%s:read:%s:%s,%s",
11511 object_name
, annex
? annex
: "",
11512 phex_nz (offset
, sizeof offset
),
11513 phex_nz (n
, sizeof n
));
11514 i
= putpkt (rs
->buf
);
11516 return TARGET_XFER_E_IO
;
11519 packet_len
= getpkt (&rs
->buf
);
11521 || m_features
.packet_ok (rs
->buf
, which_packet
) != PACKET_OK
)
11522 return TARGET_XFER_E_IO
;
11524 if (rs
->buf
[0] != 'l' && rs
->buf
[0] != 'm')
11525 error (_("Unknown remote qXfer reply: %s"), rs
->buf
.data ());
11527 /* 'm' means there is (or at least might be) more data after this
11528 batch. That does not make sense unless there's at least one byte
11529 of data in this reply. */
11530 if (rs
->buf
[0] == 'm' && packet_len
== 1)
11531 error (_("Remote qXfer reply contained no data."));
11533 /* Got some data. */
11534 i
= remote_unescape_input ((gdb_byte
*) rs
->buf
.data () + 1,
11535 packet_len
- 1, readbuf
, n
);
11537 /* 'l' is an EOF marker, possibly including a final block of data,
11538 or possibly empty. If we have the final block of a non-empty
11539 object, record this fact to bypass a subsequent partial read. */
11540 if (rs
->buf
[0] == 'l' && offset
+ i
> 0)
11542 rs
->finished_object
= xstrdup (object_name
);
11543 rs
->finished_annex
= xstrdup (annex
? annex
: "");
11544 rs
->finished_offset
= offset
+ i
;
11548 return TARGET_XFER_EOF
;
11552 return TARGET_XFER_OK
;
11556 enum target_xfer_status
11557 remote_target::xfer_partial (enum target_object object
,
11558 const char *annex
, gdb_byte
*readbuf
,
11559 const gdb_byte
*writebuf
, ULONGEST offset
, ULONGEST len
,
11560 ULONGEST
*xfered_len
)
11562 struct remote_state
*rs
;
11567 = gdbarch_addressable_memory_unit_size (current_inferior ()->arch ());
11569 set_remote_traceframe ();
11570 set_general_thread (inferior_ptid
);
11572 rs
= get_remote_state ();
11574 /* Handle memory using the standard memory routines. */
11575 if (object
== TARGET_OBJECT_MEMORY
)
11577 /* If the remote target is connected but not running, we should
11578 pass this request down to a lower stratum (e.g. the executable
11580 if (!target_has_execution ())
11581 return TARGET_XFER_EOF
;
11583 if (writebuf
!= NULL
)
11584 return remote_write_bytes (offset
, writebuf
, len
, unit_size
,
11587 return remote_read_bytes (offset
, readbuf
, len
, unit_size
,
11591 /* Handle extra signal info using qxfer packets. */
11592 if (object
== TARGET_OBJECT_SIGNAL_INFO
)
11595 return remote_read_qxfer ("siginfo", annex
, readbuf
, offset
, len
,
11596 xfered_len
, PACKET_qXfer_siginfo_read
);
11598 return remote_write_qxfer ("siginfo", annex
, writebuf
, offset
, len
,
11599 xfered_len
, PACKET_qXfer_siginfo_write
);
11602 if (object
== TARGET_OBJECT_STATIC_TRACE_DATA
)
11605 return remote_read_qxfer ("statictrace", annex
,
11606 readbuf
, offset
, len
, xfered_len
,
11607 PACKET_qXfer_statictrace_read
);
11609 return TARGET_XFER_E_IO
;
11612 /* Only handle flash writes. */
11613 if (writebuf
!= NULL
)
11617 case TARGET_OBJECT_FLASH
:
11618 return remote_flash_write (offset
, len
, xfered_len
,
11622 return TARGET_XFER_E_IO
;
11626 /* Map pre-existing objects onto letters. DO NOT do this for new
11627 objects!!! Instead specify new query packets. */
11630 case TARGET_OBJECT_AVR
:
11634 case TARGET_OBJECT_AUXV
:
11635 gdb_assert (annex
== NULL
);
11636 return remote_read_qxfer
11637 ("auxv", annex
, readbuf
, offset
, len
, xfered_len
, PACKET_qXfer_auxv
);
11639 case TARGET_OBJECT_AVAILABLE_FEATURES
:
11640 return remote_read_qxfer
11641 ("features", annex
, readbuf
, offset
, len
, xfered_len
,
11642 PACKET_qXfer_features
);
11644 case TARGET_OBJECT_LIBRARIES
:
11645 return remote_read_qxfer
11646 ("libraries", annex
, readbuf
, offset
, len
, xfered_len
,
11647 PACKET_qXfer_libraries
);
11649 case TARGET_OBJECT_LIBRARIES_SVR4
:
11650 return remote_read_qxfer
11651 ("libraries-svr4", annex
, readbuf
, offset
, len
, xfered_len
,
11652 PACKET_qXfer_libraries_svr4
);
11654 case TARGET_OBJECT_MEMORY_MAP
:
11655 gdb_assert (annex
== NULL
);
11656 return remote_read_qxfer
11657 ("memory-map", annex
, readbuf
, offset
, len
, xfered_len
,
11658 PACKET_qXfer_memory_map
);
11660 case TARGET_OBJECT_OSDATA
:
11661 /* Should only get here if we're connected. */
11662 gdb_assert (rs
->remote_desc
);
11663 return remote_read_qxfer
11664 ("osdata", annex
, readbuf
, offset
, len
, xfered_len
,
11665 PACKET_qXfer_osdata
);
11667 case TARGET_OBJECT_THREADS
:
11668 gdb_assert (annex
== NULL
);
11669 return remote_read_qxfer
11670 ("threads", annex
, readbuf
, offset
, len
, xfered_len
,
11671 PACKET_qXfer_threads
);
11673 case TARGET_OBJECT_TRACEFRAME_INFO
:
11674 gdb_assert (annex
== NULL
);
11675 return remote_read_qxfer
11676 ("traceframe-info", annex
, readbuf
, offset
, len
, xfered_len
,
11677 PACKET_qXfer_traceframe_info
);
11679 case TARGET_OBJECT_FDPIC
:
11680 return remote_read_qxfer
11681 ("fdpic", annex
, readbuf
, offset
, len
, xfered_len
, PACKET_qXfer_fdpic
);
11683 case TARGET_OBJECT_OPENVMS_UIB
:
11684 return remote_read_qxfer
11685 ("uib", annex
, readbuf
, offset
, len
, xfered_len
, PACKET_qXfer_uib
);
11687 case TARGET_OBJECT_BTRACE
:
11688 return remote_read_qxfer
11689 ("btrace", annex
, readbuf
, offset
, len
, xfered_len
,
11690 PACKET_qXfer_btrace
);
11692 case TARGET_OBJECT_BTRACE_CONF
:
11693 return remote_read_qxfer
11694 ("btrace-conf", annex
, readbuf
, offset
, len
, xfered_len
,
11695 PACKET_qXfer_btrace_conf
);
11697 case TARGET_OBJECT_EXEC_FILE
:
11698 return remote_read_qxfer
11699 ("exec-file", annex
, readbuf
, offset
, len
, xfered_len
,
11700 PACKET_qXfer_exec_file
);
11703 return TARGET_XFER_E_IO
;
11706 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
11707 large enough let the caller deal with it. */
11708 if (len
< get_remote_packet_size ())
11709 return TARGET_XFER_E_IO
;
11710 len
= get_remote_packet_size ();
11712 /* Except for querying the minimum buffer size, target must be open. */
11713 if (!rs
->remote_desc
)
11714 error (_("remote query is only available after target open"));
11716 gdb_assert (annex
!= NULL
);
11717 gdb_assert (readbuf
!= NULL
);
11719 p2
= rs
->buf
.data ();
11721 *p2
++ = query_type
;
11723 /* We used one buffer char for the remote protocol q command and
11724 another for the query type. As the remote protocol encapsulation
11725 uses 4 chars plus one extra in case we are debugging
11726 (remote_debug), we have PBUFZIZ - 7 left to pack the query
11729 while (annex
[i
] && (i
< (get_remote_packet_size () - 8)))
11731 /* Bad caller may have sent forbidden characters. */
11732 gdb_assert (isprint (annex
[i
]) && annex
[i
] != '$' && annex
[i
] != '#');
11737 gdb_assert (annex
[i
] == '\0');
11739 i
= putpkt (rs
->buf
);
11741 return TARGET_XFER_E_IO
;
11744 strcpy ((char *) readbuf
, rs
->buf
.data ());
11746 *xfered_len
= strlen ((char *) readbuf
);
11747 return (*xfered_len
!= 0) ? TARGET_XFER_OK
: TARGET_XFER_EOF
;
11750 /* Implementation of to_get_memory_xfer_limit. */
11753 remote_target::get_memory_xfer_limit ()
11755 return get_memory_write_packet_size ();
11759 remote_target::search_memory (CORE_ADDR start_addr
, ULONGEST search_space_len
,
11760 const gdb_byte
*pattern
, ULONGEST pattern_len
,
11761 CORE_ADDR
*found_addrp
)
11763 int addr_size
= gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
11764 struct remote_state
*rs
= get_remote_state ();
11765 int max_size
= get_memory_write_packet_size ();
11767 /* Number of packet bytes used to encode the pattern;
11768 this could be more than PATTERN_LEN due to escape characters. */
11769 int escaped_pattern_len
;
11770 /* Amount of pattern that was encodable in the packet. */
11771 int used_pattern_len
;
11774 ULONGEST found_addr
;
11776 auto read_memory
= [this] (CORE_ADDR addr
, gdb_byte
*result
, size_t len
)
11778 return (target_read (this, TARGET_OBJECT_MEMORY
, NULL
, result
, addr
, len
)
11782 /* Don't go to the target if we don't have to. This is done before
11783 checking packet_support to avoid the possibility that a success for this
11784 edge case means the facility works in general. */
11785 if (pattern_len
> search_space_len
)
11787 if (pattern_len
== 0)
11789 *found_addrp
= start_addr
;
11793 /* If we already know the packet isn't supported, fall back to the simple
11794 way of searching memory. */
11796 if (m_features
.packet_support (PACKET_qSearch_memory
) == PACKET_DISABLE
)
11798 /* Target doesn't provided special support, fall back and use the
11799 standard support (copy memory and do the search here). */
11800 return simple_search_memory (read_memory
, start_addr
, search_space_len
,
11801 pattern
, pattern_len
, found_addrp
);
11804 /* Make sure the remote is pointing at the right process. */
11805 set_general_process ();
11807 /* Insert header. */
11808 i
= snprintf (rs
->buf
.data (), max_size
,
11809 "qSearch:memory:%s;%s;",
11810 phex_nz (start_addr
, addr_size
),
11811 phex_nz (search_space_len
, sizeof (search_space_len
)));
11812 max_size
-= (i
+ 1);
11814 /* Escape as much data as fits into rs->buf. */
11815 escaped_pattern_len
=
11816 remote_escape_output (pattern
, pattern_len
, 1,
11817 (gdb_byte
*) rs
->buf
.data () + i
,
11818 &used_pattern_len
, max_size
);
11820 /* Bail if the pattern is too large. */
11821 if (used_pattern_len
!= pattern_len
)
11822 error (_("Pattern is too large to transmit to remote target."));
11824 if (putpkt_binary (rs
->buf
.data (), i
+ escaped_pattern_len
) < 0
11825 || getpkt (&rs
->buf
) < 0
11826 || m_features
.packet_ok (rs
->buf
, PACKET_qSearch_memory
) != PACKET_OK
)
11828 /* The request may not have worked because the command is not
11829 supported. If so, fall back to the simple way. */
11830 if (m_features
.packet_support (PACKET_qSearch_memory
) == PACKET_DISABLE
)
11832 return simple_search_memory (read_memory
, start_addr
, search_space_len
,
11833 pattern
, pattern_len
, found_addrp
);
11838 if (rs
->buf
[0] == '0')
11840 else if (rs
->buf
[0] == '1')
11843 if (rs
->buf
[1] != ',')
11844 error (_("Unknown qSearch:memory reply: %s"), rs
->buf
.data ());
11845 unpack_varlen_hex (&rs
->buf
[2], &found_addr
);
11846 *found_addrp
= found_addr
;
11849 error (_("Unknown qSearch:memory reply: %s"), rs
->buf
.data ());
11855 remote_target::rcmd (const char *command
, struct ui_file
*outbuf
)
11857 struct remote_state
*rs
= get_remote_state ();
11858 char *p
= rs
->buf
.data ();
11860 if (!rs
->remote_desc
)
11861 error (_("remote rcmd is only available after target open"));
11863 /* Send a NULL command across as an empty command. */
11864 if (command
== NULL
)
11867 /* The query prefix. */
11868 strcpy (rs
->buf
.data (), "qRcmd,");
11869 p
= strchr (rs
->buf
.data (), '\0');
11871 if ((strlen (rs
->buf
.data ()) + strlen (command
) * 2 + 8/*misc*/)
11872 > get_remote_packet_size ())
11873 error (_("\"monitor\" command ``%s'' is too long."), command
);
11875 /* Encode the actual command. */
11876 bin2hex ((const gdb_byte
*) command
, p
, strlen (command
));
11878 if (putpkt (rs
->buf
) < 0)
11879 error (_("Communication problem with target."));
11881 /* get/display the response */
11886 /* XXX - see also remote_get_noisy_reply(). */
11887 QUIT
; /* Allow user to bail out with ^C. */
11889 if (getpkt (&rs
->buf
) == -1)
11891 /* Timeout. Continue to (try to) read responses.
11892 This is better than stopping with an error, assuming the stub
11893 is still executing the (long) monitor command.
11894 If needed, the user can interrupt gdb using C-c, obtaining
11895 an effect similar to stop on timeout. */
11898 buf
= rs
->buf
.data ();
11899 if (buf
[0] == '\0')
11900 error (_("Target does not support this command."));
11901 if (buf
[0] == 'O' && buf
[1] != 'K')
11903 remote_console_output (buf
+ 1); /* 'O' message from stub. */
11906 if (strcmp (buf
, "OK") == 0)
11908 if (strlen (buf
) == 3 && buf
[0] == 'E'
11909 && isxdigit (buf
[1]) && isxdigit (buf
[2]))
11911 error (_("Protocol error with Rcmd"));
11913 for (p
= buf
; p
[0] != '\0' && p
[1] != '\0'; p
+= 2)
11915 char c
= (fromhex (p
[0]) << 4) + fromhex (p
[1]);
11917 gdb_putc (c
, outbuf
);
11923 std::vector
<mem_region
>
11924 remote_target::memory_map ()
11926 std::vector
<mem_region
> result
;
11927 std::optional
<gdb::char_vector
> text
11928 = target_read_stralloc (current_inferior ()->top_target (),
11929 TARGET_OBJECT_MEMORY_MAP
, NULL
);
11932 result
= parse_memory_map (text
->data ());
11937 /* Set of callbacks used to implement the 'maint packet' command. */
11939 struct cli_packet_command_callbacks
: public send_remote_packet_callbacks
11941 /* Called before the packet is sent. BUF is the packet content before
11942 the protocol specific prefix, suffix, and escaping is added. */
11944 void sending (gdb::array_view
<const char> &buf
) override
11946 gdb_puts ("sending: ");
11947 print_packet (buf
);
11951 /* Called with BUF, the reply from the remote target. */
11953 void received (gdb::array_view
<const char> &buf
) override
11955 gdb_puts ("received: \"");
11956 print_packet (buf
);
11962 /* Print BUF o gdb_stdout. Any non-printable bytes in BUF are printed as
11963 '\x??' with '??' replaced by the hexadecimal value of the byte. */
11966 print_packet (gdb::array_view
<const char> &buf
)
11970 for (int i
= 0; i
< buf
.size (); ++i
)
11972 gdb_byte c
= buf
[i
];
11974 gdb_putc (c
, &stb
);
11976 gdb_printf (&stb
, "\\x%02x", (unsigned char) c
);
11979 gdb_puts (stb
.string ().c_str ());
11983 /* See remote.h. */
11986 send_remote_packet (gdb::array_view
<const char> &buf
,
11987 send_remote_packet_callbacks
*callbacks
)
11989 if (buf
.size () == 0 || buf
.data ()[0] == '\0')
11990 error (_("a remote packet must not be empty"));
11992 remote_target
*remote
= get_current_remote_target ();
11993 if (remote
== nullptr)
11994 error (_("packets can only be sent to a remote target"));
11996 callbacks
->sending (buf
);
11998 remote
->putpkt_binary (buf
.data (), buf
.size ());
11999 remote_state
*rs
= remote
->get_remote_state ();
12000 int bytes
= remote
->getpkt (&rs
->buf
);
12003 error (_("error while fetching packet from remote target"));
12005 gdb::array_view
<const char> view (&rs
->buf
[0], bytes
);
12006 callbacks
->received (view
);
12009 /* Entry point for the 'maint packet' command. */
12012 cli_packet_command (const char *args
, int from_tty
)
12014 cli_packet_command_callbacks cb
;
12015 gdb::array_view
<const char> view
12016 = gdb::make_array_view (args
, args
== nullptr ? 0 : strlen (args
));
12017 send_remote_packet (view
, &cb
);
12021 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
12023 static void display_thread_info (struct gdb_ext_thread_info
*info
);
12025 static void threadset_test_cmd (char *cmd
, int tty
);
12027 static void threadalive_test (char *cmd
, int tty
);
12029 static void threadlist_test_cmd (char *cmd
, int tty
);
12031 int get_and_display_threadinfo (threadref
*ref
);
12033 static void threadinfo_test_cmd (char *cmd
, int tty
);
12035 static int thread_display_step (threadref
*ref
, void *context
);
12037 static void threadlist_update_test_cmd (char *cmd
, int tty
);
12039 static void init_remote_threadtests (void);
12041 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
12044 threadset_test_cmd (const char *cmd
, int tty
)
12046 int sample_thread
= SAMPLE_THREAD
;
12048 gdb_printf (_("Remote threadset test\n"));
12049 set_general_thread (sample_thread
);
12054 threadalive_test (const char *cmd
, int tty
)
12056 int sample_thread
= SAMPLE_THREAD
;
12057 int pid
= inferior_ptid
.pid ();
12058 ptid_t ptid
= ptid_t (pid
, sample_thread
, 0);
12060 if (remote_thread_alive (ptid
))
12061 gdb_printf ("PASS: Thread alive test\n");
12063 gdb_printf ("FAIL: Thread alive test\n");
12066 void output_threadid (char *title
, threadref
*ref
);
12069 output_threadid (char *title
, threadref
*ref
)
12073 pack_threadid (&hexid
[0], ref
); /* Convert thread id into hex. */
12075 gdb_printf ("%s %s\n", title
, (&hexid
[0]));
12079 threadlist_test_cmd (const char *cmd
, int tty
)
12082 threadref nextthread
;
12083 int done
, result_count
;
12084 threadref threadlist
[3];
12086 gdb_printf ("Remote Threadlist test\n");
12087 if (!remote_get_threadlist (startflag
, &nextthread
, 3, &done
,
12088 &result_count
, &threadlist
[0]))
12089 gdb_printf ("FAIL: threadlist test\n");
12092 threadref
*scan
= threadlist
;
12093 threadref
*limit
= scan
+ result_count
;
12095 while (scan
< limit
)
12096 output_threadid (" thread ", scan
++);
12101 display_thread_info (struct gdb_ext_thread_info
*info
)
12103 output_threadid ("Threadid: ", &info
->threadid
);
12104 gdb_printf ("Name: %s\n ", info
->shortname
);
12105 gdb_printf ("State: %s\n", info
->display
);
12106 gdb_printf ("other: %s\n\n", info
->more_display
);
12110 get_and_display_threadinfo (threadref
*ref
)
12114 struct gdb_ext_thread_info threadinfo
;
12116 set
= TAG_THREADID
| TAG_EXISTS
| TAG_THREADNAME
12117 | TAG_MOREDISPLAY
| TAG_DISPLAY
;
12118 if (0 != (result
= remote_get_threadinfo (ref
, set
, &threadinfo
)))
12119 display_thread_info (&threadinfo
);
12124 threadinfo_test_cmd (const char *cmd
, int tty
)
12126 int athread
= SAMPLE_THREAD
;
12130 int_to_threadref (&thread
, athread
);
12131 gdb_printf ("Remote Threadinfo test\n");
12132 if (!get_and_display_threadinfo (&thread
))
12133 gdb_printf ("FAIL cannot get thread info\n");
12137 thread_display_step (threadref
*ref
, void *context
)
12139 /* output_threadid(" threadstep ",ref); *//* simple test */
12140 return get_and_display_threadinfo (ref
);
12144 threadlist_update_test_cmd (const char *cmd
, int tty
)
12146 gdb_printf ("Remote Threadlist update test\n");
12147 remote_threadlist_iterator (thread_display_step
, 0, CRAZY_MAX_THREADS
);
12151 init_remote_threadtests (void)
12153 add_com ("tlist", class_obscure
, threadlist_test_cmd
,
12154 _("Fetch and print the remote list of "
12155 "thread identifiers, one pkt only."));
12156 add_com ("tinfo", class_obscure
, threadinfo_test_cmd
,
12157 _("Fetch and display info about one thread."));
12158 add_com ("tset", class_obscure
, threadset_test_cmd
,
12159 _("Test setting to a different thread."));
12160 add_com ("tupd", class_obscure
, threadlist_update_test_cmd
,
12161 _("Iterate through updating all remote thread info."));
12162 add_com ("talive", class_obscure
, threadalive_test
,
12163 _("Remote thread alive test."));
12168 /* Convert a thread ID to a string. */
12171 remote_target::pid_to_str (ptid_t ptid
)
12173 if (ptid
== null_ptid
)
12174 return normal_pid_to_str (ptid
);
12175 else if (ptid
.is_pid ())
12177 /* Printing an inferior target id. */
12179 /* When multi-process extensions are off, there's no way in the
12180 remote protocol to know the remote process id, if there's any
12181 at all. There's one exception --- when we're connected with
12182 target extended-remote, and we manually attached to a process
12183 with "attach PID". We don't record anywhere a flag that
12184 allows us to distinguish that case from the case of
12185 connecting with extended-remote and the stub already being
12186 attached to a process, and reporting yes to qAttached, hence
12187 no smart special casing here. */
12188 if (!m_features
.remote_multi_process_p ())
12189 return "Remote target";
12191 return normal_pid_to_str (ptid
);
12195 if (magic_null_ptid
== ptid
)
12196 return "Thread <main>";
12197 else if (m_features
.remote_multi_process_p ())
12198 if (ptid
.lwp () == 0)
12199 return normal_pid_to_str (ptid
);
12201 return string_printf ("Thread %d.%ld",
12202 ptid
.pid (), ptid
.lwp ());
12204 return string_printf ("Thread %ld", ptid
.lwp ());
12208 /* Get the address of the thread local variable in OBJFILE which is
12209 stored at OFFSET within the thread local storage for thread PTID. */
12212 remote_target::get_thread_local_address (ptid_t ptid
, CORE_ADDR lm
,
12215 if (m_features
.packet_support (PACKET_qGetTLSAddr
) != PACKET_DISABLE
)
12217 struct remote_state
*rs
= get_remote_state ();
12218 char *p
= rs
->buf
.data ();
12219 char *endp
= p
+ get_remote_packet_size ();
12220 enum packet_result result
;
12222 strcpy (p
, "qGetTLSAddr:");
12224 p
= write_ptid (p
, endp
, ptid
);
12226 p
+= hexnumstr (p
, offset
);
12228 p
+= hexnumstr (p
, lm
);
12233 result
= m_features
.packet_ok (rs
->buf
, PACKET_qGetTLSAddr
);
12234 if (result
== PACKET_OK
)
12238 unpack_varlen_hex (rs
->buf
.data (), &addr
);
12241 else if (result
== PACKET_UNKNOWN
)
12242 throw_error (TLS_GENERIC_ERROR
,
12243 _("Remote target doesn't support qGetTLSAddr packet"));
12245 throw_error (TLS_GENERIC_ERROR
,
12246 _("Remote target failed to process qGetTLSAddr request"));
12249 throw_error (TLS_GENERIC_ERROR
,
12250 _("TLS not supported or disabled on this target"));
12255 /* Provide thread local base, i.e. Thread Information Block address.
12256 Returns 1 if ptid is found and thread_local_base is non zero. */
12259 remote_target::get_tib_address (ptid_t ptid
, CORE_ADDR
*addr
)
12261 if (m_features
.packet_support (PACKET_qGetTIBAddr
) != PACKET_DISABLE
)
12263 struct remote_state
*rs
= get_remote_state ();
12264 char *p
= rs
->buf
.data ();
12265 char *endp
= p
+ get_remote_packet_size ();
12266 enum packet_result result
;
12268 strcpy (p
, "qGetTIBAddr:");
12270 p
= write_ptid (p
, endp
, ptid
);
12275 result
= m_features
.packet_ok (rs
->buf
, PACKET_qGetTIBAddr
);
12276 if (result
== PACKET_OK
)
12279 unpack_varlen_hex (rs
->buf
.data (), &val
);
12281 *addr
= (CORE_ADDR
) val
;
12284 else if (result
== PACKET_UNKNOWN
)
12285 error (_("Remote target doesn't support qGetTIBAddr packet"));
12287 error (_("Remote target failed to process qGetTIBAddr request"));
12290 error (_("qGetTIBAddr not supported or disabled on this target"));
12295 /* Support for inferring a target description based on the current
12296 architecture and the size of a 'g' packet. While the 'g' packet
12297 can have any size (since optional registers can be left off the
12298 end), some sizes are easily recognizable given knowledge of the
12299 approximate architecture. */
12301 struct remote_g_packet_guess
12303 remote_g_packet_guess (int bytes_
, const struct target_desc
*tdesc_
)
12310 const struct target_desc
*tdesc
;
12313 struct remote_g_packet_data
12315 std::vector
<remote_g_packet_guess
> guesses
;
12318 static const registry
<gdbarch
>::key
<struct remote_g_packet_data
>
12319 remote_g_packet_data_handle
;
12321 static struct remote_g_packet_data
*
12322 get_g_packet_data (struct gdbarch
*gdbarch
)
12324 struct remote_g_packet_data
*data
12325 = remote_g_packet_data_handle
.get (gdbarch
);
12326 if (data
== nullptr)
12327 data
= remote_g_packet_data_handle
.emplace (gdbarch
);
12332 register_remote_g_packet_guess (struct gdbarch
*gdbarch
, int bytes
,
12333 const struct target_desc
*tdesc
)
12335 struct remote_g_packet_data
*data
= get_g_packet_data (gdbarch
);
12337 gdb_assert (tdesc
!= NULL
);
12339 for (const remote_g_packet_guess
&guess
: data
->guesses
)
12340 if (guess
.bytes
== bytes
)
12341 internal_error (_("Duplicate g packet description added for size %d"),
12344 data
->guesses
.emplace_back (bytes
, tdesc
);
12347 /* Return true if remote_read_description would do anything on this target
12348 and architecture, false otherwise. */
12351 remote_read_description_p (struct target_ops
*target
)
12353 remote_g_packet_data
*data
= get_g_packet_data (current_inferior ()->arch ());
12355 return !data
->guesses
.empty ();
12358 const struct target_desc
*
12359 remote_target::read_description ()
12361 remote_g_packet_data
*data
= get_g_packet_data (current_inferior ()->arch ());
12363 /* Do not try this during initial connection, when we do not know
12364 whether there is a running but stopped thread. */
12365 if (!target_has_execution () || inferior_ptid
== null_ptid
)
12366 return beneath ()->read_description ();
12368 if (!data
->guesses
.empty ())
12370 int bytes
= send_g_packet ();
12372 for (const remote_g_packet_guess
&guess
: data
->guesses
)
12373 if (guess
.bytes
== bytes
)
12374 return guess
.tdesc
;
12376 /* We discard the g packet. A minor optimization would be to
12377 hold on to it, and fill the register cache once we have selected
12378 an architecture, but it's too tricky to do safely. */
12381 return beneath ()->read_description ();
12384 /* Remote file transfer support. This is host-initiated I/O, not
12385 target-initiated; for target-initiated, see remote-fileio.c. */
12387 /* If *LEFT is at least the length of STRING, copy STRING to
12388 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12389 decrease *LEFT. Otherwise raise an error. */
12392 remote_buffer_add_string (char **buffer
, int *left
, const char *string
)
12394 int len
= strlen (string
);
12397 error (_("Packet too long for target."));
12399 memcpy (*buffer
, string
, len
);
12403 /* NUL-terminate the buffer as a convenience, if there is
12409 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
12410 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12411 decrease *LEFT. Otherwise raise an error. */
12414 remote_buffer_add_bytes (char **buffer
, int *left
, const gdb_byte
*bytes
,
12417 if (2 * len
> *left
)
12418 error (_("Packet too long for target."));
12420 bin2hex (bytes
, *buffer
, len
);
12421 *buffer
+= 2 * len
;
12424 /* NUL-terminate the buffer as a convenience, if there is
12430 /* If *LEFT is large enough, convert VALUE to hex and add it to
12431 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12432 decrease *LEFT. Otherwise raise an error. */
12435 remote_buffer_add_int (char **buffer
, int *left
, ULONGEST value
)
12437 int len
= hexnumlen (value
);
12440 error (_("Packet too long for target."));
12442 hexnumstr (*buffer
, value
);
12446 /* NUL-terminate the buffer as a convenience, if there is
12452 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
12453 value, *REMOTE_ERRNO to the remote error number or FILEIO_SUCCESS if none
12454 was included, and *ATTACHMENT to point to the start of the annex
12455 if any. The length of the packet isn't needed here; there may
12456 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
12458 Return 0 if the packet could be parsed, -1 if it could not. If
12459 -1 is returned, the other variables may not be initialized. */
12462 remote_hostio_parse_result (const char *buffer
, int *retcode
,
12463 fileio_error
*remote_errno
, const char **attachment
)
12467 *remote_errno
= FILEIO_SUCCESS
;
12468 *attachment
= NULL
;
12470 if (buffer
[0] != 'F')
12474 *retcode
= strtol (&buffer
[1], &p
, 16);
12475 if (errno
!= 0 || p
== &buffer
[1])
12478 /* Check for ",errno". */
12482 *remote_errno
= (fileio_error
) strtol (p
+ 1, &p2
, 16);
12483 if (errno
!= 0 || p
+ 1 == p2
)
12488 /* Check for ";attachment". If there is no attachment, the
12489 packet should end here. */
12492 *attachment
= p
+ 1;
12495 else if (*p
== '\0')
12501 /* Send a prepared I/O packet to the target and read its response.
12502 The prepared packet is in the global RS->BUF before this function
12503 is called, and the answer is there when we return.
12505 COMMAND_BYTES is the length of the request to send, which may include
12506 binary data. WHICH_PACKET is the packet configuration to check
12507 before attempting a packet. If an error occurs, *REMOTE_ERRNO
12508 is set to the error number and -1 is returned. Otherwise the value
12509 returned by the function is returned.
12511 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
12512 attachment is expected; an error will be reported if there's a
12513 mismatch. If one is found, *ATTACHMENT will be set to point into
12514 the packet buffer and *ATTACHMENT_LEN will be set to the
12515 attachment's length. */
12518 remote_target::remote_hostio_send_command (int command_bytes
, int which_packet
,
12519 fileio_error
*remote_errno
, const char **attachment
,
12520 int *attachment_len
)
12522 struct remote_state
*rs
= get_remote_state ();
12523 int ret
, bytes_read
;
12524 const char *attachment_tmp
;
12526 if (m_features
.packet_support (which_packet
) == PACKET_DISABLE
)
12528 *remote_errno
= FILEIO_ENOSYS
;
12532 putpkt_binary (rs
->buf
.data (), command_bytes
);
12533 bytes_read
= getpkt (&rs
->buf
);
12535 /* If it timed out, something is wrong. Don't try to parse the
12537 if (bytes_read
< 0)
12539 *remote_errno
= FILEIO_EINVAL
;
12543 switch (m_features
.packet_ok (rs
->buf
, which_packet
))
12546 *remote_errno
= FILEIO_EINVAL
;
12548 case PACKET_UNKNOWN
:
12549 *remote_errno
= FILEIO_ENOSYS
;
12555 if (remote_hostio_parse_result (rs
->buf
.data (), &ret
, remote_errno
,
12558 *remote_errno
= FILEIO_EINVAL
;
12562 /* Make sure we saw an attachment if and only if we expected one. */
12563 if ((attachment_tmp
== NULL
&& attachment
!= NULL
)
12564 || (attachment_tmp
!= NULL
&& attachment
== NULL
))
12566 *remote_errno
= FILEIO_EINVAL
;
12570 /* If an attachment was found, it must point into the packet buffer;
12571 work out how many bytes there were. */
12572 if (attachment_tmp
!= NULL
)
12574 *attachment
= attachment_tmp
;
12575 *attachment_len
= bytes_read
- (*attachment
- rs
->buf
.data ());
12581 /* See declaration.h. */
12584 readahead_cache::invalidate ()
12589 /* See declaration.h. */
12592 readahead_cache::invalidate_fd (int fd
)
12594 if (this->fd
== fd
)
12598 /* Set the filesystem remote_hostio functions that take FILENAME
12599 arguments will use. Return 0 on success, or -1 if an error
12600 occurs (and set *REMOTE_ERRNO). */
12603 remote_target::remote_hostio_set_filesystem (struct inferior
*inf
,
12604 fileio_error
*remote_errno
)
12606 struct remote_state
*rs
= get_remote_state ();
12607 int required_pid
= (inf
== NULL
|| inf
->fake_pid_p
) ? 0 : inf
->pid
;
12608 char *p
= rs
->buf
.data ();
12609 int left
= get_remote_packet_size () - 1;
12613 if (m_features
.packet_support (PACKET_vFile_setfs
) == PACKET_DISABLE
)
12616 if (rs
->fs_pid
!= -1 && required_pid
== rs
->fs_pid
)
12619 remote_buffer_add_string (&p
, &left
, "vFile:setfs:");
12621 xsnprintf (arg
, sizeof (arg
), "%x", required_pid
);
12622 remote_buffer_add_string (&p
, &left
, arg
);
12624 ret
= remote_hostio_send_command (p
- rs
->buf
.data (), PACKET_vFile_setfs
,
12625 remote_errno
, NULL
, NULL
);
12627 if (m_features
.packet_support (PACKET_vFile_setfs
) == PACKET_DISABLE
)
12631 rs
->fs_pid
= required_pid
;
12636 /* Implementation of to_fileio_open. */
12639 remote_target::remote_hostio_open (inferior
*inf
, const char *filename
,
12640 int flags
, int mode
, int warn_if_slow
,
12641 fileio_error
*remote_errno
)
12643 struct remote_state
*rs
= get_remote_state ();
12644 char *p
= rs
->buf
.data ();
12645 int left
= get_remote_packet_size () - 1;
12649 static int warning_issued
= 0;
12651 gdb_printf (_("Reading %s from remote target...\n"),
12654 if (!warning_issued
)
12656 warning (_("File transfers from remote targets can be slow."
12657 " Use \"set sysroot\" to access files locally"
12659 warning_issued
= 1;
12663 if (remote_hostio_set_filesystem (inf
, remote_errno
) != 0)
12666 remote_buffer_add_string (&p
, &left
, "vFile:open:");
12668 remote_buffer_add_bytes (&p
, &left
, (const gdb_byte
*) filename
,
12669 strlen (filename
));
12670 remote_buffer_add_string (&p
, &left
, ",");
12672 remote_buffer_add_int (&p
, &left
, flags
);
12673 remote_buffer_add_string (&p
, &left
, ",");
12675 remote_buffer_add_int (&p
, &left
, mode
);
12677 return remote_hostio_send_command (p
- rs
->buf
.data (), PACKET_vFile_open
,
12678 remote_errno
, NULL
, NULL
);
12682 remote_target::fileio_open (struct inferior
*inf
, const char *filename
,
12683 int flags
, int mode
, int warn_if_slow
,
12684 fileio_error
*remote_errno
)
12686 return remote_hostio_open (inf
, filename
, flags
, mode
, warn_if_slow
,
12690 /* Implementation of to_fileio_pwrite. */
12693 remote_target::remote_hostio_pwrite (int fd
, const gdb_byte
*write_buf
, int len
,
12694 ULONGEST offset
, fileio_error
*remote_errno
)
12696 struct remote_state
*rs
= get_remote_state ();
12697 char *p
= rs
->buf
.data ();
12698 int left
= get_remote_packet_size ();
12701 rs
->readahead_cache
.invalidate_fd (fd
);
12703 remote_buffer_add_string (&p
, &left
, "vFile:pwrite:");
12705 remote_buffer_add_int (&p
, &left
, fd
);
12706 remote_buffer_add_string (&p
, &left
, ",");
12708 remote_buffer_add_int (&p
, &left
, offset
);
12709 remote_buffer_add_string (&p
, &left
, ",");
12711 p
+= remote_escape_output (write_buf
, len
, 1, (gdb_byte
*) p
, &out_len
,
12712 (get_remote_packet_size ()
12713 - (p
- rs
->buf
.data ())));
12715 return remote_hostio_send_command (p
- rs
->buf
.data (), PACKET_vFile_pwrite
,
12716 remote_errno
, NULL
, NULL
);
12720 remote_target::fileio_pwrite (int fd
, const gdb_byte
*write_buf
, int len
,
12721 ULONGEST offset
, fileio_error
*remote_errno
)
12723 return remote_hostio_pwrite (fd
, write_buf
, len
, offset
, remote_errno
);
12726 /* Helper for the implementation of to_fileio_pread. Read the file
12727 from the remote side with vFile:pread. */
12730 remote_target::remote_hostio_pread_vFile (int fd
, gdb_byte
*read_buf
, int len
,
12731 ULONGEST offset
, fileio_error
*remote_errno
)
12733 struct remote_state
*rs
= get_remote_state ();
12734 char *p
= rs
->buf
.data ();
12735 const char *attachment
;
12736 int left
= get_remote_packet_size ();
12737 int ret
, attachment_len
;
12740 remote_buffer_add_string (&p
, &left
, "vFile:pread:");
12742 remote_buffer_add_int (&p
, &left
, fd
);
12743 remote_buffer_add_string (&p
, &left
, ",");
12745 remote_buffer_add_int (&p
, &left
, len
);
12746 remote_buffer_add_string (&p
, &left
, ",");
12748 remote_buffer_add_int (&p
, &left
, offset
);
12750 ret
= remote_hostio_send_command (p
- rs
->buf
.data (), PACKET_vFile_pread
,
12751 remote_errno
, &attachment
,
12757 read_len
= remote_unescape_input ((gdb_byte
*) attachment
, attachment_len
,
12759 if (read_len
!= ret
)
12760 error (_("Read returned %d, but %d bytes."), ret
, (int) read_len
);
12765 /* See declaration.h. */
12768 readahead_cache::pread (int fd
, gdb_byte
*read_buf
, size_t len
,
12772 && this->offset
<= offset
12773 && offset
< this->offset
+ this->buf
.size ())
12775 ULONGEST max
= this->offset
+ this->buf
.size ();
12777 if (offset
+ len
> max
)
12778 len
= max
- offset
;
12780 memcpy (read_buf
, &this->buf
[offset
- this->offset
], len
);
12787 /* Implementation of to_fileio_pread. */
12790 remote_target::remote_hostio_pread (int fd
, gdb_byte
*read_buf
, int len
,
12791 ULONGEST offset
, fileio_error
*remote_errno
)
12794 struct remote_state
*rs
= get_remote_state ();
12795 readahead_cache
*cache
= &rs
->readahead_cache
;
12797 ret
= cache
->pread (fd
, read_buf
, len
, offset
);
12800 cache
->hit_count
++;
12802 remote_debug_printf ("readahead cache hit %s",
12803 pulongest (cache
->hit_count
));
12807 cache
->miss_count
++;
12809 remote_debug_printf ("readahead cache miss %s",
12810 pulongest (cache
->miss_count
));
12813 cache
->offset
= offset
;
12814 cache
->buf
.resize (get_remote_packet_size ());
12816 ret
= remote_hostio_pread_vFile (cache
->fd
, &cache
->buf
[0],
12817 cache
->buf
.size (),
12818 cache
->offset
, remote_errno
);
12821 cache
->invalidate_fd (fd
);
12825 cache
->buf
.resize (ret
);
12826 return cache
->pread (fd
, read_buf
, len
, offset
);
12830 remote_target::fileio_pread (int fd
, gdb_byte
*read_buf
, int len
,
12831 ULONGEST offset
, fileio_error
*remote_errno
)
12833 return remote_hostio_pread (fd
, read_buf
, len
, offset
, remote_errno
);
12836 /* Implementation of to_fileio_close. */
12839 remote_target::remote_hostio_close (int fd
, fileio_error
*remote_errno
)
12841 struct remote_state
*rs
= get_remote_state ();
12842 char *p
= rs
->buf
.data ();
12843 int left
= get_remote_packet_size () - 1;
12845 rs
->readahead_cache
.invalidate_fd (fd
);
12847 remote_buffer_add_string (&p
, &left
, "vFile:close:");
12849 remote_buffer_add_int (&p
, &left
, fd
);
12851 return remote_hostio_send_command (p
- rs
->buf
.data (), PACKET_vFile_close
,
12852 remote_errno
, NULL
, NULL
);
12856 remote_target::fileio_close (int fd
, fileio_error
*remote_errno
)
12858 return remote_hostio_close (fd
, remote_errno
);
12861 /* Implementation of to_fileio_unlink. */
12864 remote_target::remote_hostio_unlink (inferior
*inf
, const char *filename
,
12865 fileio_error
*remote_errno
)
12867 struct remote_state
*rs
= get_remote_state ();
12868 char *p
= rs
->buf
.data ();
12869 int left
= get_remote_packet_size () - 1;
12871 if (remote_hostio_set_filesystem (inf
, remote_errno
) != 0)
12874 remote_buffer_add_string (&p
, &left
, "vFile:unlink:");
12876 remote_buffer_add_bytes (&p
, &left
, (const gdb_byte
*) filename
,
12877 strlen (filename
));
12879 return remote_hostio_send_command (p
- rs
->buf
.data (), PACKET_vFile_unlink
,
12880 remote_errno
, NULL
, NULL
);
12884 remote_target::fileio_unlink (struct inferior
*inf
, const char *filename
,
12885 fileio_error
*remote_errno
)
12887 return remote_hostio_unlink (inf
, filename
, remote_errno
);
12890 /* Implementation of to_fileio_readlink. */
12892 std::optional
<std::string
>
12893 remote_target::fileio_readlink (struct inferior
*inf
, const char *filename
,
12894 fileio_error
*remote_errno
)
12896 struct remote_state
*rs
= get_remote_state ();
12897 char *p
= rs
->buf
.data ();
12898 const char *attachment
;
12899 int left
= get_remote_packet_size ();
12900 int len
, attachment_len
;
12903 if (remote_hostio_set_filesystem (inf
, remote_errno
) != 0)
12906 remote_buffer_add_string (&p
, &left
, "vFile:readlink:");
12908 remote_buffer_add_bytes (&p
, &left
, (const gdb_byte
*) filename
,
12909 strlen (filename
));
12911 len
= remote_hostio_send_command (p
- rs
->buf
.data (), PACKET_vFile_readlink
,
12912 remote_errno
, &attachment
,
12918 std::string
ret (len
, '\0');
12920 read_len
= remote_unescape_input ((gdb_byte
*) attachment
, attachment_len
,
12921 (gdb_byte
*) &ret
[0], len
);
12922 if (read_len
!= len
)
12923 error (_("Readlink returned %d, but %d bytes."), len
, read_len
);
12928 /* Implementation of to_fileio_fstat. */
12931 remote_target::fileio_fstat (int fd
, struct stat
*st
, fileio_error
*remote_errno
)
12933 struct remote_state
*rs
= get_remote_state ();
12934 char *p
= rs
->buf
.data ();
12935 int left
= get_remote_packet_size ();
12936 int attachment_len
, ret
;
12937 const char *attachment
;
12938 struct fio_stat fst
;
12941 remote_buffer_add_string (&p
, &left
, "vFile:fstat:");
12943 remote_buffer_add_int (&p
, &left
, fd
);
12945 ret
= remote_hostio_send_command (p
- rs
->buf
.data (), PACKET_vFile_fstat
,
12946 remote_errno
, &attachment
,
12950 if (*remote_errno
!= FILEIO_ENOSYS
)
12953 /* Strictly we should return -1, ENOSYS here, but when
12954 "set sysroot remote:" was implemented in August 2008
12955 BFD's need for a stat function was sidestepped with
12956 this hack. This was not remedied until March 2015
12957 so we retain the previous behavior to avoid breaking
12960 Note that the memset is a March 2015 addition; older
12961 GDBs set st_size *and nothing else* so the structure
12962 would have garbage in all other fields. This might
12963 break something but retaining the previous behavior
12964 here would be just too wrong. */
12966 memset (st
, 0, sizeof (struct stat
));
12967 st
->st_size
= INT_MAX
;
12971 read_len
= remote_unescape_input ((gdb_byte
*) attachment
, attachment_len
,
12972 (gdb_byte
*) &fst
, sizeof (fst
));
12974 if (read_len
!= ret
)
12975 error (_("vFile:fstat returned %d, but %d bytes."), ret
, read_len
);
12977 if (read_len
!= sizeof (fst
))
12978 error (_("vFile:fstat returned %d bytes, but expecting %d."),
12979 read_len
, (int) sizeof (fst
));
12981 remote_fileio_to_host_stat (&fst
, st
);
12986 /* Implementation of to_filesystem_is_local. */
12989 remote_target::filesystem_is_local ()
12991 /* Valgrind GDB presents itself as a remote target but works
12992 on the local filesystem: it does not implement remote get
12993 and users are not expected to set a sysroot. To handle
12994 this case we treat the remote filesystem as local if the
12995 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
12996 does not support vFile:open. */
12997 if (gdb_sysroot
== TARGET_SYSROOT_PREFIX
)
12999 packet_support ps
= m_features
.packet_support (PACKET_vFile_open
);
13001 if (ps
== PACKET_SUPPORT_UNKNOWN
)
13004 fileio_error remote_errno
;
13006 /* Try opening a file to probe support. The supplied
13007 filename is irrelevant, we only care about whether
13008 the stub recognizes the packet or not. */
13009 fd
= remote_hostio_open (NULL
, "just probing",
13010 FILEIO_O_RDONLY
, 0700, 0,
13014 remote_hostio_close (fd
, &remote_errno
);
13016 ps
= m_features
.packet_support (PACKET_vFile_open
);
13019 if (ps
== PACKET_DISABLE
)
13021 static int warning_issued
= 0;
13023 if (!warning_issued
)
13025 warning (_("remote target does not support file"
13026 " transfer, attempting to access files"
13027 " from local filesystem."));
13028 warning_issued
= 1;
13039 remote_hostio_error (fileio_error errnum
)
13041 int host_error
= fileio_error_to_host (errnum
);
13043 if (host_error
== -1)
13044 error (_("Unknown remote I/O error %d"), errnum
);
13046 error (_("Remote I/O error: %s"), safe_strerror (host_error
));
13049 /* A RAII wrapper around a remote file descriptor. */
13051 class scoped_remote_fd
13054 scoped_remote_fd (remote_target
*remote
, int fd
)
13055 : m_remote (remote
), m_fd (fd
)
13059 ~scoped_remote_fd ()
13065 fileio_error remote_errno
;
13066 m_remote
->remote_hostio_close (m_fd
, &remote_errno
);
13070 /* Swallow exception before it escapes the dtor. If
13071 something goes wrong, likely the connection is gone,
13072 and there's nothing else that can be done. */
13077 DISABLE_COPY_AND_ASSIGN (scoped_remote_fd
);
13079 /* Release ownership of the file descriptor, and return it. */
13080 ATTRIBUTE_UNUSED_RESULT
int release () noexcept
13087 /* Return the owned file descriptor. */
13088 int get () const noexcept
13094 /* The remote target. */
13095 remote_target
*m_remote
;
13097 /* The owned remote I/O file descriptor. */
13102 remote_file_put (const char *local_file
, const char *remote_file
, int from_tty
)
13104 remote_target
*remote
= get_current_remote_target ();
13106 if (remote
== nullptr)
13107 error (_("command can only be used with remote target"));
13109 remote
->remote_file_put (local_file
, remote_file
, from_tty
);
13113 remote_target::remote_file_put (const char *local_file
, const char *remote_file
,
13116 int retcode
, bytes
, io_size
;
13117 fileio_error remote_errno
;
13118 int bytes_in_buffer
;
13122 gdb_file_up file
= gdb_fopen_cloexec (local_file
, "rb");
13124 perror_with_name (local_file
);
13126 scoped_remote_fd fd
13127 (this, remote_hostio_open (NULL
,
13128 remote_file
, (FILEIO_O_WRONLY
| FILEIO_O_CREAT
13130 0700, 0, &remote_errno
));
13131 if (fd
.get () == -1)
13132 remote_hostio_error (remote_errno
);
13134 /* Send up to this many bytes at once. They won't all fit in the
13135 remote packet limit, so we'll transfer slightly fewer. */
13136 io_size
= get_remote_packet_size ();
13137 gdb::byte_vector
buffer (io_size
);
13139 bytes_in_buffer
= 0;
13142 while (bytes_in_buffer
|| !saw_eof
)
13146 bytes
= fread (buffer
.data () + bytes_in_buffer
, 1,
13147 io_size
- bytes_in_buffer
,
13151 if (ferror (file
.get ()))
13152 error (_("Error reading %s."), local_file
);
13155 /* EOF. Unless there is something still in the
13156 buffer from the last iteration, we are done. */
13158 if (bytes_in_buffer
== 0)
13166 bytes
+= bytes_in_buffer
;
13167 bytes_in_buffer
= 0;
13169 retcode
= remote_hostio_pwrite (fd
.get (), buffer
.data (), bytes
,
13170 offset
, &remote_errno
);
13173 remote_hostio_error (remote_errno
);
13174 else if (retcode
== 0)
13175 error (_("Remote write of %d bytes returned 0!"), bytes
);
13176 else if (retcode
< bytes
)
13178 /* Short write. Save the rest of the read data for the next
13180 bytes_in_buffer
= bytes
- retcode
;
13181 memmove (buffer
.data (), buffer
.data () + retcode
, bytes_in_buffer
);
13187 if (remote_hostio_close (fd
.release (), &remote_errno
))
13188 remote_hostio_error (remote_errno
);
13191 gdb_printf (_("Successfully sent file \"%s\".\n"), local_file
);
13195 remote_file_get (const char *remote_file
, const char *local_file
, int from_tty
)
13197 remote_target
*remote
= get_current_remote_target ();
13199 if (remote
== nullptr)
13200 error (_("command can only be used with remote target"));
13202 remote
->remote_file_get (remote_file
, local_file
, from_tty
);
13206 remote_target::remote_file_get (const char *remote_file
, const char *local_file
,
13209 fileio_error remote_errno
;
13210 int bytes
, io_size
;
13213 scoped_remote_fd fd
13214 (this, remote_hostio_open (NULL
,
13215 remote_file
, FILEIO_O_RDONLY
, 0, 0,
13217 if (fd
.get () == -1)
13218 remote_hostio_error (remote_errno
);
13220 gdb_file_up file
= gdb_fopen_cloexec (local_file
, "wb");
13222 perror_with_name (local_file
);
13224 /* Send up to this many bytes at once. They won't all fit in the
13225 remote packet limit, so we'll transfer slightly fewer. */
13226 io_size
= get_remote_packet_size ();
13227 gdb::byte_vector
buffer (io_size
);
13232 bytes
= remote_hostio_pread (fd
.get (), buffer
.data (), io_size
, offset
,
13235 /* Success, but no bytes, means end-of-file. */
13238 remote_hostio_error (remote_errno
);
13242 bytes
= fwrite (buffer
.data (), 1, bytes
, file
.get ());
13244 perror_with_name (local_file
);
13247 if (remote_hostio_close (fd
.release (), &remote_errno
))
13248 remote_hostio_error (remote_errno
);
13251 gdb_printf (_("Successfully fetched file \"%s\".\n"), remote_file
);
13255 remote_file_delete (const char *remote_file
, int from_tty
)
13257 remote_target
*remote
= get_current_remote_target ();
13259 if (remote
== nullptr)
13260 error (_("command can only be used with remote target"));
13262 remote
->remote_file_delete (remote_file
, from_tty
);
13266 remote_target::remote_file_delete (const char *remote_file
, int from_tty
)
13269 fileio_error remote_errno
;
13271 retcode
= remote_hostio_unlink (NULL
, remote_file
, &remote_errno
);
13273 remote_hostio_error (remote_errno
);
13276 gdb_printf (_("Successfully deleted file \"%s\".\n"), remote_file
);
13280 remote_put_command (const char *args
, int from_tty
)
13283 error_no_arg (_("file to put"));
13285 gdb_argv
argv (args
);
13286 if (argv
[0] == NULL
|| argv
[1] == NULL
|| argv
[2] != NULL
)
13287 error (_("Invalid parameters to remote put"));
13289 remote_file_put (argv
[0], argv
[1], from_tty
);
13293 remote_get_command (const char *args
, int from_tty
)
13296 error_no_arg (_("file to get"));
13298 gdb_argv
argv (args
);
13299 if (argv
[0] == NULL
|| argv
[1] == NULL
|| argv
[2] != NULL
)
13300 error (_("Invalid parameters to remote get"));
13302 remote_file_get (argv
[0], argv
[1], from_tty
);
13306 remote_delete_command (const char *args
, int from_tty
)
13309 error_no_arg (_("file to delete"));
13311 gdb_argv
argv (args
);
13312 if (argv
[0] == NULL
|| argv
[1] != NULL
)
13313 error (_("Invalid parameters to remote delete"));
13315 remote_file_delete (argv
[0], from_tty
);
13319 remote_target::can_execute_reverse ()
13321 if (m_features
.packet_support (PACKET_bs
) == PACKET_ENABLE
13322 || m_features
.packet_support (PACKET_bc
) == PACKET_ENABLE
)
13329 remote_target::supports_non_stop ()
13335 remote_target::supports_disable_randomization ()
13337 /* Only supported in extended mode. */
13342 remote_target::supports_multi_process ()
13344 return m_features
.remote_multi_process_p ();
13348 remote_target::remote_supports_cond_tracepoints ()
13350 return (m_features
.packet_support (PACKET_ConditionalTracepoints
)
13355 remote_target::supports_evaluation_of_breakpoint_conditions ()
13357 return (m_features
.packet_support (PACKET_ConditionalBreakpoints
)
13362 remote_target::remote_supports_fast_tracepoints ()
13364 return m_features
.packet_support (PACKET_FastTracepoints
) == PACKET_ENABLE
;
13368 remote_target::remote_supports_static_tracepoints ()
13370 return m_features
.packet_support (PACKET_StaticTracepoints
) == PACKET_ENABLE
;
13374 remote_target::remote_supports_install_in_trace ()
13376 return m_features
.packet_support (PACKET_InstallInTrace
) == PACKET_ENABLE
;
13380 remote_target::supports_enable_disable_tracepoint ()
13382 return (m_features
.packet_support (PACKET_EnableDisableTracepoints_feature
)
13387 remote_target::supports_string_tracing ()
13389 return m_features
.packet_support (PACKET_tracenz_feature
) == PACKET_ENABLE
;
13393 remote_target::can_run_breakpoint_commands ()
13395 return m_features
.packet_support (PACKET_BreakpointCommands
) == PACKET_ENABLE
;
13399 remote_target::trace_init ()
13401 struct remote_state
*rs
= get_remote_state ();
13404 remote_get_noisy_reply ();
13405 if (strcmp (rs
->buf
.data (), "OK") != 0)
13406 error (_("Target does not support this command."));
13409 /* Recursive routine to walk through command list including loops, and
13410 download packets for each command. */
13413 remote_target::remote_download_command_source (int num
, ULONGEST addr
,
13414 struct command_line
*cmds
)
13416 struct remote_state
*rs
= get_remote_state ();
13417 struct command_line
*cmd
;
13419 for (cmd
= cmds
; cmd
; cmd
= cmd
->next
)
13421 QUIT
; /* Allow user to bail out with ^C. */
13422 strcpy (rs
->buf
.data (), "QTDPsrc:");
13423 encode_source_string (num
, addr
, "cmd", cmd
->line
,
13424 rs
->buf
.data () + strlen (rs
->buf
.data ()),
13425 rs
->buf
.size () - strlen (rs
->buf
.data ()));
13427 remote_get_noisy_reply ();
13428 if (strcmp (rs
->buf
.data (), "OK"))
13429 warning (_("Target does not support source download."));
13431 if (cmd
->control_type
== while_control
13432 || cmd
->control_type
== while_stepping_control
)
13434 remote_download_command_source (num
, addr
, cmd
->body_list_0
.get ());
13436 QUIT
; /* Allow user to bail out with ^C. */
13437 strcpy (rs
->buf
.data (), "QTDPsrc:");
13438 encode_source_string (num
, addr
, "cmd", "end",
13439 rs
->buf
.data () + strlen (rs
->buf
.data ()),
13440 rs
->buf
.size () - strlen (rs
->buf
.data ()));
13442 remote_get_noisy_reply ();
13443 if (strcmp (rs
->buf
.data (), "OK"))
13444 warning (_("Target does not support source download."));
13450 remote_target::download_tracepoint (struct bp_location
*loc
)
13454 std::vector
<std::string
> tdp_actions
;
13455 std::vector
<std::string
> stepping_actions
;
13457 struct breakpoint
*b
= loc
->owner
;
13458 tracepoint
*t
= gdb::checked_static_cast
<tracepoint
*> (b
);
13459 struct remote_state
*rs
= get_remote_state ();
13461 const char *err_msg
= _("Tracepoint packet too large for target.");
13464 /* We use a buffer other than rs->buf because we'll build strings
13465 across multiple statements, and other statements in between could
13467 gdb::char_vector
buf (get_remote_packet_size ());
13469 encode_actions_rsp (loc
, &tdp_actions
, &stepping_actions
);
13471 tpaddr
= loc
->address
;
13472 strcpy (addrbuf
, phex (tpaddr
, sizeof (CORE_ADDR
)));
13473 ret
= snprintf (buf
.data (), buf
.size (), "QTDP:%x:%s:%c:%lx:%x",
13474 b
->number
, addrbuf
, /* address */
13475 (b
->enable_state
== bp_enabled
? 'E' : 'D'),
13476 t
->step_count
, t
->pass_count
);
13478 if (ret
< 0 || ret
>= buf
.size ())
13479 error ("%s", err_msg
);
13481 /* Fast tracepoints are mostly handled by the target, but we can
13482 tell the target how big of an instruction block should be moved
13484 if (b
->type
== bp_fast_tracepoint
)
13486 /* Only test for support at download time; we may not know
13487 target capabilities at definition time. */
13488 if (remote_supports_fast_tracepoints ())
13490 if (gdbarch_fast_tracepoint_valid_at (loc
->gdbarch
, tpaddr
,
13493 size_left
= buf
.size () - strlen (buf
.data ());
13494 ret
= snprintf (buf
.data () + strlen (buf
.data ()),
13496 gdb_insn_length (loc
->gdbarch
, tpaddr
));
13498 if (ret
< 0 || ret
>= size_left
)
13499 error ("%s", err_msg
);
13502 /* If it passed validation at definition but fails now,
13503 something is very wrong. */
13504 internal_error (_("Fast tracepoint not valid during download"));
13507 /* Fast tracepoints are functionally identical to regular
13508 tracepoints, so don't take lack of support as a reason to
13509 give up on the trace run. */
13510 warning (_("Target does not support fast tracepoints, "
13511 "downloading %d as regular tracepoint"), b
->number
);
13513 else if (b
->type
== bp_static_tracepoint
13514 || b
->type
== bp_static_marker_tracepoint
)
13516 /* Only test for support at download time; we may not know
13517 target capabilities at definition time. */
13518 if (remote_supports_static_tracepoints ())
13520 struct static_tracepoint_marker marker
;
13522 if (target_static_tracepoint_marker_at (tpaddr
, &marker
))
13524 size_left
= buf
.size () - strlen (buf
.data ());
13525 ret
= snprintf (buf
.data () + strlen (buf
.data ()),
13528 if (ret
< 0 || ret
>= size_left
)
13529 error ("%s", err_msg
);
13532 error (_("Static tracepoint not valid during download"));
13535 /* Fast tracepoints are functionally identical to regular
13536 tracepoints, so don't take lack of support as a reason
13537 to give up on the trace run. */
13538 error (_("Target does not support static tracepoints"));
13540 /* If the tracepoint has a conditional, make it into an agent
13541 expression and append to the definition. */
13544 /* Only test support at download time, we may not know target
13545 capabilities at definition time. */
13546 if (remote_supports_cond_tracepoints ())
13548 agent_expr_up aexpr
= gen_eval_for_expr (tpaddr
,
13551 size_left
= buf
.size () - strlen (buf
.data ());
13553 ret
= snprintf (buf
.data () + strlen (buf
.data ()),
13554 size_left
, ":X%x,", (int) aexpr
->buf
.size ());
13556 if (ret
< 0 || ret
>= size_left
)
13557 error ("%s", err_msg
);
13559 size_left
= buf
.size () - strlen (buf
.data ());
13561 /* Two bytes to encode each aexpr byte, plus the terminating
13563 if (aexpr
->buf
.size () * 2 + 1 > size_left
)
13564 error ("%s", err_msg
);
13566 pkt
= buf
.data () + strlen (buf
.data ());
13568 for (int ndx
= 0; ndx
< aexpr
->buf
.size (); ++ndx
)
13569 pkt
= pack_hex_byte (pkt
, aexpr
->buf
[ndx
]);
13573 warning (_("Target does not support conditional tracepoints, "
13574 "ignoring tp %d cond"), b
->number
);
13577 if (b
->commands
|| !default_collect
.empty ())
13579 size_left
= buf
.size () - strlen (buf
.data ());
13581 ret
= snprintf (buf
.data () + strlen (buf
.data ()),
13584 if (ret
< 0 || ret
>= size_left
)
13585 error ("%s", err_msg
);
13588 putpkt (buf
.data ());
13589 remote_get_noisy_reply ();
13590 if (strcmp (rs
->buf
.data (), "OK"))
13591 error (_("Target does not support tracepoints."));
13593 /* do_single_steps (t); */
13594 for (auto action_it
= tdp_actions
.begin ();
13595 action_it
!= tdp_actions
.end (); action_it
++)
13597 QUIT
; /* Allow user to bail out with ^C. */
13599 bool has_more
= ((action_it
+ 1) != tdp_actions
.end ()
13600 || !stepping_actions
.empty ());
13602 ret
= snprintf (buf
.data (), buf
.size (), "QTDP:-%x:%s:%s%c",
13603 b
->number
, addrbuf
, /* address */
13604 action_it
->c_str (),
13605 has_more
? '-' : 0);
13607 if (ret
< 0 || ret
>= buf
.size ())
13608 error ("%s", err_msg
);
13610 putpkt (buf
.data ());
13611 remote_get_noisy_reply ();
13612 if (strcmp (rs
->buf
.data (), "OK"))
13613 error (_("Error on target while setting tracepoints."));
13616 for (auto action_it
= stepping_actions
.begin ();
13617 action_it
!= stepping_actions
.end (); action_it
++)
13619 QUIT
; /* Allow user to bail out with ^C. */
13621 bool is_first
= action_it
== stepping_actions
.begin ();
13622 bool has_more
= (action_it
+ 1) != stepping_actions
.end ();
13624 ret
= snprintf (buf
.data (), buf
.size (), "QTDP:-%x:%s:%s%s%s",
13625 b
->number
, addrbuf
, /* address */
13626 is_first
? "S" : "",
13627 action_it
->c_str (),
13628 has_more
? "-" : "");
13630 if (ret
< 0 || ret
>= buf
.size ())
13631 error ("%s", err_msg
);
13633 putpkt (buf
.data ());
13634 remote_get_noisy_reply ();
13635 if (strcmp (rs
->buf
.data (), "OK"))
13636 error (_("Error on target while setting tracepoints."));
13639 if (m_features
.packet_support (PACKET_TracepointSource
) == PACKET_ENABLE
)
13641 if (b
->locspec
!= nullptr)
13643 ret
= snprintf (buf
.data (), buf
.size (), "QTDPsrc:");
13645 if (ret
< 0 || ret
>= buf
.size ())
13646 error ("%s", err_msg
);
13648 const char *str
= b
->locspec
->to_string ();
13649 encode_source_string (b
->number
, loc
->address
, "at", str
,
13650 buf
.data () + strlen (buf
.data ()),
13651 buf
.size () - strlen (buf
.data ()));
13652 putpkt (buf
.data ());
13653 remote_get_noisy_reply ();
13654 if (strcmp (rs
->buf
.data (), "OK"))
13655 warning (_("Target does not support source download."));
13657 if (b
->cond_string
)
13659 ret
= snprintf (buf
.data (), buf
.size (), "QTDPsrc:");
13661 if (ret
< 0 || ret
>= buf
.size ())
13662 error ("%s", err_msg
);
13664 encode_source_string (b
->number
, loc
->address
,
13665 "cond", b
->cond_string
.get (),
13666 buf
.data () + strlen (buf
.data ()),
13667 buf
.size () - strlen (buf
.data ()));
13668 putpkt (buf
.data ());
13669 remote_get_noisy_reply ();
13670 if (strcmp (rs
->buf
.data (), "OK"))
13671 warning (_("Target does not support source download."));
13673 remote_download_command_source (b
->number
, loc
->address
,
13674 breakpoint_commands (b
));
13679 remote_target::can_download_tracepoint ()
13681 struct remote_state
*rs
= get_remote_state ();
13682 struct trace_status
*ts
;
13685 /* Don't try to install tracepoints until we've relocated our
13686 symbols, and fetched and merged the target's tracepoint list with
13688 if (rs
->starting_up
)
13691 ts
= current_trace_status ();
13692 status
= get_trace_status (ts
);
13694 if (status
== -1 || !ts
->running_known
|| !ts
->running
)
13697 /* If we are in a tracing experiment, but remote stub doesn't support
13698 installing tracepoint in trace, we have to return. */
13699 if (!remote_supports_install_in_trace ())
13707 remote_target::download_trace_state_variable (const trace_state_variable
&tsv
)
13709 struct remote_state
*rs
= get_remote_state ();
13712 xsnprintf (rs
->buf
.data (), get_remote_packet_size (), "QTDV:%x:%s:%x:",
13713 tsv
.number
, phex ((ULONGEST
) tsv
.initial_value
, 8),
13715 p
= rs
->buf
.data () + strlen (rs
->buf
.data ());
13716 if ((p
- rs
->buf
.data ()) + tsv
.name
.length () * 2
13717 >= get_remote_packet_size ())
13718 error (_("Trace state variable name too long for tsv definition packet"));
13719 p
+= 2 * bin2hex ((gdb_byte
*) (tsv
.name
.data ()), p
, tsv
.name
.length ());
13722 remote_get_noisy_reply ();
13723 if (rs
->buf
[0] == '\0')
13724 error (_("Target does not support this command."));
13725 if (strcmp (rs
->buf
.data (), "OK") != 0)
13726 error (_("Error on target while downloading trace state variable."));
13730 remote_target::enable_tracepoint (struct bp_location
*location
)
13732 struct remote_state
*rs
= get_remote_state ();
13734 xsnprintf (rs
->buf
.data (), get_remote_packet_size (), "QTEnable:%x:%s",
13735 location
->owner
->number
,
13736 phex (location
->address
, sizeof (CORE_ADDR
)));
13738 remote_get_noisy_reply ();
13739 if (rs
->buf
[0] == '\0')
13740 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
13741 if (strcmp (rs
->buf
.data (), "OK") != 0)
13742 error (_("Error on target while enabling tracepoint."));
13746 remote_target::disable_tracepoint (struct bp_location
*location
)
13748 struct remote_state
*rs
= get_remote_state ();
13750 xsnprintf (rs
->buf
.data (), get_remote_packet_size (), "QTDisable:%x:%s",
13751 location
->owner
->number
,
13752 phex (location
->address
, sizeof (CORE_ADDR
)));
13754 remote_get_noisy_reply ();
13755 if (rs
->buf
[0] == '\0')
13756 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
13757 if (strcmp (rs
->buf
.data (), "OK") != 0)
13758 error (_("Error on target while disabling tracepoint."));
13762 remote_target::trace_set_readonly_regions ()
13765 bfd_size_type size
;
13769 bfd
*abfd
= current_program_space
->exec_bfd ();
13772 return; /* No information to give. */
13774 struct remote_state
*rs
= get_remote_state ();
13776 strcpy (rs
->buf
.data (), "QTro");
13777 offset
= strlen (rs
->buf
.data ());
13778 for (s
= abfd
->sections
; s
; s
= s
->next
)
13780 char tmp1
[40], tmp2
[40];
13783 if ((s
->flags
& SEC_LOAD
) == 0
13784 /* || (s->flags & SEC_CODE) == 0 */
13785 || (s
->flags
& SEC_READONLY
) == 0)
13789 vma
= bfd_section_vma (s
);
13790 size
= bfd_section_size (s
);
13791 bfd_sprintf_vma (abfd
, tmp1
, vma
);
13792 bfd_sprintf_vma (abfd
, tmp2
, vma
+ size
);
13793 sec_length
= 1 + strlen (tmp1
) + 1 + strlen (tmp2
);
13794 if (offset
+ sec_length
+ 1 > rs
->buf
.size ())
13796 if (m_features
.packet_support (PACKET_qXfer_traceframe_info
)
13799 Too many sections for read-only sections definition packet."));
13802 xsnprintf (rs
->buf
.data () + offset
, rs
->buf
.size () - offset
, ":%s,%s",
13804 offset
+= sec_length
;
13814 remote_target::trace_start ()
13816 struct remote_state
*rs
= get_remote_state ();
13818 putpkt ("QTStart");
13819 remote_get_noisy_reply ();
13820 if (rs
->buf
[0] == '\0')
13821 error (_("Target does not support this command."));
13822 if (strcmp (rs
->buf
.data (), "OK") != 0)
13823 error (_("Bogus reply from target: %s"), rs
->buf
.data ());
13827 remote_target::get_trace_status (struct trace_status
*ts
)
13829 /* Initialize it just to avoid a GCC false warning. */
13831 enum packet_result result
;
13832 struct remote_state
*rs
= get_remote_state ();
13834 if (m_features
.packet_support (PACKET_qTStatus
) == PACKET_DISABLE
)
13837 /* FIXME we need to get register block size some other way. */
13838 trace_regblock_size
13839 = rs
->get_remote_arch_state (current_inferior ()->arch ())->sizeof_g_packet
;
13841 putpkt ("qTStatus");
13845 p
= remote_get_noisy_reply ();
13847 catch (const gdb_exception_error
&ex
)
13849 if (ex
.error
!= TARGET_CLOSE_ERROR
)
13851 exception_fprintf (gdb_stderr
, ex
, "qTStatus: ");
13857 result
= m_features
.packet_ok (p
, PACKET_qTStatus
);
13859 /* If the remote target doesn't do tracing, flag it. */
13860 if (result
== PACKET_UNKNOWN
)
13863 /* We're working with a live target. */
13864 ts
->filename
= NULL
;
13867 error (_("Bogus trace status reply from target: %s"), rs
->buf
.data ());
13869 /* Function 'parse_trace_status' sets default value of each field of
13870 'ts' at first, so we don't have to do it here. */
13871 parse_trace_status (p
, ts
);
13873 return ts
->running
;
13877 remote_target::get_tracepoint_status (tracepoint
*tp
,
13878 struct uploaded_tp
*utp
)
13880 struct remote_state
*rs
= get_remote_state ();
13882 size_t size
= get_remote_packet_size ();
13887 tp
->traceframe_usage
= 0;
13888 for (bp_location
&loc
: tp
->locations ())
13890 /* If the tracepoint was never downloaded, don't go asking for
13892 if (tp
->number_on_target
== 0)
13894 xsnprintf (rs
->buf
.data (), size
, "qTP:%x:%s", tp
->number_on_target
,
13895 phex_nz (loc
.address
, 0));
13897 reply
= remote_get_noisy_reply ();
13898 if (reply
&& *reply
)
13901 parse_tracepoint_status (reply
+ 1, tp
, utp
);
13907 utp
->hit_count
= 0;
13908 utp
->traceframe_usage
= 0;
13909 xsnprintf (rs
->buf
.data (), size
, "qTP:%x:%s", utp
->number
,
13910 phex_nz (utp
->addr
, 0));
13912 reply
= remote_get_noisy_reply ();
13913 if (reply
&& *reply
)
13916 parse_tracepoint_status (reply
+ 1, tp
, utp
);
13922 remote_target::trace_stop ()
13924 struct remote_state
*rs
= get_remote_state ();
13927 remote_get_noisy_reply ();
13928 if (rs
->buf
[0] == '\0')
13929 error (_("Target does not support this command."));
13930 if (strcmp (rs
->buf
.data (), "OK") != 0)
13931 error (_("Bogus reply from target: %s"), rs
->buf
.data ());
13935 remote_target::trace_find (enum trace_find_type type
, int num
,
13936 CORE_ADDR addr1
, CORE_ADDR addr2
,
13939 struct remote_state
*rs
= get_remote_state ();
13940 char *endbuf
= rs
->buf
.data () + get_remote_packet_size ();
13942 int target_frameno
= -1, target_tracept
= -1;
13944 /* Lookups other than by absolute frame number depend on the current
13945 trace selected, so make sure it is correct on the remote end
13947 if (type
!= tfind_number
)
13948 set_remote_traceframe ();
13950 p
= rs
->buf
.data ();
13951 strcpy (p
, "QTFrame:");
13952 p
= strchr (p
, '\0');
13956 xsnprintf (p
, endbuf
- p
, "%x", num
);
13959 xsnprintf (p
, endbuf
- p
, "pc:%s", phex_nz (addr1
, 0));
13962 xsnprintf (p
, endbuf
- p
, "tdp:%x", num
);
13965 xsnprintf (p
, endbuf
- p
, "range:%s:%s", phex_nz (addr1
, 0),
13966 phex_nz (addr2
, 0));
13968 case tfind_outside
:
13969 xsnprintf (p
, endbuf
- p
, "outside:%s:%s", phex_nz (addr1
, 0),
13970 phex_nz (addr2
, 0));
13973 error (_("Unknown trace find type %d"), type
);
13977 reply
= remote_get_noisy_reply ();
13978 if (*reply
== '\0')
13979 error (_("Target does not support this command."));
13981 while (reply
&& *reply
)
13986 target_frameno
= (int) strtol (p
, &reply
, 16);
13988 error (_("Unable to parse trace frame number"));
13989 /* Don't update our remote traceframe number cache on failure
13990 to select a remote traceframe. */
13991 if (target_frameno
== -1)
13996 target_tracept
= (int) strtol (p
, &reply
, 16);
13998 error (_("Unable to parse tracepoint number"));
14000 case 'O': /* "OK"? */
14001 if (reply
[1] == 'K' && reply
[2] == '\0')
14004 error (_("Bogus reply from target: %s"), reply
);
14007 error (_("Bogus reply from target: %s"), reply
);
14010 *tpp
= target_tracept
;
14012 rs
->remote_traceframe_number
= target_frameno
;
14013 return target_frameno
;
14017 remote_target::get_trace_state_variable_value (int tsvnum
, LONGEST
*val
)
14019 struct remote_state
*rs
= get_remote_state ();
14023 set_remote_traceframe ();
14025 xsnprintf (rs
->buf
.data (), get_remote_packet_size (), "qTV:%x", tsvnum
);
14027 reply
= remote_get_noisy_reply ();
14028 if (reply
&& *reply
)
14032 unpack_varlen_hex (reply
+ 1, &uval
);
14033 *val
= (LONGEST
) uval
;
14041 remote_target::save_trace_data (const char *filename
)
14043 struct remote_state
*rs
= get_remote_state ();
14046 p
= rs
->buf
.data ();
14047 strcpy (p
, "QTSave:");
14049 if ((p
- rs
->buf
.data ()) + strlen (filename
) * 2
14050 >= get_remote_packet_size ())
14051 error (_("Remote file name too long for trace save packet"));
14052 p
+= 2 * bin2hex ((gdb_byte
*) filename
, p
, strlen (filename
));
14055 reply
= remote_get_noisy_reply ();
14056 if (*reply
== '\0')
14057 error (_("Target does not support this command."));
14058 if (strcmp (reply
, "OK") != 0)
14059 error (_("Bogus reply from target: %s"), reply
);
14063 /* This is basically a memory transfer, but needs to be its own packet
14064 because we don't know how the target actually organizes its trace
14065 memory, plus we want to be able to ask for as much as possible, but
14066 not be unhappy if we don't get as much as we ask for. */
14069 remote_target::get_raw_trace_data (gdb_byte
*buf
, ULONGEST offset
, LONGEST len
)
14071 struct remote_state
*rs
= get_remote_state ();
14076 p
= rs
->buf
.data ();
14077 strcpy (p
, "qTBuffer:");
14079 p
+= hexnumstr (p
, offset
);
14081 p
+= hexnumstr (p
, len
);
14085 reply
= remote_get_noisy_reply ();
14086 if (reply
&& *reply
)
14088 /* 'l' by itself means we're at the end of the buffer and
14089 there is nothing more to get. */
14093 /* Convert the reply into binary. Limit the number of bytes to
14094 convert according to our passed-in buffer size, rather than
14095 what was returned in the packet; if the target is
14096 unexpectedly generous and gives us a bigger reply than we
14097 asked for, we don't want to crash. */
14098 rslt
= hex2bin (reply
, buf
, len
);
14102 /* Something went wrong, flag as an error. */
14107 remote_target::set_disconnected_tracing (int val
)
14109 struct remote_state
*rs
= get_remote_state ();
14111 if (m_features
.packet_support (PACKET_DisconnectedTracing_feature
)
14116 xsnprintf (rs
->buf
.data (), get_remote_packet_size (),
14117 "QTDisconnected:%x", val
);
14119 reply
= remote_get_noisy_reply ();
14120 if (*reply
== '\0')
14121 error (_("Target does not support this command."));
14122 if (strcmp (reply
, "OK") != 0)
14123 error (_("Bogus reply from target: %s"), reply
);
14126 warning (_("Target does not support disconnected tracing."));
14130 remote_target::core_of_thread (ptid_t ptid
)
14132 thread_info
*info
= this->find_thread (ptid
);
14134 if (info
!= NULL
&& info
->priv
!= NULL
)
14135 return get_remote_thread_info (info
)->core
;
14141 remote_target::set_circular_trace_buffer (int val
)
14143 struct remote_state
*rs
= get_remote_state ();
14146 xsnprintf (rs
->buf
.data (), get_remote_packet_size (),
14147 "QTBuffer:circular:%x", val
);
14149 reply
= remote_get_noisy_reply ();
14150 if (*reply
== '\0')
14151 error (_("Target does not support this command."));
14152 if (strcmp (reply
, "OK") != 0)
14153 error (_("Bogus reply from target: %s"), reply
);
14157 remote_target::traceframe_info ()
14159 std::optional
<gdb::char_vector
> text
14160 = target_read_stralloc (current_inferior ()->top_target (),
14161 TARGET_OBJECT_TRACEFRAME_INFO
,
14164 return parse_traceframe_info (text
->data ());
14169 /* Handle the qTMinFTPILen packet. Returns the minimum length of
14170 instruction on which a fast tracepoint may be placed. Returns -1
14171 if the packet is not supported, and 0 if the minimum instruction
14172 length is unknown. */
14175 remote_target::get_min_fast_tracepoint_insn_len ()
14177 struct remote_state
*rs
= get_remote_state ();
14180 /* If we're not debugging a process yet, the IPA can't be
14182 if (!target_has_execution ())
14185 /* Make sure the remote is pointing at the right process. */
14186 set_general_process ();
14188 xsnprintf (rs
->buf
.data (), get_remote_packet_size (), "qTMinFTPILen");
14190 reply
= remote_get_noisy_reply ();
14191 if (*reply
== '\0')
14195 ULONGEST min_insn_len
;
14197 unpack_varlen_hex (reply
, &min_insn_len
);
14199 return (int) min_insn_len
;
14204 remote_target::set_trace_buffer_size (LONGEST val
)
14206 if (m_features
.packet_support (PACKET_QTBuffer_size
) != PACKET_DISABLE
)
14208 struct remote_state
*rs
= get_remote_state ();
14209 char *buf
= rs
->buf
.data ();
14210 char *endbuf
= buf
+ get_remote_packet_size ();
14211 enum packet_result result
;
14213 gdb_assert (val
>= 0 || val
== -1);
14214 buf
+= xsnprintf (buf
, endbuf
- buf
, "QTBuffer:size:");
14215 /* Send -1 as literal "-1" to avoid host size dependency. */
14219 buf
+= hexnumstr (buf
, (ULONGEST
) -val
);
14222 buf
+= hexnumstr (buf
, (ULONGEST
) val
);
14225 remote_get_noisy_reply ();
14226 result
= m_features
.packet_ok (rs
->buf
, PACKET_QTBuffer_size
);
14228 if (result
!= PACKET_OK
)
14229 warning (_("Bogus reply from target: %s"), rs
->buf
.data ());
14234 remote_target::set_trace_notes (const char *user
, const char *notes
,
14235 const char *stop_notes
)
14237 struct remote_state
*rs
= get_remote_state ();
14239 char *buf
= rs
->buf
.data ();
14240 char *endbuf
= buf
+ get_remote_packet_size ();
14243 buf
+= xsnprintf (buf
, endbuf
- buf
, "QTNotes:");
14246 buf
+= xsnprintf (buf
, endbuf
- buf
, "user:");
14247 nbytes
= bin2hex ((gdb_byte
*) user
, buf
, strlen (user
));
14253 buf
+= xsnprintf (buf
, endbuf
- buf
, "notes:");
14254 nbytes
= bin2hex ((gdb_byte
*) notes
, buf
, strlen (notes
));
14260 buf
+= xsnprintf (buf
, endbuf
- buf
, "tstop:");
14261 nbytes
= bin2hex ((gdb_byte
*) stop_notes
, buf
, strlen (stop_notes
));
14265 /* Ensure the buffer is terminated. */
14269 reply
= remote_get_noisy_reply ();
14270 if (*reply
== '\0')
14273 if (strcmp (reply
, "OK") != 0)
14274 error (_("Bogus reply from target: %s"), reply
);
14280 remote_target::use_agent (bool use
)
14282 if (m_features
.packet_support (PACKET_QAgent
) != PACKET_DISABLE
)
14284 struct remote_state
*rs
= get_remote_state ();
14286 /* If the stub supports QAgent. */
14287 xsnprintf (rs
->buf
.data (), get_remote_packet_size (), "QAgent:%d", use
);
14291 if (strcmp (rs
->buf
.data (), "OK") == 0)
14302 remote_target::can_use_agent ()
14304 return (m_features
.packet_support (PACKET_QAgent
) != PACKET_DISABLE
);
14307 #if defined (HAVE_LIBEXPAT)
14309 /* Check the btrace document version. */
14312 check_xml_btrace_version (struct gdb_xml_parser
*parser
,
14313 const struct gdb_xml_element
*element
,
14315 std::vector
<gdb_xml_value
> &attributes
)
14317 const char *version
14318 = (const char *) xml_find_attribute (attributes
, "version")->value
.get ();
14320 if (strcmp (version
, "1.0") != 0)
14321 gdb_xml_error (parser
, _("Unsupported btrace version: \"%s\""), version
);
14324 /* Parse a btrace "block" xml record. */
14327 parse_xml_btrace_block (struct gdb_xml_parser
*parser
,
14328 const struct gdb_xml_element
*element
,
14330 std::vector
<gdb_xml_value
> &attributes
)
14332 struct btrace_data
*btrace
;
14333 ULONGEST
*begin
, *end
;
14335 btrace
= (struct btrace_data
*) user_data
;
14337 switch (btrace
->format
)
14339 case BTRACE_FORMAT_BTS
:
14342 case BTRACE_FORMAT_NONE
:
14343 btrace
->format
= BTRACE_FORMAT_BTS
;
14344 btrace
->variant
.bts
.blocks
= new std::vector
<btrace_block
>;
14348 gdb_xml_error (parser
, _("Btrace format error."));
14351 begin
= (ULONGEST
*) xml_find_attribute (attributes
, "begin")->value
.get ();
14352 end
= (ULONGEST
*) xml_find_attribute (attributes
, "end")->value
.get ();
14353 btrace
->variant
.bts
.blocks
->emplace_back (*begin
, *end
);
14356 /* Parse a "raw" xml record. */
14359 parse_xml_raw (struct gdb_xml_parser
*parser
, const char *body_text
,
14360 gdb_byte
**pdata
, size_t *psize
)
14365 len
= strlen (body_text
);
14367 gdb_xml_error (parser
, _("Bad raw data size."));
14371 gdb::unique_xmalloc_ptr
<gdb_byte
> data ((gdb_byte
*) xmalloc (size
));
14374 /* We use hex encoding - see gdbsupport/rsp-low.h. */
14382 if (hi
== 0 || lo
== 0)
14383 gdb_xml_error (parser
, _("Bad hex encoding."));
14385 *bin
++ = fromhex (hi
) * 16 + fromhex (lo
);
14389 *pdata
= data
.release ();
14393 /* Parse a btrace pt-config "cpu" xml record. */
14396 parse_xml_btrace_pt_config_cpu (struct gdb_xml_parser
*parser
,
14397 const struct gdb_xml_element
*element
,
14399 std::vector
<gdb_xml_value
> &attributes
)
14401 struct btrace_data
*btrace
;
14402 const char *vendor
;
14403 ULONGEST
*family
, *model
, *stepping
;
14406 = (const char *) xml_find_attribute (attributes
, "vendor")->value
.get ();
14408 = (ULONGEST
*) xml_find_attribute (attributes
, "family")->value
.get ();
14410 = (ULONGEST
*) xml_find_attribute (attributes
, "model")->value
.get ();
14412 = (ULONGEST
*) xml_find_attribute (attributes
, "stepping")->value
.get ();
14414 btrace
= (struct btrace_data
*) user_data
;
14416 if (strcmp (vendor
, "GenuineIntel") == 0)
14417 btrace
->variant
.pt
.config
.cpu
.vendor
= CV_INTEL
;
14419 btrace
->variant
.pt
.config
.cpu
.family
= *family
;
14420 btrace
->variant
.pt
.config
.cpu
.model
= *model
;
14421 btrace
->variant
.pt
.config
.cpu
.stepping
= *stepping
;
14424 /* Parse a btrace pt "raw" xml record. */
14427 parse_xml_btrace_pt_raw (struct gdb_xml_parser
*parser
,
14428 const struct gdb_xml_element
*element
,
14429 void *user_data
, const char *body_text
)
14431 struct btrace_data
*btrace
;
14433 btrace
= (struct btrace_data
*) user_data
;
14434 parse_xml_raw (parser
, body_text
, &btrace
->variant
.pt
.data
,
14435 &btrace
->variant
.pt
.size
);
14438 /* Parse a btrace "pt" xml record. */
14441 parse_xml_btrace_pt (struct gdb_xml_parser
*parser
,
14442 const struct gdb_xml_element
*element
,
14444 std::vector
<gdb_xml_value
> &attributes
)
14446 struct btrace_data
*btrace
;
14448 btrace
= (struct btrace_data
*) user_data
;
14449 btrace
->format
= BTRACE_FORMAT_PT
;
14450 btrace
->variant
.pt
.config
.cpu
.vendor
= CV_UNKNOWN
;
14451 btrace
->variant
.pt
.data
= NULL
;
14452 btrace
->variant
.pt
.size
= 0;
14455 static const struct gdb_xml_attribute block_attributes
[] = {
14456 { "begin", GDB_XML_AF_NONE
, gdb_xml_parse_attr_ulongest
, NULL
},
14457 { "end", GDB_XML_AF_NONE
, gdb_xml_parse_attr_ulongest
, NULL
},
14458 { NULL
, GDB_XML_AF_NONE
, NULL
, NULL
}
14461 static const struct gdb_xml_attribute btrace_pt_config_cpu_attributes
[] = {
14462 { "vendor", GDB_XML_AF_NONE
, NULL
, NULL
},
14463 { "family", GDB_XML_AF_NONE
, gdb_xml_parse_attr_ulongest
, NULL
},
14464 { "model", GDB_XML_AF_NONE
, gdb_xml_parse_attr_ulongest
, NULL
},
14465 { "stepping", GDB_XML_AF_NONE
, gdb_xml_parse_attr_ulongest
, NULL
},
14466 { NULL
, GDB_XML_AF_NONE
, NULL
, NULL
}
14469 static const struct gdb_xml_element btrace_pt_config_children
[] = {
14470 { "cpu", btrace_pt_config_cpu_attributes
, NULL
, GDB_XML_EF_OPTIONAL
,
14471 parse_xml_btrace_pt_config_cpu
, NULL
},
14472 { NULL
, NULL
, NULL
, GDB_XML_EF_NONE
, NULL
, NULL
}
14475 static const struct gdb_xml_element btrace_pt_children
[] = {
14476 { "pt-config", NULL
, btrace_pt_config_children
, GDB_XML_EF_OPTIONAL
, NULL
,
14478 { "raw", NULL
, NULL
, GDB_XML_EF_OPTIONAL
, NULL
, parse_xml_btrace_pt_raw
},
14479 { NULL
, NULL
, NULL
, GDB_XML_EF_NONE
, NULL
, NULL
}
14482 static const struct gdb_xml_attribute btrace_attributes
[] = {
14483 { "version", GDB_XML_AF_NONE
, NULL
, NULL
},
14484 { NULL
, GDB_XML_AF_NONE
, NULL
, NULL
}
14487 static const struct gdb_xml_element btrace_children
[] = {
14488 { "block", block_attributes
, NULL
,
14489 GDB_XML_EF_REPEATABLE
| GDB_XML_EF_OPTIONAL
, parse_xml_btrace_block
, NULL
},
14490 { "pt", NULL
, btrace_pt_children
, GDB_XML_EF_OPTIONAL
, parse_xml_btrace_pt
,
14492 { NULL
, NULL
, NULL
, GDB_XML_EF_NONE
, NULL
, NULL
}
14495 static const struct gdb_xml_element btrace_elements
[] = {
14496 { "btrace", btrace_attributes
, btrace_children
, GDB_XML_EF_NONE
,
14497 check_xml_btrace_version
, NULL
},
14498 { NULL
, NULL
, NULL
, GDB_XML_EF_NONE
, NULL
, NULL
}
14501 #endif /* defined (HAVE_LIBEXPAT) */
14503 /* Parse a branch trace xml document XML into DATA. */
14506 parse_xml_btrace (struct btrace_data
*btrace
, const char *buffer
)
14508 #if defined (HAVE_LIBEXPAT)
14511 btrace_data result
;
14512 result
.format
= BTRACE_FORMAT_NONE
;
14514 errcode
= gdb_xml_parse_quick (_("btrace"), "btrace.dtd", btrace_elements
,
14517 error (_("Error parsing branch trace."));
14519 /* Keep parse results. */
14520 *btrace
= std::move (result
);
14522 #else /* !defined (HAVE_LIBEXPAT) */
14524 error (_("Cannot process branch trace. XML support was disabled at "
14527 #endif /* !defined (HAVE_LIBEXPAT) */
14530 #if defined (HAVE_LIBEXPAT)
14532 /* Parse a btrace-conf "bts" xml record. */
14535 parse_xml_btrace_conf_bts (struct gdb_xml_parser
*parser
,
14536 const struct gdb_xml_element
*element
,
14538 std::vector
<gdb_xml_value
> &attributes
)
14540 struct btrace_config
*conf
;
14541 struct gdb_xml_value
*size
;
14543 conf
= (struct btrace_config
*) user_data
;
14544 conf
->format
= BTRACE_FORMAT_BTS
;
14545 conf
->bts
.size
= 0;
14547 size
= xml_find_attribute (attributes
, "size");
14549 conf
->bts
.size
= (unsigned int) *(ULONGEST
*) size
->value
.get ();
14552 /* Parse a btrace-conf "pt" xml record. */
14555 parse_xml_btrace_conf_pt (struct gdb_xml_parser
*parser
,
14556 const struct gdb_xml_element
*element
,
14558 std::vector
<gdb_xml_value
> &attributes
)
14560 struct btrace_config
*conf
;
14561 struct gdb_xml_value
*size
;
14563 conf
= (struct btrace_config
*) user_data
;
14564 conf
->format
= BTRACE_FORMAT_PT
;
14567 size
= xml_find_attribute (attributes
, "size");
14569 conf
->pt
.size
= (unsigned int) *(ULONGEST
*) size
->value
.get ();
14572 static const struct gdb_xml_attribute btrace_conf_pt_attributes
[] = {
14573 { "size", GDB_XML_AF_OPTIONAL
, gdb_xml_parse_attr_ulongest
, NULL
},
14574 { NULL
, GDB_XML_AF_NONE
, NULL
, NULL
}
14577 static const struct gdb_xml_attribute btrace_conf_bts_attributes
[] = {
14578 { "size", GDB_XML_AF_OPTIONAL
, gdb_xml_parse_attr_ulongest
, NULL
},
14579 { NULL
, GDB_XML_AF_NONE
, NULL
, NULL
}
14582 static const struct gdb_xml_element btrace_conf_children
[] = {
14583 { "bts", btrace_conf_bts_attributes
, NULL
, GDB_XML_EF_OPTIONAL
,
14584 parse_xml_btrace_conf_bts
, NULL
},
14585 { "pt", btrace_conf_pt_attributes
, NULL
, GDB_XML_EF_OPTIONAL
,
14586 parse_xml_btrace_conf_pt
, NULL
},
14587 { NULL
, NULL
, NULL
, GDB_XML_EF_NONE
, NULL
, NULL
}
14590 static const struct gdb_xml_attribute btrace_conf_attributes
[] = {
14591 { "version", GDB_XML_AF_NONE
, NULL
, NULL
},
14592 { NULL
, GDB_XML_AF_NONE
, NULL
, NULL
}
14595 static const struct gdb_xml_element btrace_conf_elements
[] = {
14596 { "btrace-conf", btrace_conf_attributes
, btrace_conf_children
,
14597 GDB_XML_EF_NONE
, NULL
, NULL
},
14598 { NULL
, NULL
, NULL
, GDB_XML_EF_NONE
, NULL
, NULL
}
14601 #endif /* defined (HAVE_LIBEXPAT) */
14603 /* Parse a branch trace configuration xml document XML into CONF. */
14606 parse_xml_btrace_conf (struct btrace_config
*conf
, const char *xml
)
14608 #if defined (HAVE_LIBEXPAT)
14611 errcode
= gdb_xml_parse_quick (_("btrace-conf"), "btrace-conf.dtd",
14612 btrace_conf_elements
, xml
, conf
);
14614 error (_("Error parsing branch trace configuration."));
14616 #else /* !defined (HAVE_LIBEXPAT) */
14618 error (_("Cannot process the branch trace configuration. XML support "
14619 "was disabled at compile time."));
14621 #endif /* !defined (HAVE_LIBEXPAT) */
14624 /* Reset our idea of our target's btrace configuration. */
14627 remote_btrace_reset (remote_state
*rs
)
14629 memset (&rs
->btrace_config
, 0, sizeof (rs
->btrace_config
));
14632 /* Synchronize the configuration with the target. */
14635 remote_target::btrace_sync_conf (const btrace_config
*conf
)
14637 struct remote_state
*rs
;
14638 char *buf
, *pos
, *endbuf
;
14640 rs
= get_remote_state ();
14641 buf
= rs
->buf
.data ();
14642 endbuf
= buf
+ get_remote_packet_size ();
14644 if (m_features
.packet_support (PACKET_Qbtrace_conf_bts_size
) == PACKET_ENABLE
14645 && conf
->bts
.size
!= rs
->btrace_config
.bts
.size
)
14648 pos
+= xsnprintf (pos
, endbuf
- pos
, "%s=0x%x",
14649 packets_descriptions
[PACKET_Qbtrace_conf_bts_size
].name
,
14655 if (m_features
.packet_ok (buf
, PACKET_Qbtrace_conf_bts_size
)
14658 if (buf
[0] == 'E' && buf
[1] == '.')
14659 error (_("Failed to configure the BTS buffer size: %s"), buf
+ 2);
14661 error (_("Failed to configure the BTS buffer size."));
14664 rs
->btrace_config
.bts
.size
= conf
->bts
.size
;
14667 if (m_features
.packet_support (PACKET_Qbtrace_conf_pt_size
) == PACKET_ENABLE
14668 && conf
->pt
.size
!= rs
->btrace_config
.pt
.size
)
14671 pos
+= xsnprintf (pos
, endbuf
- pos
, "%s=0x%x",
14672 packets_descriptions
[PACKET_Qbtrace_conf_pt_size
].name
,
14678 if (m_features
.packet_ok (buf
, PACKET_Qbtrace_conf_pt_size
)
14681 if (buf
[0] == 'E' && buf
[1] == '.')
14682 error (_("Failed to configure the trace buffer size: %s"), buf
+ 2);
14684 error (_("Failed to configure the trace buffer size."));
14687 rs
->btrace_config
.pt
.size
= conf
->pt
.size
;
14691 /* Read TP's btrace configuration from the target and store it into CONF. */
14694 btrace_read_config (thread_info
*tp
, btrace_config
*conf
)
14696 /* target_read_stralloc relies on INFERIOR_PTID. */
14697 scoped_restore_current_thread restore_thread
;
14698 switch_to_thread (tp
);
14700 std::optional
<gdb::char_vector
> xml
14701 = target_read_stralloc (current_inferior ()->top_target (),
14702 TARGET_OBJECT_BTRACE_CONF
, "");
14704 parse_xml_btrace_conf (conf
, xml
->data ());
14707 /* Maybe reopen target btrace. */
14710 remote_target::remote_btrace_maybe_reopen ()
14712 struct remote_state
*rs
= get_remote_state ();
14713 int btrace_target_pushed
= 0;
14714 #if !defined (HAVE_LIBIPT)
14718 /* Don't bother walking the entirety of the remote thread list when
14719 we know the feature isn't supported by the remote. */
14720 if (m_features
.packet_support (PACKET_qXfer_btrace_conf
) != PACKET_ENABLE
)
14723 for (thread_info
*tp
: all_non_exited_threads (this))
14725 memset (&rs
->btrace_config
, 0x00, sizeof (struct btrace_config
));
14726 btrace_read_config (tp
, &rs
->btrace_config
);
14728 if (rs
->btrace_config
.format
== BTRACE_FORMAT_NONE
)
14731 #if !defined (HAVE_LIBIPT)
14732 if (rs
->btrace_config
.format
== BTRACE_FORMAT_PT
)
14737 warning (_("Target is recording using Intel Processor Trace "
14738 "but support was disabled at compile time."));
14743 #endif /* !defined (HAVE_LIBIPT) */
14745 /* Push target, once, but before anything else happens. This way our
14746 changes to the threads will be cleaned up by unpushing the target
14747 in case btrace_read_config () throws. */
14748 if (!btrace_target_pushed
)
14750 btrace_target_pushed
= 1;
14751 record_btrace_push_target ();
14752 gdb_printf (_("Target is recording using %s.\n"),
14753 btrace_format_string (rs
->btrace_config
.format
));
14757 = new btrace_target_info
{ tp
->ptid
, rs
->btrace_config
};
14761 /* Enable branch tracing. */
14763 struct btrace_target_info
*
14764 remote_target::enable_btrace (thread_info
*tp
,
14765 const struct btrace_config
*conf
)
14767 struct packet_config
*packet
= NULL
;
14768 struct remote_state
*rs
= get_remote_state ();
14769 char *buf
= rs
->buf
.data ();
14770 char *endbuf
= buf
+ get_remote_packet_size ();
14772 unsigned int which_packet
;
14773 switch (conf
->format
)
14775 case BTRACE_FORMAT_BTS
:
14776 which_packet
= PACKET_Qbtrace_bts
;
14778 case BTRACE_FORMAT_PT
:
14779 which_packet
= PACKET_Qbtrace_pt
;
14782 internal_error (_("Bad branch btrace format: %u."),
14783 (unsigned int) conf
->format
);
14786 packet
= &m_features
.m_protocol_packets
[which_packet
];
14787 if (packet
== NULL
|| packet_config_support (packet
) != PACKET_ENABLE
)
14788 error (_("Target does not support branch tracing."));
14790 btrace_sync_conf (conf
);
14792 ptid_t ptid
= tp
->ptid
;
14793 set_general_thread (ptid
);
14795 buf
+= xsnprintf (buf
, endbuf
- buf
, "%s",
14796 packets_descriptions
[which_packet
].name
);
14800 if (m_features
.packet_ok (rs
->buf
, which_packet
) == PACKET_ERROR
)
14802 if (rs
->buf
[0] == 'E' && rs
->buf
[1] == '.')
14803 error (_("Could not enable branch tracing for %s: %s"),
14804 target_pid_to_str (ptid
).c_str (), &rs
->buf
[2]);
14806 error (_("Could not enable branch tracing for %s."),
14807 target_pid_to_str (ptid
).c_str ());
14810 btrace_target_info
*tinfo
= new btrace_target_info
{ ptid
};
14812 /* If we fail to read the configuration, we lose some information, but the
14813 tracing itself is not impacted. */
14816 btrace_read_config (tp
, &tinfo
->conf
);
14818 catch (const gdb_exception_error
&err
)
14820 if (err
.message
!= NULL
)
14821 warning ("%s", err
.what ());
14827 /* Disable branch tracing. */
14830 remote_target::disable_btrace (struct btrace_target_info
*tinfo
)
14832 struct remote_state
*rs
= get_remote_state ();
14833 char *buf
= rs
->buf
.data ();
14834 char *endbuf
= buf
+ get_remote_packet_size ();
14836 if (m_features
.packet_support (PACKET_Qbtrace_off
) != PACKET_ENABLE
)
14837 error (_("Target does not support branch tracing."));
14839 set_general_thread (tinfo
->ptid
);
14841 buf
+= xsnprintf (buf
, endbuf
- buf
, "%s",
14842 packets_descriptions
[PACKET_Qbtrace_off
].name
);
14846 if (m_features
.packet_ok (rs
->buf
, PACKET_Qbtrace_off
) == PACKET_ERROR
)
14848 if (rs
->buf
[0] == 'E' && rs
->buf
[1] == '.')
14849 error (_("Could not disable branch tracing for %s: %s"),
14850 target_pid_to_str (tinfo
->ptid
).c_str (), &rs
->buf
[2]);
14852 error (_("Could not disable branch tracing for %s."),
14853 target_pid_to_str (tinfo
->ptid
).c_str ());
14859 /* Teardown branch tracing. */
14862 remote_target::teardown_btrace (struct btrace_target_info
*tinfo
)
14864 /* We must not talk to the target during teardown. */
14868 /* Read the branch trace. */
14871 remote_target::read_btrace (struct btrace_data
*btrace
,
14872 struct btrace_target_info
*tinfo
,
14873 enum btrace_read_type type
)
14877 if (m_features
.packet_support (PACKET_qXfer_btrace
) != PACKET_ENABLE
)
14878 error (_("Target does not support branch tracing."));
14880 #if !defined(HAVE_LIBEXPAT)
14881 error (_("Cannot process branch tracing result. XML parsing not supported."));
14886 case BTRACE_READ_ALL
:
14889 case BTRACE_READ_NEW
:
14892 case BTRACE_READ_DELTA
:
14896 internal_error (_("Bad branch tracing read type: %u."),
14897 (unsigned int) type
);
14900 std::optional
<gdb::char_vector
> xml
14901 = target_read_stralloc (current_inferior ()->top_target (),
14902 TARGET_OBJECT_BTRACE
, annex
);
14904 return BTRACE_ERR_UNKNOWN
;
14906 parse_xml_btrace (btrace
, xml
->data ());
14908 return BTRACE_ERR_NONE
;
14911 const struct btrace_config
*
14912 remote_target::btrace_conf (const struct btrace_target_info
*tinfo
)
14914 return &tinfo
->conf
;
14918 remote_target::augmented_libraries_svr4_read ()
14921 (m_features
.packet_support (PACKET_augmented_libraries_svr4_read_feature
)
14925 /* Implementation of to_load. */
14928 remote_target::load (const char *name
, int from_tty
)
14930 generic_load (name
, from_tty
);
14933 /* Accepts an integer PID; returns a string representing a file that
14934 can be opened on the remote side to get the symbols for the child
14935 process. Returns NULL if the operation is not supported. */
14938 remote_target::pid_to_exec_file (int pid
)
14940 static std::optional
<gdb::char_vector
> filename
;
14941 char *annex
= NULL
;
14943 if (m_features
.packet_support (PACKET_qXfer_exec_file
) != PACKET_ENABLE
)
14946 inferior
*inf
= find_inferior_pid (this, pid
);
14948 internal_error (_("not currently attached to process %d"), pid
);
14950 if (!inf
->fake_pid_p
)
14952 const int annex_size
= 9;
14954 annex
= (char *) alloca (annex_size
);
14955 xsnprintf (annex
, annex_size
, "%x", pid
);
14958 filename
= target_read_stralloc (current_inferior ()->top_target (),
14959 TARGET_OBJECT_EXEC_FILE
, annex
);
14961 return filename
? filename
->data () : nullptr;
14964 /* Implement the to_can_do_single_step target_ops method. */
14967 remote_target::can_do_single_step ()
14969 /* We can only tell whether target supports single step or not by
14970 supported s and S vCont actions if the stub supports vContSupported
14971 feature. If the stub doesn't support vContSupported feature,
14972 we have conservatively to think target doesn't supports single
14974 if (m_features
.packet_support (PACKET_vContSupported
) == PACKET_ENABLE
)
14976 struct remote_state
*rs
= get_remote_state ();
14978 return rs
->supports_vCont
.s
&& rs
->supports_vCont
.S
;
14984 /* Implementation of the to_execution_direction method for the remote
14987 enum exec_direction_kind
14988 remote_target::execution_direction ()
14990 struct remote_state
*rs
= get_remote_state ();
14992 return rs
->last_resume_exec_dir
;
14995 /* Return pointer to the thread_info struct which corresponds to
14996 THREAD_HANDLE (having length HANDLE_LEN). */
14999 remote_target::thread_handle_to_thread_info (const gdb_byte
*thread_handle
,
15003 for (thread_info
*tp
: all_non_exited_threads (this))
15005 remote_thread_info
*priv
= get_remote_thread_info (tp
);
15007 if (tp
->inf
== inf
&& priv
!= NULL
)
15009 if (handle_len
!= priv
->thread_handle
.size ())
15010 error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
15011 handle_len
, priv
->thread_handle
.size ());
15012 if (memcmp (thread_handle
, priv
->thread_handle
.data (),
15021 gdb::array_view
<const gdb_byte
>
15022 remote_target::thread_info_to_thread_handle (struct thread_info
*tp
)
15024 remote_thread_info
*priv
= get_remote_thread_info (tp
);
15025 return priv
->thread_handle
;
15029 remote_target::can_async_p ()
15031 /* This flag should be checked in the common target.c code. */
15032 gdb_assert (target_async_permitted
);
15034 /* We're async whenever the serial device can. */
15035 return get_remote_state ()->can_async_p ();
15039 remote_target::is_async_p ()
15041 /* We're async whenever the serial device is. */
15042 return get_remote_state ()->is_async_p ();
15045 /* Pass the SERIAL event on and up to the client. One day this code
15046 will be able to delay notifying the client of an event until the
15047 point where an entire packet has been received. */
15049 static serial_event_ftype remote_async_serial_handler
;
15052 remote_async_serial_handler (struct serial
*scb
, void *context
)
15054 /* Don't propogate error information up to the client. Instead let
15055 the client find out about the error by querying the target. */
15056 inferior_event_handler (INF_REG_EVENT
);
15060 remote_target::async_wait_fd ()
15062 struct remote_state
*rs
= get_remote_state ();
15063 return rs
->remote_desc
->fd
;
15067 remote_target::async (bool enable
)
15069 struct remote_state
*rs
= get_remote_state ();
15073 serial_async (rs
->remote_desc
, remote_async_serial_handler
, rs
);
15075 /* If there are pending events in the stop reply queue tell the
15076 event loop to process them. */
15077 if (!rs
->stop_reply_queue
.empty ())
15078 rs
->mark_async_event_handler ();
15080 /* For simplicity, below we clear the pending events token
15081 without remembering whether it is marked, so here we always
15082 mark it. If there's actually no pending notification to
15083 process, this ends up being a no-op (other than a spurious
15084 event-loop wakeup). */
15085 if (target_is_non_stop_p ())
15086 mark_async_event_handler (rs
->notif_state
->get_pending_events_token
);
15090 serial_async (rs
->remote_desc
, NULL
, NULL
);
15091 /* If the core is disabling async, it doesn't want to be
15092 disturbed with target events. Clear all async event sources
15094 rs
->clear_async_event_handler ();
15096 if (target_is_non_stop_p ())
15097 clear_async_event_handler (rs
->notif_state
->get_pending_events_token
);
15101 /* Implementation of the to_thread_events method. */
15104 remote_target::thread_events (int enable
)
15106 struct remote_state
*rs
= get_remote_state ();
15107 size_t size
= get_remote_packet_size ();
15109 if (m_features
.packet_support (PACKET_QThreadEvents
) == PACKET_DISABLE
)
15112 if (rs
->last_thread_events
== enable
)
15115 xsnprintf (rs
->buf
.data (), size
, "QThreadEvents:%x", enable
? 1 : 0);
15119 switch (m_features
.packet_ok (rs
->buf
, PACKET_QThreadEvents
))
15122 if (strcmp (rs
->buf
.data (), "OK") != 0)
15123 error (_("Remote refused setting thread events: %s"), rs
->buf
.data ());
15124 rs
->last_thread_events
= enable
;
15127 warning (_("Remote failure reply: %s"), rs
->buf
.data ());
15129 case PACKET_UNKNOWN
:
15134 /* Implementation of the supports_set_thread_options target
15138 remote_target::supports_set_thread_options (gdb_thread_options options
)
15140 remote_state
*rs
= get_remote_state ();
15141 return (m_features
.packet_support (PACKET_QThreadOptions
) == PACKET_ENABLE
15142 && (rs
->supported_thread_options
& options
) == options
);
15145 /* For coalescing reasons, actually sending the options to the target
15146 happens at resume time, via this function. See target_resume for
15147 all-stop, and target_commit_resumed for non-stop. */
15150 remote_target::commit_requested_thread_options ()
15152 struct remote_state
*rs
= get_remote_state ();
15154 if (m_features
.packet_support (PACKET_QThreadOptions
) != PACKET_ENABLE
)
15157 char *p
= rs
->buf
.data ();
15158 char *endp
= p
+ get_remote_packet_size ();
15160 /* Clear options for all threads by default. Note that unlike
15161 vCont, the rightmost options that match a thread apply, so we
15162 don't have to worry about whether we can use wildcard ptids. */
15163 strcpy (p
, "QThreadOptions;0");
15166 /* Send the QThreadOptions packet stored in P. */
15167 auto flush
= [&] ()
15172 getpkt (&rs
->buf
, 0);
15174 switch (m_features
.packet_ok (rs
->buf
, PACKET_QThreadOptions
))
15177 if (strcmp (rs
->buf
.data (), "OK") != 0)
15178 error (_("Remote refused setting thread options: %s"), rs
->buf
.data ());
15181 error (_("Remote failure reply: %s"), rs
->buf
.data ());
15182 case PACKET_UNKNOWN
:
15183 gdb_assert_not_reached ("PACKET_UNKNOWN");
15188 /* Prepare P for another QThreadOptions packet. */
15189 auto restart
= [&] ()
15191 p
= rs
->buf
.data ();
15192 strcpy (p
, "QThreadOptions");
15196 /* Now set non-zero options for threads that need them. We don't
15197 bother with the case of all threads of a process wanting the same
15198 non-zero options as that's not an expected scenario. */
15199 for (thread_info
*tp
: all_non_exited_threads (this))
15201 gdb_thread_options options
= tp
->thread_options ();
15206 /* It might be possible to we have more threads with options
15207 than can fit a single QThreadOptions packet. So build each
15208 options/thread pair in this separate buffer to make sure it
15210 constexpr size_t max_options_size
= 100;
15211 char obuf
[max_options_size
];
15212 char *obuf_p
= obuf
;
15213 char *obuf_endp
= obuf
+ max_options_size
;
15216 obuf_p
+= xsnprintf (obuf_p
, obuf_endp
- obuf_p
, "%s",
15217 phex_nz (options
, sizeof (options
)));
15218 if (tp
->ptid
!= magic_null_ptid
)
15221 obuf_p
= write_ptid (obuf_p
, obuf_endp
, tp
->ptid
);
15224 size_t osize
= obuf_p
- obuf
;
15225 if (osize
> endp
- p
)
15227 /* This new options/thread pair doesn't fit the packet
15228 buffer. Send what we have already. */
15232 /* Should now fit. */
15233 gdb_assert (osize
<= endp
- p
);
15236 memcpy (p
, obuf
, osize
);
15244 show_remote_cmd (const char *args
, int from_tty
)
15246 /* We can't just use cmd_show_list here, because we want to skip
15247 the redundant "show remote Z-packet" and the legacy aliases. */
15248 struct cmd_list_element
*list
= remote_show_cmdlist
;
15249 struct ui_out
*uiout
= current_uiout
;
15251 ui_out_emit_tuple
tuple_emitter (uiout
, "showlist");
15252 for (; list
!= NULL
; list
= list
->next
)
15253 if (strcmp (list
->name
, "Z-packet") == 0)
15255 else if (list
->type
== not_set_cmd
)
15256 /* Alias commands are exactly like the original, except they
15257 don't have the normal type. */
15261 ui_out_emit_tuple
option_emitter (uiout
, "option");
15263 uiout
->field_string ("name", list
->name
);
15264 uiout
->text (": ");
15265 if (list
->type
== show_cmd
)
15266 do_show_command (NULL
, from_tty
, list
);
15268 cmd_func (list
, NULL
, from_tty
);
15272 /* Some change happened in PSPACE's objfile list (obfiles added or removed),
15273 offer all inferiors using that program space a change to look up symbols. */
15276 remote_objfile_changed_check_symbols (program_space
*pspace
)
15278 /* The affected program space is possibly shared by multiple inferiors.
15279 Consider sending a qSymbol packet for each of the inferiors using that
15281 for (inferior
*inf
: all_inferiors ())
15283 if (inf
->pspace
!= pspace
)
15286 /* Check whether the inferior's process target is a remote target. */
15287 remote_target
*remote
= as_remote_target (inf
->process_target ());
15288 if (remote
== nullptr)
15291 /* When we are attaching or handling a fork child and the shared library
15292 subsystem reads the list of loaded libraries, we receive new objfile
15293 events in between each found library. The libraries are read in an
15294 undefined order, so if we gave the remote side a chance to look up
15295 symbols between each objfile, we might give it an inconsistent picture
15296 of the inferior. It could appear that a library A appears loaded but
15297 a library B does not, even though library A requires library B. That
15298 would present a state that couldn't normally exist in the inferior.
15300 So, skip these events, we'll give the remote a chance to look up
15301 symbols once all the loaded libraries and their symbols are known to
15303 if (inf
->in_initial_library_scan
)
15306 if (!remote
->has_execution (inf
))
15309 /* Need to switch to a specific thread, because remote_check_symbols will
15310 set the general thread using INFERIOR_PTID.
15312 It's possible to have inferiors with no thread here, because we are
15313 called very early in the connection process, while the inferior is
15314 being set up, before threads are added. Just skip it, start_remote_1
15315 also calls remote_check_symbols when it's done setting things up. */
15316 thread_info
*thread
= any_thread_of_inferior (inf
);
15317 if (thread
!= nullptr)
15319 scoped_restore_current_thread restore_thread
;
15320 switch_to_thread (thread
);
15321 remote
->remote_check_symbols ();
15326 /* Function to be called whenever a new objfile (shlib) is detected. */
15329 remote_new_objfile (struct objfile
*objfile
)
15331 remote_objfile_changed_check_symbols (objfile
->pspace
);
15334 /* Pull all the tracepoints defined on the target and create local
15335 data structures representing them. We don't want to create real
15336 tracepoints yet, we don't want to mess up the user's existing
15340 remote_target::upload_tracepoints (struct uploaded_tp
**utpp
)
15342 struct remote_state
*rs
= get_remote_state ();
15345 /* Ask for a first packet of tracepoint definition. */
15348 p
= rs
->buf
.data ();
15349 while (*p
&& *p
!= 'l')
15351 parse_tracepoint_definition (p
, utpp
);
15352 /* Ask for another packet of tracepoint definition. */
15355 p
= rs
->buf
.data ();
15361 remote_target::upload_trace_state_variables (struct uploaded_tsv
**utsvp
)
15363 struct remote_state
*rs
= get_remote_state ();
15366 /* Ask for a first packet of variable definition. */
15369 p
= rs
->buf
.data ();
15370 while (*p
&& *p
!= 'l')
15372 parse_tsv_definition (p
, utsvp
);
15373 /* Ask for another packet of variable definition. */
15376 p
= rs
->buf
.data ();
15381 /* The "set/show range-stepping" show hook. */
15384 show_range_stepping (struct ui_file
*file
, int from_tty
,
15385 struct cmd_list_element
*c
,
15389 _("Debugger's willingness to use range stepping "
15390 "is %s.\n"), value
);
15393 /* Return true if the vCont;r action is supported by the remote
15397 remote_target::vcont_r_supported ()
15399 return (m_features
.packet_support (PACKET_vCont
) == PACKET_ENABLE
15400 && get_remote_state ()->supports_vCont
.r
);
15403 /* The "set/show range-stepping" set hook. */
15406 set_range_stepping (const char *ignore_args
, int from_tty
,
15407 struct cmd_list_element
*c
)
15409 /* When enabling, check whether range stepping is actually supported
15410 by the target, and warn if not. */
15411 if (use_range_stepping
)
15413 remote_target
*remote
= get_current_remote_target ();
15415 || !remote
->vcont_r_supported ())
15416 warning (_("Range stepping is not supported by the current target"));
15421 show_remote_debug (struct ui_file
*file
, int from_tty
,
15422 struct cmd_list_element
*c
, const char *value
)
15424 gdb_printf (file
, _("Debugging of remote protocol is %s.\n"),
15429 show_remote_timeout (struct ui_file
*file
, int from_tty
,
15430 struct cmd_list_element
*c
, const char *value
)
15433 _("Timeout limit to wait for target to respond is %s.\n"),
15437 /* Implement the "supports_memory_tagging" target_ops method. */
15440 remote_target::supports_memory_tagging ()
15442 return m_features
.remote_memory_tagging_p ();
15445 /* Create the qMemTags packet given ADDRESS, LEN and TYPE. */
15448 create_fetch_memtags_request (gdb::char_vector
&packet
, CORE_ADDR address
,
15449 size_t len
, int type
)
15451 int addr_size
= gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
15453 std::string request
= string_printf ("qMemTags:%s,%s:%s",
15454 phex_nz (address
, addr_size
),
15455 phex_nz (len
, sizeof (len
)),
15456 phex_nz (type
, sizeof (type
)));
15458 strcpy (packet
.data (), request
.c_str ());
15461 /* Parse the qMemTags packet reply into TAGS.
15463 Return true if successful, false otherwise. */
15466 parse_fetch_memtags_reply (const gdb::char_vector
&reply
,
15467 gdb::byte_vector
&tags
)
15469 if (reply
.empty () || reply
[0] == 'E' || reply
[0] != 'm')
15472 /* Copy the tag data. */
15473 tags
= hex2bin (reply
.data () + 1);
15478 /* Create the QMemTags packet given ADDRESS, LEN, TYPE and TAGS. */
15481 create_store_memtags_request (gdb::char_vector
&packet
, CORE_ADDR address
,
15482 size_t len
, int type
,
15483 const gdb::byte_vector
&tags
)
15485 int addr_size
= gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
15487 /* Put together the main packet, address and length. */
15488 std::string request
= string_printf ("QMemTags:%s,%s:%s:",
15489 phex_nz (address
, addr_size
),
15490 phex_nz (len
, sizeof (len
)),
15491 phex_nz (type
, sizeof (type
)));
15492 request
+= bin2hex (tags
.data (), tags
.size ());
15494 /* Check if we have exceeded the maximum packet size. */
15495 if (packet
.size () < request
.length ())
15496 error (_("Contents too big for packet QMemTags."));
15498 strcpy (packet
.data (), request
.c_str ());
15501 /* Implement the "fetch_memtags" target_ops method. */
15504 remote_target::fetch_memtags (CORE_ADDR address
, size_t len
,
15505 gdb::byte_vector
&tags
, int type
)
15507 /* Make sure the qMemTags packet is supported. */
15508 if (!m_features
.remote_memory_tagging_p ())
15509 gdb_assert_not_reached ("remote fetch_memtags called with packet disabled");
15511 struct remote_state
*rs
= get_remote_state ();
15513 create_fetch_memtags_request (rs
->buf
, address
, len
, type
);
15518 return parse_fetch_memtags_reply (rs
->buf
, tags
);
15521 /* Implement the "store_memtags" target_ops method. */
15524 remote_target::store_memtags (CORE_ADDR address
, size_t len
,
15525 const gdb::byte_vector
&tags
, int type
)
15527 /* Make sure the QMemTags packet is supported. */
15528 if (!m_features
.remote_memory_tagging_p ())
15529 gdb_assert_not_reached ("remote store_memtags called with packet disabled");
15531 struct remote_state
*rs
= get_remote_state ();
15533 create_store_memtags_request (rs
->buf
, address
, len
, type
, tags
);
15538 /* Verify if the request was successful. */
15539 return packet_check_result (rs
->buf
.data ()) == PACKET_OK
;
15542 /* Return true if remote target T is non-stop. */
15545 remote_target_is_non_stop_p (remote_target
*t
)
15547 scoped_restore_current_thread restore_thread
;
15548 switch_to_target_no_thread (t
);
15550 return target_is_non_stop_p ();
15555 namespace selftests
{
15558 test_memory_tagging_functions ()
15560 remote_target remote
;
15562 struct packet_config
*config
15563 = &remote
.m_features
.m_protocol_packets
[PACKET_memory_tagging_feature
];
15565 scoped_restore restore_memtag_support_
15566 = make_scoped_restore (&config
->support
);
15568 /* Test memory tagging packet support. */
15569 config
->support
= PACKET_SUPPORT_UNKNOWN
;
15570 SELF_CHECK (remote
.supports_memory_tagging () == false);
15571 config
->support
= PACKET_DISABLE
;
15572 SELF_CHECK (remote
.supports_memory_tagging () == false);
15573 config
->support
= PACKET_ENABLE
;
15574 SELF_CHECK (remote
.supports_memory_tagging () == true);
15576 /* Setup testing. */
15577 gdb::char_vector packet
;
15578 gdb::byte_vector tags
, bv
;
15579 std::string expected
, reply
;
15580 packet
.resize (32000);
15582 /* Test creating a qMemTags request. */
15584 expected
= "qMemTags:0,0:0";
15585 create_fetch_memtags_request (packet
, 0x0, 0x0, 0);
15586 SELF_CHECK (strcmp (packet
.data (), expected
.c_str ()) == 0);
15588 expected
= "qMemTags:deadbeef,10:1";
15589 create_fetch_memtags_request (packet
, 0xdeadbeef, 16, 1);
15590 SELF_CHECK (strcmp (packet
.data (), expected
.c_str ()) == 0);
15592 /* Test parsing a qMemTags reply. */
15594 /* Error reply, tags vector unmodified. */
15596 strcpy (packet
.data (), reply
.c_str ());
15598 SELF_CHECK (parse_fetch_memtags_reply (packet
, tags
) == false);
15599 SELF_CHECK (tags
.size () == 0);
15601 /* Valid reply, tags vector updated. */
15605 for (int i
= 0; i
< 5; i
++)
15608 reply
= "m" + bin2hex (bv
.data (), bv
.size ());
15609 strcpy (packet
.data (), reply
.c_str ());
15611 SELF_CHECK (parse_fetch_memtags_reply (packet
, tags
) == true);
15612 SELF_CHECK (tags
.size () == 5);
15614 for (int i
= 0; i
< 5; i
++)
15615 SELF_CHECK (tags
[i
] == i
);
15617 /* Test creating a QMemTags request. */
15619 /* Empty tag data. */
15621 expected
= "QMemTags:0,0:0:";
15622 create_store_memtags_request (packet
, 0x0, 0x0, 0, tags
);
15623 SELF_CHECK (memcmp (packet
.data (), expected
.c_str (),
15624 expected
.length ()) == 0);
15626 /* Non-empty tag data. */
15628 for (int i
= 0; i
< 5; i
++)
15629 tags
.push_back (i
);
15630 expected
= "QMemTags:deadbeef,ff:1:0001020304";
15631 create_store_memtags_request (packet
, 0xdeadbeef, 255, 1, tags
);
15632 SELF_CHECK (memcmp (packet
.data (), expected
.c_str (),
15633 expected
.length ()) == 0);
15636 } // namespace selftests
15637 #endif /* GDB_SELF_TEST */
15639 void _initialize_remote ();
15641 _initialize_remote ()
15643 add_target (remote_target_info
, remote_target::open
);
15644 add_target (extended_remote_target_info
, extended_remote_target::open
);
15646 /* Hook into new objfile notification. */
15647 gdb::observers::new_objfile
.attach (remote_new_objfile
, "remote");
15648 gdb::observers::all_objfiles_removed
.attach
15649 (remote_objfile_changed_check_symbols
, "remote");
15652 init_remote_threadtests ();
15655 /* set/show remote ... */
15657 add_basic_prefix_cmd ("remote", class_maintenance
, _("\
15658 Remote protocol specific variables.\n\
15659 Configure various remote-protocol specific variables such as\n\
15660 the packets being used."),
15661 &remote_set_cmdlist
,
15662 0 /* allow-unknown */, &setlist
);
15663 add_prefix_cmd ("remote", class_maintenance
, show_remote_cmd
, _("\
15664 Remote protocol specific variables.\n\
15665 Configure various remote-protocol specific variables such as\n\
15666 the packets being used."),
15667 &remote_show_cmdlist
,
15668 0 /* allow-unknown */, &showlist
);
15670 add_cmd ("compare-sections", class_obscure
, compare_sections_command
, _("\
15671 Compare section data on target to the exec file.\n\
15672 Argument is a single section name (default: all loaded sections).\n\
15673 To compare only read-only loaded sections, specify the -r option."),
15676 add_cmd ("packet", class_maintenance
, cli_packet_command
, _("\
15677 Send an arbitrary packet to a remote target.\n\
15678 maintenance packet TEXT\n\
15679 If GDB is talking to an inferior via the GDB serial protocol, then\n\
15680 this command sends the string TEXT to the inferior, and displays the\n\
15681 response packet. GDB supplies the initial `$' character, and the\n\
15682 terminating `#' character and checksum."),
15685 set_show_commands remotebreak_cmds
15686 = add_setshow_boolean_cmd ("remotebreak", no_class
, &remote_break
, _("\
15687 Set whether to send break if interrupted."), _("\
15688 Show whether to send break if interrupted."), _("\
15689 If set, a break, instead of a cntrl-c, is sent to the remote target."),
15690 set_remotebreak
, show_remotebreak
,
15691 &setlist
, &showlist
);
15692 deprecate_cmd (remotebreak_cmds
.set
, "set remote interrupt-sequence");
15693 deprecate_cmd (remotebreak_cmds
.show
, "show remote interrupt-sequence");
15695 add_setshow_enum_cmd ("interrupt-sequence", class_support
,
15696 interrupt_sequence_modes
, &interrupt_sequence_mode
,
15698 Set interrupt sequence to remote target."), _("\
15699 Show interrupt sequence to remote target."), _("\
15700 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
15701 NULL
, show_interrupt_sequence
,
15702 &remote_set_cmdlist
,
15703 &remote_show_cmdlist
);
15705 add_setshow_boolean_cmd ("interrupt-on-connect", class_support
,
15706 &interrupt_on_connect
, _("\
15707 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
15708 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
15709 If set, interrupt sequence is sent to remote target."),
15711 &remote_set_cmdlist
, &remote_show_cmdlist
);
15713 /* Install commands for configuring memory read/write packets. */
15715 add_cmd ("remotewritesize", no_class
, set_memory_write_packet_size
, _("\
15716 Set the maximum number of bytes per memory write packet (deprecated)."),
15718 add_cmd ("remotewritesize", no_class
, show_memory_write_packet_size
, _("\
15719 Show the maximum number of bytes per memory write packet (deprecated)."),
15721 add_cmd ("memory-write-packet-size", no_class
,
15722 set_memory_write_packet_size
, _("\
15723 Set the maximum number of bytes per memory-write packet.\n\
15724 Specify the number of bytes in a packet or 0 (zero) for the\n\
15725 default packet size. The actual limit is further reduced\n\
15726 dependent on the target. Specify \"fixed\" to disable the\n\
15727 further restriction and \"limit\" to enable that restriction."),
15728 &remote_set_cmdlist
);
15729 add_cmd ("memory-read-packet-size", no_class
,
15730 set_memory_read_packet_size
, _("\
15731 Set the maximum number of bytes per memory-read packet.\n\
15732 Specify the number of bytes in a packet or 0 (zero) for the\n\
15733 default packet size. The actual limit is further reduced\n\
15734 dependent on the target. Specify \"fixed\" to disable the\n\
15735 further restriction and \"limit\" to enable that restriction."),
15736 &remote_set_cmdlist
);
15737 add_cmd ("memory-write-packet-size", no_class
,
15738 show_memory_write_packet_size
,
15739 _("Show the maximum number of bytes per memory-write packet."),
15740 &remote_show_cmdlist
);
15741 add_cmd ("memory-read-packet-size", no_class
,
15742 show_memory_read_packet_size
,
15743 _("Show the maximum number of bytes per memory-read packet."),
15744 &remote_show_cmdlist
);
15746 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-limit", no_class
,
15747 &remote_hw_watchpoint_limit
, _("\
15748 Set the maximum number of target hardware watchpoints."), _("\
15749 Show the maximum number of target hardware watchpoints."), _("\
15750 Specify \"unlimited\" for unlimited hardware watchpoints."),
15751 NULL
, show_hardware_watchpoint_limit
,
15752 &remote_set_cmdlist
,
15753 &remote_show_cmdlist
);
15754 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-length-limit",
15756 &remote_hw_watchpoint_length_limit
, _("\
15757 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
15758 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
15759 Specify \"unlimited\" to allow watchpoints of unlimited size."),
15760 NULL
, show_hardware_watchpoint_length_limit
,
15761 &remote_set_cmdlist
, &remote_show_cmdlist
);
15762 add_setshow_zuinteger_unlimited_cmd ("hardware-breakpoint-limit", no_class
,
15763 &remote_hw_breakpoint_limit
, _("\
15764 Set the maximum number of target hardware breakpoints."), _("\
15765 Show the maximum number of target hardware breakpoints."), _("\
15766 Specify \"unlimited\" for unlimited hardware breakpoints."),
15767 NULL
, show_hardware_breakpoint_limit
,
15768 &remote_set_cmdlist
, &remote_show_cmdlist
);
15770 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure
,
15771 &remote_address_size
, _("\
15772 Set the maximum size of the address (in bits) in a memory packet."), _("\
15773 Show the maximum size of the address (in bits) in a memory packet."), NULL
,
15775 NULL
, /* FIXME: i18n: */
15776 &setlist
, &showlist
);
15778 init_all_packet_configs ();
15780 add_packet_config_cmd (PACKET_X
, "X", "binary-download", 1);
15782 add_packet_config_cmd (PACKET_vCont
, "vCont", "verbose-resume", 0);
15784 add_packet_config_cmd (PACKET_QPassSignals
, "QPassSignals", "pass-signals",
15787 add_packet_config_cmd (PACKET_QCatchSyscalls
, "QCatchSyscalls",
15788 "catch-syscalls", 0);
15790 add_packet_config_cmd (PACKET_QProgramSignals
, "QProgramSignals",
15791 "program-signals", 0);
15793 add_packet_config_cmd (PACKET_QSetWorkingDir
, "QSetWorkingDir",
15794 "set-working-dir", 0);
15796 add_packet_config_cmd (PACKET_QStartupWithShell
, "QStartupWithShell",
15797 "startup-with-shell", 0);
15799 add_packet_config_cmd (PACKET_QEnvironmentHexEncoded
,"QEnvironmentHexEncoded",
15800 "environment-hex-encoded", 0);
15802 add_packet_config_cmd (PACKET_QEnvironmentReset
, "QEnvironmentReset",
15803 "environment-reset", 0);
15805 add_packet_config_cmd (PACKET_QEnvironmentUnset
, "QEnvironmentUnset",
15806 "environment-unset", 0);
15808 add_packet_config_cmd (PACKET_qSymbol
, "qSymbol", "symbol-lookup", 0);
15810 add_packet_config_cmd (PACKET_P
, "P", "set-register", 1);
15812 add_packet_config_cmd (PACKET_p
, "p", "fetch-register", 1);
15814 add_packet_config_cmd (PACKET_Z0
, "Z0", "software-breakpoint", 0);
15816 add_packet_config_cmd (PACKET_Z1
, "Z1", "hardware-breakpoint", 0);
15818 add_packet_config_cmd (PACKET_Z2
, "Z2", "write-watchpoint", 0);
15820 add_packet_config_cmd (PACKET_Z3
, "Z3", "read-watchpoint", 0);
15822 add_packet_config_cmd (PACKET_Z4
, "Z4", "access-watchpoint", 0);
15824 add_packet_config_cmd (PACKET_qXfer_auxv
, "qXfer:auxv:read",
15825 "read-aux-vector", 0);
15827 add_packet_config_cmd (PACKET_qXfer_exec_file
, "qXfer:exec-file:read",
15828 "pid-to-exec-file", 0);
15830 add_packet_config_cmd (PACKET_qXfer_features
,
15831 "qXfer:features:read", "target-features", 0);
15833 add_packet_config_cmd (PACKET_qXfer_libraries
, "qXfer:libraries:read",
15834 "library-info", 0);
15836 add_packet_config_cmd (PACKET_qXfer_libraries_svr4
,
15837 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
15839 add_packet_config_cmd (PACKET_qXfer_memory_map
, "qXfer:memory-map:read",
15842 add_packet_config_cmd (PACKET_qXfer_osdata
, "qXfer:osdata:read", "osdata", 0);
15844 add_packet_config_cmd (PACKET_qXfer_threads
, "qXfer:threads:read", "threads",
15847 add_packet_config_cmd (PACKET_qXfer_siginfo_read
, "qXfer:siginfo:read",
15848 "read-siginfo-object", 0);
15850 add_packet_config_cmd (PACKET_qXfer_siginfo_write
, "qXfer:siginfo:write",
15851 "write-siginfo-object", 0);
15853 add_packet_config_cmd (PACKET_qXfer_traceframe_info
,
15854 "qXfer:traceframe-info:read", "traceframe-info", 0);
15856 add_packet_config_cmd (PACKET_qXfer_uib
, "qXfer:uib:read",
15857 "unwind-info-block", 0);
15859 add_packet_config_cmd (PACKET_qGetTLSAddr
, "qGetTLSAddr",
15860 "get-thread-local-storage-address", 0);
15862 add_packet_config_cmd (PACKET_qGetTIBAddr
, "qGetTIBAddr",
15863 "get-thread-information-block-address", 0);
15865 add_packet_config_cmd (PACKET_bc
, "bc", "reverse-continue", 0);
15867 add_packet_config_cmd (PACKET_bs
, "bs", "reverse-step", 0);
15869 add_packet_config_cmd (PACKET_qSupported
, "qSupported", "supported-packets",
15872 add_packet_config_cmd (PACKET_qSearch_memory
, "qSearch:memory",
15873 "search-memory", 0);
15875 add_packet_config_cmd (PACKET_qTStatus
, "qTStatus", "trace-status", 0);
15877 add_packet_config_cmd (PACKET_vFile_setfs
, "vFile:setfs", "hostio-setfs", 0);
15879 add_packet_config_cmd (PACKET_vFile_open
, "vFile:open", "hostio-open", 0);
15881 add_packet_config_cmd (PACKET_vFile_pread
, "vFile:pread", "hostio-pread", 0);
15883 add_packet_config_cmd (PACKET_vFile_pwrite
, "vFile:pwrite", "hostio-pwrite",
15886 add_packet_config_cmd (PACKET_vFile_close
, "vFile:close", "hostio-close", 0);
15888 add_packet_config_cmd (PACKET_vFile_unlink
, "vFile:unlink", "hostio-unlink",
15891 add_packet_config_cmd (PACKET_vFile_readlink
, "vFile:readlink",
15892 "hostio-readlink", 0);
15894 add_packet_config_cmd (PACKET_vFile_fstat
, "vFile:fstat", "hostio-fstat", 0);
15896 add_packet_config_cmd (PACKET_vAttach
, "vAttach", "attach", 0);
15898 add_packet_config_cmd (PACKET_vRun
, "vRun", "run", 0);
15900 add_packet_config_cmd (PACKET_QStartNoAckMode
, "QStartNoAckMode", "noack", 0);
15902 add_packet_config_cmd (PACKET_vKill
, "vKill", "kill", 0);
15904 add_packet_config_cmd (PACKET_qAttached
, "qAttached", "query-attached", 0);
15906 add_packet_config_cmd (PACKET_ConditionalTracepoints
,
15907 "ConditionalTracepoints", "conditional-tracepoints",
15910 add_packet_config_cmd (PACKET_ConditionalBreakpoints
,
15911 "ConditionalBreakpoints", "conditional-breakpoints",
15914 add_packet_config_cmd (PACKET_BreakpointCommands
, "BreakpointCommands",
15915 "breakpoint-commands", 0);
15917 add_packet_config_cmd (PACKET_FastTracepoints
, "FastTracepoints",
15918 "fast-tracepoints", 0);
15920 add_packet_config_cmd (PACKET_TracepointSource
, "TracepointSource",
15921 "TracepointSource", 0);
15923 add_packet_config_cmd (PACKET_QAllow
, "QAllow", "allow", 0);
15925 add_packet_config_cmd (PACKET_StaticTracepoints
, "StaticTracepoints",
15926 "static-tracepoints", 0);
15928 add_packet_config_cmd (PACKET_InstallInTrace
, "InstallInTrace",
15929 "install-in-trace", 0);
15931 add_packet_config_cmd (PACKET_qXfer_statictrace_read
,
15932 "qXfer:statictrace:read", "read-sdata-object", 0);
15934 add_packet_config_cmd (PACKET_qXfer_fdpic
, "qXfer:fdpic:read",
15935 "read-fdpic-loadmap", 0);
15937 add_packet_config_cmd (PACKET_QDisableRandomization
, "QDisableRandomization",
15938 "disable-randomization", 0);
15940 add_packet_config_cmd (PACKET_QAgent
, "QAgent", "agent", 0);
15942 add_packet_config_cmd (PACKET_QTBuffer_size
, "QTBuffer:size",
15943 "trace-buffer-size", 0);
15945 add_packet_config_cmd (PACKET_Qbtrace_off
, "Qbtrace:off", "disable-btrace",
15948 add_packet_config_cmd (PACKET_Qbtrace_bts
, "Qbtrace:bts", "enable-btrace-bts",
15951 add_packet_config_cmd (PACKET_Qbtrace_pt
, "Qbtrace:pt", "enable-btrace-pt",
15954 add_packet_config_cmd (PACKET_qXfer_btrace
, "qXfer:btrace", "read-btrace", 0);
15956 add_packet_config_cmd (PACKET_qXfer_btrace_conf
, "qXfer:btrace-conf",
15957 "read-btrace-conf", 0);
15959 add_packet_config_cmd (PACKET_Qbtrace_conf_bts_size
, "Qbtrace-conf:bts:size",
15960 "btrace-conf-bts-size", 0);
15962 add_packet_config_cmd (PACKET_multiprocess_feature
, "multiprocess-feature",
15963 "multiprocess-feature", 0);
15965 add_packet_config_cmd (PACKET_swbreak_feature
, "swbreak-feature",
15966 "swbreak-feature", 0);
15968 add_packet_config_cmd (PACKET_hwbreak_feature
, "hwbreak-feature",
15969 "hwbreak-feature", 0);
15971 add_packet_config_cmd (PACKET_fork_event_feature
, "fork-event-feature",
15972 "fork-event-feature", 0);
15974 add_packet_config_cmd (PACKET_vfork_event_feature
, "vfork-event-feature",
15975 "vfork-event-feature", 0);
15977 add_packet_config_cmd (PACKET_Qbtrace_conf_pt_size
, "Qbtrace-conf:pt:size",
15978 "btrace-conf-pt-size", 0);
15980 add_packet_config_cmd (PACKET_vContSupported
, "vContSupported",
15981 "verbose-resume-supported", 0);
15983 add_packet_config_cmd (PACKET_exec_event_feature
, "exec-event-feature",
15984 "exec-event-feature", 0);
15986 add_packet_config_cmd (PACKET_vCtrlC
, "vCtrlC", "ctrl-c", 0);
15988 add_packet_config_cmd (PACKET_QThreadEvents
, "QThreadEvents", "thread-events",
15991 add_packet_config_cmd (PACKET_QThreadOptions
, "QThreadOptions",
15992 "thread-options", 0);
15994 add_packet_config_cmd (PACKET_no_resumed
, "N stop reply",
15995 "no-resumed-stop-reply", 0);
15997 add_packet_config_cmd (PACKET_memory_tagging_feature
,
15998 "memory-tagging-feature", "memory-tagging-feature", 0);
16000 /* Assert that we've registered "set remote foo-packet" commands
16001 for all packet configs. */
16005 for (i
= 0; i
< PACKET_MAX
; i
++)
16007 /* Ideally all configs would have a command associated. Some
16008 still don't though. */
16013 case PACKET_QNonStop
:
16014 case PACKET_EnableDisableTracepoints_feature
:
16015 case PACKET_tracenz_feature
:
16016 case PACKET_DisconnectedTracing_feature
:
16017 case PACKET_augmented_libraries_svr4_read_feature
:
16019 /* Additions to this list need to be well justified:
16020 pre-existing packets are OK; new packets are not. */
16028 /* This catches both forgetting to add a config command, and
16029 forgetting to remove a packet from the exception list. */
16030 gdb_assert (excepted
== (packets_descriptions
[i
].name
== NULL
));
16034 /* Keep the old ``set remote Z-packet ...'' working. Each individual
16035 Z sub-packet has its own set and show commands, but users may
16036 have sets to this variable in their .gdbinit files (or in their
16038 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure
,
16039 &remote_Z_packet_detect
, _("\
16040 Set use of remote protocol `Z' packets."), _("\
16041 Show use of remote protocol `Z' packets."), _("\
16042 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
16044 set_remote_protocol_Z_packet_cmd
,
16045 show_remote_protocol_Z_packet_cmd
,
16046 /* FIXME: i18n: Use of remote protocol
16047 `Z' packets is %s. */
16048 &remote_set_cmdlist
, &remote_show_cmdlist
);
16050 add_basic_prefix_cmd ("remote", class_files
, _("\
16051 Manipulate files on the remote system.\n\
16052 Transfer files to and from the remote target system."),
16054 0 /* allow-unknown */, &cmdlist
);
16056 add_cmd ("put", class_files
, remote_put_command
,
16057 _("Copy a local file to the remote system."),
16060 add_cmd ("get", class_files
, remote_get_command
,
16061 _("Copy a remote file to the local system."),
16064 add_cmd ("delete", class_files
, remote_delete_command
,
16065 _("Delete a remote file."),
16068 add_setshow_string_noescape_cmd ("exec-file", class_files
,
16069 &remote_exec_file_var
, _("\
16070 Set the remote pathname for \"run\"."), _("\
16071 Show the remote pathname for \"run\"."), NULL
,
16072 set_remote_exec_file
,
16073 show_remote_exec_file
,
16074 &remote_set_cmdlist
,
16075 &remote_show_cmdlist
);
16077 add_setshow_boolean_cmd ("range-stepping", class_run
,
16078 &use_range_stepping
, _("\
16079 Enable or disable range stepping."), _("\
16080 Show whether target-assisted range stepping is enabled."), _("\
16081 If on, and the target supports it, when stepping a source line, GDB\n\
16082 tells the target to step the corresponding range of addresses itself instead\n\
16083 of issuing multiple single-steps. This speeds up source level\n\
16084 stepping. If off, GDB always issues single-steps, even if range\n\
16085 stepping is supported by the target. The default is on."),
16086 set_range_stepping
,
16087 show_range_stepping
,
16091 add_setshow_zinteger_cmd ("watchdog", class_maintenance
, &watchdog
, _("\
16092 Set watchdog timer."), _("\
16093 Show watchdog timer."), _("\
16094 When non-zero, this timeout is used instead of waiting forever for a target\n\
16095 to finish a low-level step or continue operation. If the specified amount\n\
16096 of time passes without a response from the target, an error occurs."),
16099 &setlist
, &showlist
);
16101 add_setshow_zuinteger_unlimited_cmd ("remote-packet-max-chars", no_class
,
16102 &remote_packet_max_chars
, _("\
16103 Set the maximum number of characters to display for each remote packet."), _("\
16104 Show the maximum number of characters to display for each remote packet."), _("\
16105 Specify \"unlimited\" to display all the characters."),
16106 NULL
, show_remote_packet_max_chars
,
16107 &setdebuglist
, &showdebuglist
);
16109 add_setshow_boolean_cmd ("remote", no_class
, &remote_debug
,
16110 _("Set debugging of remote protocol."),
16111 _("Show debugging of remote protocol."),
16113 When enabled, each packet sent or received with the remote target\n\
16117 &setdebuglist
, &showdebuglist
);
16119 add_setshow_zuinteger_unlimited_cmd ("remotetimeout", no_class
,
16120 &remote_timeout
, _("\
16121 Set timeout limit to wait for target to respond."), _("\
16122 Show timeout limit to wait for target to respond."), _("\
16123 This value is used to set the time limit for gdb to wait for a response\n\
16124 from the target."),
16126 show_remote_timeout
,
16127 &setlist
, &showlist
);
16129 /* Eventually initialize fileio. See fileio.c */
16130 initialize_remote_fileio (&remote_set_cmdlist
, &remote_show_cmdlist
);
16133 selftests::register_test ("remote_memory_tagging",
16134 selftests::test_memory_tagging_functions
);